一行中相同元素的数量 - 红宝石

时间:2015-02-10 15:32:11

标签: ruby arrays

A有一个带字符串的简单数组。 我需要知道一行中是否存在10个元素,其中包含" ffff"串。我找到了解决方案:each_with_index然后添加一些计数器(if string.exist?递增计数器,在下一个周期 - 比较计数器:如果字符串再次存在则递增或者如果没有则重置计数器),但这看起来很难看。可能有一些优雅的解决方案? 有什么建议吗?

2 个答案:

答案 0 :(得分:2)

我会写一些类似的东西:

my_array.each_cons(10).any?{|subarray| subarray.all?{|item| item['ffff']}}

答案 1 :(得分:1)

这是另一种方式,与hirolau提出的方式不同,它更加冗长,但可能会有更好的表现。

# a recursive method which return true or false
def consecutive(array, pattern, count)
   return false if array.empty?
   # Filter out the first elements not matching the pattern
   filtered = array.drop_while{|a| !a[pattern] }
   # Take the first elements matching the pattern from the filtered array
   cons = filtered.take_while{ |a| a[pattern] }
   if(cons.count >= count)
     true
   else
     # this time filter out the first elements matching the pattern
     # because their number does not equal the desired count
     filtered = filtered.drop_while{ |a| a[pattern] }
     consecutive(filtered, pattern, count)
   end
end

array = ["ffff",
         "ffff",
         "ffff",
         "er",
         "er",
         "ffff",
         "ffff",
         "er",
         "reffff",
         "bffff",
         "fffftr",
         "ffffm",
         "ffff",
         "ffff",
         "ffff",
         "ffff",
         "ffff",
         "ffffcf"]

puts consecutive(array, /f{4}/, 10)