数组找到相同元素的数量

时间:2016-08-21 04:26:12

标签: arrays ruby

例如我有一个这样的数组:

["a","a","a","a","b","c","d","a","a","a"] #Expected result = 4

在我更改为不同的值之前,如何找到相同元素的数量(在我的情况下为"a"?)

提前致谢。

5 个答案:

答案 0 :(得分:1)

letters = ["a","a","a","a","b","c","d","a","a","a"]
letters.take_while { |letter| letter == letters.first }.count
 => 4 

答案 1 :(得分:1)

def nbr_consecutive(arr, str)
  start_ndx = arr.index(str)
  return 0 if start_ndx.nil?
  a = arr[start_ndx..-1]      
  a.index { |s| s != str } || a.size
end

arr = %w| e e a a a a b c d a a a |
  #=> ["e", "e", "a", "a", "a", "a", "b", "c", "d", "a", "a", "a"]

nbr_consecutive(arr, "e")
  #=> 2
nbr_consecutive(arr, "a")
  #=> 4
nbr_consecutive(arr, "b")
  #=> 1
nbr_consecutive(arr, "z")
  #=> 0

答案 2 :(得分:1)

array = ["a","a","a","a","b","c","d","a","a","a"]

如果您只关心第一个值,无论它是什么:

p array.slice_when(&:!=).first.size #=> 4

# same as array.slice_when{|x,y| x != y }.first.size #=> 4

如果您需要查找特定值:

p array.slice_when(&:!=).find{|x| x.first == 'b' }.size #=> 1

或者也许:

p array.slice_when(&:!=).to_a.assoc('a').size #=> 4

答案 3 :(得分:0)

这是我能想到的最多Ruby方式

O(n^2)

这个想法是删除开头的字母,直到找到你想要的字母,然后计算你想要的字母,直到你找到一封不是你的字母的字母。

所以对于你的例子,你会做

list.drop_while { |letter| letter != letter_to_find }.take_while { |letter| letter == letter_to_find }.count

并非只有["a","a","a","a","b","c","d","a","a","a"].drop_while { |letter| letter != "a" }.take_while { |letter| letter == "a" }.count 对于您的具体示例是必需的,但如果您在所需字母前面加上字母,则必须take_while

答案 4 :(得分:-2)

array = ["a","a","a","a","b","c","d","a","a","a"]

array.chunk{|char| char}.map{|char, a| a.size if char == "a"}.first