我有一个像['n','n','n','s','n','s','n','s','n','s']
这样的数组,我想检查是否有相同数量的字符。在上面我有6 n
s和4 s
s,所以他们不平等,我尝试过,但没有任何事情是正确的。我怎么能用Ruby做到这一点?
答案 0 :(得分:1)
给定数组:
a = ['n','n','n','s','n','s','n','s','n','s']
按照它的元素对数组进行分组,并仅采用该组的值:
(f,s) = a.group_by{|e| e}.values
比较尺寸:
f.size == s.size
结果:false
答案 1 :(得分:1)
或者你可以试试这个:
x = ['n','n','n','s','n','s','n','s','n','s']
x.group_by {|c| c}.values.map(&:size).inject(:==)
答案 2 :(得分:0)
你可以选择这样的东西:
def eq_num? arr
return false if arr.size == 1
arr.uniq.map {|i| arr.count(i)}.uniq.size == 1
end
arr = ['n','n','n','s','n','s','n','s','n','s']
eq_num? arr #=> false
arr = ['n','n','n','s','n','s','s','s']
eq_num? arr #=> true
也适用于两种以上的字母:
arr = ['n','n','t','s','n','t','s','s','t']
eq_num? arr #=> true
答案 3 :(得分:0)
使用Array#count的效率相对较低,因为它需要为其实例计数的每个元素完全通过数组。而是像其他人一样使用Enumerable#group_by,或使用计数哈希,如下所示(请参阅Hash::new):
<强>代码强>
def equal_counts?(arr)
arr.each_with_object(Hash.new(0)) { |s,h| h[s] += 1 }.values.uniq.size == 1
end
<强>实施例强>
equal_counts? ['n','n','n','s','n','s','n','s','n','s']
#=> false
equal_counts? ['n','r','r','n','s','s','n','s','r']
#=> true
<强>解释强>
有关
arr = ['n','n','n','s','n','s','n','s','n','s']
步骤如下。
h = arr.each_with_object(Hash.new(0)) { |s,h| h[s] += 1 }
#=> {"n"=>6, "s"=>4}
a = h.values
#=> [6, 4]
b = a.uniq
#=> [6, 4]
b.size == 1
#=> false