计算数组中的更改 [英] Counting changes in an array
本文介绍了计算数组中的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想计算数组中红色
后跟绿色
的次数:
I would like to count the number of times "red"
is followed by "green"
in this array:
["red", "orange", "green", "red", "yellow", "blue", "green"]
如果是另一种颜色,代码应忽略它并继续进行下一项
If it is another color, the code should ignore it and proceed to the next item in the array.
event_type.each_slice(2) do |red, green|
break unless green
count = count + 1
end
p "The count is #{count}"
步骤1:
Look for red
步骤2:
IF not last item
Compare with next item on array
ELSE Go to Step 4
步骤3:
IF green, count = count + 1
Go to Step 1
ELSE Go to Step 2
步骤4:
Print Count
推荐答案
以下是我认为的解决方案。当然,还有更多的重构空间,您可以从这里开始。
Below one is solution I believe. Sure there is more room to refactor it, you can start from here.
a = ["red", "orange", "green", "red", "yellow", "blue", "green"]
a.reject {|e| !['red', 'green'].include? e }
.each_cons(2)
.select{|e| e == ['red', 'green']}
.size
A更多艺术版本。
def neither_red_nor_green e
!['red', 'green'].include? e
end
def red_followed_by_green ary
ary == ['red', 'green']
end
a.reject(&method(:neither_red_nor_green))
.each_cons(2)
.select(&method(:red_followed_by_green))
.size
更新
感谢@Stefan提供以下建议。
Thanks to @Stefan for below suggestions.
def either_red_or_green e
['red', 'green'].include? e
end
def red_followed_by_green ary
ary == ['red', 'green']
end
a.select(&method(:either_red_or_green))
.each_cons(2)
.count(&method(:red_followed_by_green))
更新
按照Stefan Pochmann的建议,
As Stefan Pochmann proposed,
a.select(&method(:either_red_or_green))
.each_cons(2)
.count(['red', 'green'])
将完成相同的工作,而无需调用其他方法。
will do the same work, without needing another method call.
这篇关于计算数组中的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文