如何比较3/4匹配的字符串

时间:2017-07-11 20:00:18

标签: ruby string comparison

需要将数组中的数字与“获胜”数字进行比较数。但是我必须看看4个中有3个匹配。例如" 1234"是我的号码和获胜= [" 4356"," 8312"," 4820"," 7623"]。在这种情况下" 8312"应该提醒胜利,因为他们共有1 2&3。我必须在单元测试中定义数字,然后在单独的文件中编写函数,然后将该函数传递回单元测试。任何帮助将不胜感激。我已经编写了一个函数和测试,比较了完全匹配,并且对下一步采取的措施一无所知。

function_file

NSURLSession

test_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     

1 个答案:

答案 0 :(得分:0)

因此,让我们将这个问题分成两个独立的问题。

  1. 您需要一个计算匹配字符数的函数。
  2. 然后,如果他们有足够的匹配字符,你想要收集这些字符串。
  3. 例如,您可以编写一个函数来检查两个字符串匹配的字符数。

    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
    

    您可以使用countselect等枚举函数以更紧凑的方式编写这两个函数:

    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