开发者

Comparing the order of three arrays with the same elements

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 ar开发者_开发知识库e 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.


Have you tried this?

array1 == array2 || array1 == array3 || array2 == array3


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]]


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜