如何检查数组中的所有元素是否出现不超过两次? [英] How do I check if all the elements in my array occur no more than twice?
本文介绍了如何检查数组中的所有元素是否出现不超过两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Ruby 2.4.假设我有一个字符串数组(所有字符串都只是string-i-fied(是一个单词?)整数...
I'm using Ruby 2.4. Let's say I have an array of strings (which are all just string-i-fied (is that a word?) integers ...
["1", "2", "5", "25", "5"]
我该如何编写一个函数来告诉我数组中的所有元素在数组中的出现次数是否不超过两次?例如,这个数组
How do I write a function that tells me if all the elements in the array occur no more than twice in the array? For example, this array
["1", "3", "3", "55", "3", "2"]
将返回 false
,因为"3"
出现了3次,但是此数组
would return false
because "3"
occurs three times, but this array
["20", "10", "20", "10"]
将返回 true
,因为所有元素都不会出现两次以上.
would return true
because none of the elements occur more than twice.
推荐答案
在我看来,这可能是一个非常简单的解决方案:
In my point of view, that could be a pretty simple solution:
def no_more_than_twice_occur?(array)
array.none? { |el| array.count(el) > 2 }
end
no_more_than_twice_occur?(["1", "3", "3", "55", "3", "2"]) # => false
no_more_than_twice_occur?(["20", "10", "20", "10"]) # => true
这篇关于如何检查数组中的所有元素是否出现不超过两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文