tags:

views:

43

answers:

3

I have three arrays. The arrays all have the same size and contain the same elements. However, the three arrays must not be in the same order. How do I verify that the elements are not in the same order?

Here's how I've implemented it:

    all_elements_equal = true
    array1.zip(array2, array3) do |first, second, third|
        if first != second && second != third && first != third
            all_elements_equal = false
        end
    end

If all_elements_equal is false, presumably the arrays are not in the same order. However, there is a possibility that this will not be the case if only one of the arrays is different and the other two are identical.

So, my question is, how do I make the test stronger, and is there a more elegant way of implementing the code? Full disclosure: I am new to Ruby.

+2  A: 

Have you tried this?

array1 == array2 || array1 == array3 || array2 == array3
Mark Byers
+1 - Just tested this with a simple example and the logic does indeed work as expected.
Topher Fangio
This worked. Turns out the solution was simpler than I thought it would be!
Mark Abersold
something slightly fancier (not necessarily better): `[array1, array2, array3].combination(2).all? { |a, b| a != b }`
Wayne Conrad
A: 

I don't know Ruby, but I think you need to inverse your logic.

anyElementEqual=false
do
    if first==second || first==third || second==third
        anyElementEqual=true
end
etc.
Kendrick
+1  A: 

In general, if you have array arr of N such arrays, you can just check if there are any duplicates there:

arr.length == arr.uniq.length

because, for example:

[[1,2,3],[2,3,1],[1,2,3]].uniq
#=> [[1, 2, 3], [2, 3, 1]]
[[1,2,3],[2,3,1],[2,1,3]].uniq
#=> [[1, 2, 3], [2, 3, 1], [2, 1, 3]]
Mladen Jablanović
+1 for supporting N arrays.
macek