Ruby-使用多维数组比较数字 [英] Ruby - Comparing numbers using a multidimensional array

查看:81
本文介绍了Ruby-使用多维数组比较数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个问题,我需要将一个数字与一个数字数组进行比较,以查看4个数字中的3个是否匹配。

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.

例如:

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

my_number = "1234"

如果比较中有3个匹配数字,则返回true。如果比较小于3或完全匹配,则返回false。

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.

任何帮助将不胜感激。

推荐答案

如果没有重复的数字,我们可以使用数组交集:

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"

或者,而不是 w.chars& my_number_arr).size == 3 ,我们可以写

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.

已提出,建议采用 Array#difference 方法作为Ruby核心方法。对于这个问题将是完美的。有关其用法的示例,请参见 Array#difference 的答案。

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)

这篇关于Ruby-使用多维数组比较数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆