0

I'm working on a problem where I need to compare a number to an array of numbers seeing if 3 of the 4 numbers match.

For example:

winning_numbers = [["2537"], ["1294"], ["5142"]]

my_number = "1234"

If the comparison has 3 matching numbers return true. If the comparison has less than 3 or an exact match return false.

From what I've read I'm using a multi-dimensional array, however I don't understand how to loop through each array one number at at time, so that I can compare it to my number.

Any help would be greatly appreciated.

Alex M
  • 2,756
  • 7
  • 29
  • 35

2 Answers2

0

You could do something like this that returns all matching numbers:

winning_numbers.select do |number| 
  (number.first.split(//) & my_number.split(//)).size >= 3
end
#=> [["1294"], ["5142"]]

You might want to use find instead of select, when you are only interested into the first matching winning_number.

spickermann
  • 100,941
  • 9
  • 101
  • 131
  • This does not work when there are duplicate digits. For example, if `winning_numbers = [["1111"]]; my_number = "1112"`, you return an empty array, though `[["1111"]]` is a match. – Cary Swoveland Aug 14 '16 at 22:33
0

If there were no duplicate digits we could use array intersection:

def triple?(winning_numbers, my_number)
  my_number_arr = my_number.chars
  winning_numbers.any? { |(w)| w.chars & my_number_arr).size == 3 }
end

winning_numbers = [["2537"], ["1294"], ["5142"]]
my_number = "1234"

triple?(winning_numbers, my_number) #=> true, matches "1294"

Alternatively, instead of w.chars & my_number_arr).size == 3, we could write

(w.chars - my_number_arr).size == 1 # (4-3=1)

This does not work, however, when strings have duplicate digits, which, of course, must be accounted for.

I have proposed that a method Array#difference be adopted as a Ruby core method. It would be perfect for this problem. See my answer at Array#difference for examples of its uses.

def triple?(winning_numbers, my_number)
  my_number_arr = my_number.chars
  winning_numbers.any? { |(w)| puts my_number_arr.difference(w.chars).size == 1 }
end

winning_numbers = [["2537"], ["1294"], ["5142"]]
my_number = "1234"

triple?(winning_numbers, my_number) #=> true, matches "1294"

Another example that includes duplicate digits:

winning_numbers = [["1551"], ["1594"], ["1141"]]

triple?(winning_numbers, my_number) # matches "1141"

and an example where there is no match on three digits:

winning_numbers = [["1551"], ["1594"], ["1561"]]

triple?(winning_numbers, my_number) #=> false (no match)
Community
  • 1
  • 1
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100