Hi,
I've got this:
a = [[123,1],[124,1],[125,1],[126,2],[127,3],[128,3]]
And I would like to turn a into b:
- ordered by value
- random within array of value
// updated:
b = [[124,123,125],[126],[128,127]]
How to do this in ruby? Im using rails.
Hi,
I've got this:
a = [[123,1],[124,1],[125,1],[126,2],[127,3],[128,3]]
And I would like to turn a into b:
// updated:
b = [[124,123,125],[126],[128,127]]
How to do this in ruby? Im using rails.
One solution is:
a = [[123,1],[124,1],[125,1],[126,2],[127,3],[128,3]]
a = a.sort {|d, e| d[1] <=> e[1]}
prev = a[0][1]; result = []; group = [];
a.each do |e|
if e[1] == prev
group << e[0]
else
result << group.shuffle
group = [e[0]]
prev = e[1]
end
end
result << group
p result
run:
$ ruby t.rb
[[125, 123, 124], [126], [127, 128]]
a.group_by(&:last).
sort_by(&:first).
map(&:last).
map {|el| el.map(&:first).shuffle }