pyfl88
pyfl88

Reputation: 1710

Array find the number of same element

For example I have an array such as this:

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

How can I find the number of same element, in my case "a", before it change to different value?

Thanks in advance.

Upvotes: 0

Views: 194

Answers (5)

Raj Adroit
Raj Adroit

Reputation: 3878

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

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

Upvotes: -2

hirolau
hirolau

Reputation: 13901

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

If you only care about the first value, no matter what it is:

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

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

If you need to look for a specific value:

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

Or perhaps:

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

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110665

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

Upvotes: 2

seph
seph

Reputation: 6076

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

Upvotes: 1

kcdragon
kcdragon

Reputation: 1733

Here is the most Ruby-ish way I could think of

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

The idea is to remove the letters in the beginning until you find the letter you want and then count the letters that you want until you reach a letter that is not your letter.

So for you example you would do

["a","a","a","a","b","c","d","a","a","a"].drop_while { |letter| letter != "a" }.take_while { |letter| letter == "a" }.count

Not that only take_while is necessary for your specific example but drop_while is necessary if you have letters preceding the letters you want.

Upvotes: 0

Related Questions