需要将数组中的数字与“获胜”数字进行比较。但我得看看四场比赛中是否有三场。我的号码是"1234“,winning=是”4356“、"8312”、"4820“、"7623”。在这种情况下,"8312“应该警告胜利,因为他们有12和3的共同点。我必须在单元测试中定义数字,然后在一个单独的文件中编写一个函数,然后将该函数传递回单元测试。任何帮助都将不胜感激。我已经写了一个函数和测试,比较一个精确的匹配,并且不知道下一步要做什么。
function_file
def match(my_num,arr)
matches = []
arr.each_with_index do |v,i|
if my_num == v
matches << my_num
end
end
matches
end
test_file
require "minitest/autorun"
require_relative "close_but_no_func.rb"
class TestWinningNumbers < Minitest::Test
def test_1_equals_1
assert_equal(10-5, 3+2)
end
def test_winning_num
my_num = "1134"
arr=["6028","2088","3058","3476","8740","1134"]
assert_equal(["1134"], match(my_num, arr))
end
end
发布于 2017-07-11 21:21:37
让我们把这个问题分成两个独立的问题。
例如,您可以编写一个函数来检查这两个字符串的匹配字符数。
def count_matching_chars(str1,str2)
# counts how many characters of str1 appear in str2
matching_chars_count = 0
str1.each_char do |char|
matching_chars_count += 1 if str2.include?(char)
end
matching_chars_count
end
puts count_matching_chars("1234", "1134") => 3
puts count_matching_chars("1111", "1134") => 4
puts count_matching_chars("1234", "1111") => 1
这里的一个忽略了定位,它只检查str1
中有多少字符与str2
的一个字符匹配。
现在,您可以轻松地在数组中收集这些数字。
def matches(my_num, arr)
result = []
arr.each do |num|
result << arr if count_matching_chars(my_num,num) >= 3
end
result
end
您可以使用枚举数函数(如count
和select
),以更紧凑的方式编写这两个函数。
def count_matching_chars(str1,str2)
str1.each_char.count do |char|
str2.include?(char)
end
end
def matches(my_num, arr)
arr.select do |num|
return true if count_matching_chars(num,my_num) >= 3
end
end
或者你把所有的东西组合成一个函数
def matches(my_num, arr)
arr.select do |num|
true if my_num.each_char.count { |char| num.include?(char)} >= 3
end
end
现在,如果你只想检查一下,它是否是一个中奖号码。一旦找到匹配项,您只需返回true
:
def winning_number?(my_num, arr)
arr.select do |num|
return true if my_num.each_char.count { |char| num.include?(char)} >= 3
end
end
https://stackoverflow.com/questions/45043534
复制相似问题