From: "Llelan D." Date: 2012-05-17T09:56:54+09:00 Subject: Re: Ruby Arrays (Pushing Array Inside the same array) The main problem here is the description of what is desired. A lot of information has been left out. An analysis of the given input and output arrays would seem to suggest the algorithm: c << a[i] and d << b[i] if a[i] is not a multiple of a[j] from any other element && b[i] != b[j] The unanswered questions are Is there a pattern to the sequence of x values? Those given are ascending multiples of 9. What is the relationship of b[i] to a[i]? The following ruby implementation performs the above algorithm with no assumption about the pattern or order of elements in array a, or the relationship of b[i] to a[i]. -------------------------------------------------------------------- a, b, c, d = [9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99, 108, 117, 126], [1, 1, 2, 1, 1, 3, 4, 5, 2, 1, 1, 3, 6, 1], [], [] (a.count - 1).times {|i| (ai, bi) = a[i], b[i] ej = (a.count - 1).times loop do begin j = ej.next (aj, bj) = a[j], b[j] break if i != j and ai % aj == 0 and bi == bj rescue c << ai d << bi break end end } c << a[-1] d << b[-1] puts('c: ' + c.to_s) puts('d: ' + d.to_s) -------------------------------------------------------------------- Output: c: [9, 27, 54, 63, 72, 117, 126] d: [1, 2, 3, 4, 5, 6, 1] -------------------------------------------------------------------- It may not be the most concise usage of the Ruby syntax, but it gets the job done without generating any extra array copies, and terminates the inner loop once a reason is found to not push the current (ai, bi) pair. If more were known about the pattern of values in a, or the relationship of b[i] to a[i], a more efficient implementation could be created. You might find it more friendly to Ruby to change the input values from two separate arrays with the same length to one array with 2-element pairs as elements. [[9, 1], [18, 1]...] I hope you find that of some help. P.S. If anyone can create the same implementation with more concise Ruby syntax without generating any extra interim arrays, I'd love to see it. -- Posted via http://www.ruby-forum.com/.