将一个数组中的元素与另一个数组中的元素进行比较

时间:2021-11-05 21:26:35

I have two arrays of numbers that have the same size. How can I tell if there is any element in the second array that is greater than the first array at a given index? With this example:

我有两个具有相同大小的数字数组。如何判断第二个数组中是否有任何元素大于给定索引处的第一个数组?通过这个例子:

a = [2, 8, 10]
b = [3, 7, 5]

3 is greater than 2 at position 0. But in the following:

3在位置0大于2.但是在下面:

a = [1, 10]
b = [0, 8]

there is no such element. At index 0, 0 is not greater than 1, and at index 1, 8 is not greater than 10.

没有这样的元素。在索引0处,0不大于1,并且在索引1处,8不大于10。

3 个解决方案

#1


5  

Try this one

试试这个

a.each_with_index.any? { |item, index| b[index] > item }

#2


4  

No need for indices. Just pair them and check each pair.

不需要指数。只需将它们配对并检查每一对。

b.zip(a).any? { |x, y| x > y }
=> true or false

And a tricky one: Check whether at every position, a is the maximum:

一个棘手的问题:检查每个位置是否是最大值:

a.zip(b).map(&:max) != a
=> true or false

And a very efficient one (both time and space):

而且非常有效(时间和空间):

b.zip(a) { |x, y| break true if x > y }
=> true or nil

(If you need true/false (often you don't, for example in if-conditions), you could prepend !! or append || false)

(如果你需要true / false(通常你没有,例如在if条件中),你可以预先添加!!或者追加|| false)

#3


0  

If there's a number in b greater than the number in a at the given index, this will return the number in b. If no numbers in b are greater, nil will be returned.

如果b中的数字大于给定索引处的数字,则返回b中的数字。如果b中的数字不大,则返回nil。

b.detect.with_index { |n, index| n > a[index] }

For example, if you have the following arrays.

例如,如果您有以下数组。

a = [3, 4, 5]
b = [6, 7, 8]

You'll get a return value of 6.

您将获得6的返回值。

#1


5  

Try this one

试试这个

a.each_with_index.any? { |item, index| b[index] > item }

#2


4  

No need for indices. Just pair them and check each pair.

不需要指数。只需将它们配对并检查每一对。

b.zip(a).any? { |x, y| x > y }
=> true or false

And a tricky one: Check whether at every position, a is the maximum:

一个棘手的问题:检查每个位置是否是最大值:

a.zip(b).map(&:max) != a
=> true or false

And a very efficient one (both time and space):

而且非常有效(时间和空间):

b.zip(a) { |x, y| break true if x > y }
=> true or nil

(If you need true/false (often you don't, for example in if-conditions), you could prepend !! or append || false)

(如果你需要true / false(通常你没有,例如在if条件中),你可以预先添加!!或者追加|| false)

#3


0  

If there's a number in b greater than the number in a at the given index, this will return the number in b. If no numbers in b are greater, nil will be returned.

如果b中的数字大于给定索引处的数字,则返回b中的数字。如果b中的数字不大,则返回nil。

b.detect.with_index { |n, index| n > a[index] }

For example, if you have the following arrays.

例如,如果您有以下数组。

a = [3, 4, 5]
b = [6, 7, 8]

You'll get a return value of 6.

您将获得6的返回值。