0

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.

2
  • What should the output look like? Commented Dec 15, 2017 at 20:31
  • It can just be true or false Commented Dec 15, 2017 at 20:34

3 Answers 3

5

Try this one

a.each_with_index.any? { |item, index| b[index] > item }
Sign up to request clarification or add additional context in comments.

3 Comments

Which reads better, what you have or a.each_index.any? { |index| b[index] > a[index] }?
I prefer your :D
@CarySwoveland Yours is also faster.
5

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)

4 Comments

I could say "no need for a new array" :D
@Ursus Well, then I could say "no need to assume that a new array is bad" or I could just plug a .lazy in there :-)
This is the cleanest answer here so far. b.lazy.zip(a).any? { |x, y| x > y } would be likely a bit better, yes.
@mudasobwa Well it really depends on the usage. For small cases like the OP's examples, adding .lazy just unnecessarily clutters the code and makes it slower. Anyway... I just added another solution that's very efficient in both time and space.
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.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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.