Reputation: 1581
arry = [["a",3.0,3], ["b",4.0,4], ["c",5.0,5]]
I am looking for the following output
[["a", 3.0, [["b", 4.0, 7], ["c", 5.0, 8]]],
["b", 4.0, [["a", 3.0, 7], ["c", 5.0, 9]]],
["c", 5.0, [["a", 3.0, 8], ["b", 4.0, 9]]]]
This is what I have done
I am not able to produce the following above mentioned format of the output. The output I am able to do is
[a,3.0,b,4.0,7]
7 here is 3+4
[a,3.0,c,5.0,8]
[b,4.0,c,5.0,9]
..etc
Apart from that, how to code to display lets say only the elements less than 8
and get this output
[["a",3.0,["b",4.0,7]],["b",4.0,["a",5.0,7]],["c",5.0,[]]
Upvotes: 0
Views: 747
Reputation: 34031
arry.map do |inner|
dup = inner.dup
n = dup[2]
dup[2] = []
arry.each do |other|
next if other == inner # Only want other inner arrays
other_dup = other.dup
other_dup[2] += n
dup[2] << other_dup
end
dup
end
This evaluates to:
[["a", 3.0, [["b", 4.0, 7], ["c", 5.0, 8]]],
["b", 4.0, [["a", 3.0, 7], ["c", 5.0, 9]]],
["c", 5.0, [["a", 3.0, 8], ["b", 4.0, 9]]]]
Update: Glad that's what you wanted. This is ugly, but I think it satisfies your filtering goal:
mapped.map do |inner|
inner_dup = inner.dup
inner_dup[2] = inner_dup[2].select do |inner_inner|
inner_inner[2] < 8 # Condition for the elements you want to test
end
inner_dup
end
This evaluates to:
[["a", 3.0, [["b", 4.0, 7]]], ["b", 4.0, [["a", 3.0, 7]]], ["c", 5.0, []]]
Note again that this is slightly different output than you specified, but I believe it's what you actually want. (What if more than one inner array matches per group?)
Upvotes: 1