Last active
October 12, 2017 08:52
-
-
Save dmitriy-kiriyenko/84b56b53cd644b88781cbaa21f889502 to your computer and use it in GitHub Desktop.
Nested hash for nested group by
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def base_for_nested_group_by(x) | |
end | |
# f(0) | |
Hash.new # or ArgumentError | |
# f(1) | |
Hash.new {|h1, k1| h1[k1] = []} | |
# f(2) | |
Hash.new{|h1,k1| h1[k1] = Hash.new{|h2,k2| h2[k2] = []}} | |
# f(3) | |
Hash.new{|h1,k1| h1[k1] = Hash.new{|h2,k2| h2[k2] = Hash.new{|h3,k3| h3[k3] = []}}} | |
# ... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def base_for_nested_group_by(n) | |
def nested_hash_source_code(n) | |
raise ArgumentError.new('Give a positive integer') if n < 1 | |
return "Hash.new {|h#{n},k#{n}|h#{n}[k#{n}] = [] }" if n == 1 | |
"Hash.new {|h#{n},k#{n}| h#{n}[k#{n}] = #{nested_hash_source_code(n-1)} }" | |
end | |
eval nested_hash_source_code(n.to_i) | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def base_for_nested_group_by(n) | |
raise ArgumentError.new('Give a positive integer') if n < 1 | |
return Hash.new { |h, k| h[k] = [] } if n == 1 | |
Hash.new {|h, k| h[k] = base_for_nested_group_by(n-1) } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment