0
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

  • With the size of the array, I iterated over the loop
  • First, I have taken the first element.
  • Deleted it and made a new array. I iterated through the new array, calculated the sum and pushed the elements to new array2
  • I added the deleted element at the end

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,[]]
4
  • What are the transformation rules (I don't see what your expected output means)? Commented Apr 26, 2013 at 23:34
  • @SergioTulentsev Looks like a mapping between an element and every other element and when a specific element is the key their value is added to others. Commented Apr 26, 2013 at 23:37
  • Neither of your outputs are valid - you're missing some ] somewhere Commented Apr 26, 2013 at 23:39
  • I have changed the output and corrected the ]. Thank you for pointing it out! Commented Apr 26, 2013 at 23:58

1 Answer 1

1
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?)

Sign up to request clarification or add additional context in comments.

1 Comment

I changed the output in the question to reflect what I actually meant as well! Now coming to the second question how to display lets say only the elements less than 8?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.