gpt4 book ai didi

arrays - 如何检查数组中的所有元素是否出现不超过两次?

转载 作者:数据小太阳 更新时间:2023-10-29 07:20:17 25 4
gpt4 key购买 nike

我正在使用 Ruby 2.4。假设我有一个字符串数组(它们都是字符串化的(这是一个词吗?)整数......

["1", "2", "5", "25", "5"]

如何编写一个函数来告诉我数组中的所有元素是否在数组中出现不超过两次?比如这个数组

["1", "3", "3", "55", "3", "2"]

会返回 false 因为 "3" 出现了三次,但是这个数组

["20", "10", "20", "10"]

将返回 true,因为没有任何元素出现超过两次。

最佳答案

Enumerable#group_by将为此做繁重的工作:

def no_element_present_more_than_twice?(a)   
a.group_by(&:itself).none? do |_key, values|
values.count > 2
end
end

p no_element_present_more_than_twice?(["1", "3", "3", "55", "3", "2"])
# => false
p no_element_present_more_than_twice?(["20", "10", "20", "10"])

关于arrays - 如何检查数组中的所有元素是否出现不超过两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41645614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com