Reputation:
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:
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
.
Upvotes: 0
Views: 862
Reputation: 28596
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
)
Upvotes: 5
Reputation: 2258
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.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
.
Upvotes: 0
Reputation: 30056
Try this one
a.each_with_index.any? { |item, index| b[index] > item }
Upvotes: 5