Reputation: 2145
Hi all I've made myself quite a complicated (at least, for me) construction. I have a Hash, looking like (example):
states_with_depths = {
#State => depth
"S0" => 0,
"S1" => 1,
"S2" => 2,
"S3" => 2,
"S4" => 2,
"S5" => 3
}
(note: its a Hash, so its not sorted yet)
Now what I would like: Having a loop starting at depth = 0 with a set of all states having depth 0 or less, next iteration of the loop, having a set of all states with depth 1 or less, etc.
What would be a neat way to get such a construction?
Please let me know if my question is unclear.
Upvotes: 1
Views: 353
Reputation: 303224
Here's a variation that works for Ruby before 1.8.7 (when Enumerable#group_by
was added):
states_by_depth = Hash.new{|h,depth| h[depth]=[] }
states_with_depths.each{ |state,depth| states_by_depth[depth] << state }
#=> {0=>["S0"], 1=>["S1"], 2=>["S3", "S4", "S2"], 3=>["S5"]}
min_depth = states_by_depth.keys.min
max_depth = states_by_depth.keys.max
min_depth.upto(max_depth) do |depth|
next unless states = states_by_depth[depth]
puts "Depth: #{depth}"
states.each{ |state| puts "..#{state}" }
end
#=> Depth: 0
#=> ..S0
#=> Depth: 1
#=> ..S1
#=> Depth: 2
#=> ..S3
#=> ..S4
#=> ..S2
#=> Depth: 3
#=> ..S5
Upvotes: 1
Reputation: 9177
require 'set'
depths_with_states = []
max_level = states_with_depths.max_by{|e|e[1]}[1]
states_with_depths.map{ |state, level|
(level..max_level).each{ |i|
depths_with_states[i] ||= Set.new # ...or just array
depths_with_states[i] << state
}
}
depths_with_states.each{ |states|
# do whatever you want to do ;)
}
Upvotes: 1
Reputation: 66837
You can just use group_by
with the value:
>> states_with_depths.group_by { |k,v| v }
#=> {0=>[["S0", 0]], 1=>[["S1", 1]], 2=>[["S2", 2], ["S3", 2], ["S4", 2]], 3=>[["S5", 3]]}
This can also be shortened to:
states_with_depths.group_by(&:last)
To use this you can do something like:
states_with_depths.group_by(&:last).each do |depth, arrs|
puts "Values with depth #{depth}: #{arrs.map(&:first)}"
end
Which outputs:
Values with depth 0: ["S0"]
Values with depth 1: ["S1"]
Values with depth 2: ["S2", "S3", "S4"]
Values with depth 3: ["S5"]
Upvotes: 4