Understanding counts[counts_idx][0]?

def num_repeats(string)
counts = []

str_idx = 0
while str_idx < string.length
letter = string[str_idx]

counts_idx = 0
while counts_idx < counts.length
  if counts[counts_idx][0] == letter
    counts[counts_idx][1] += 1
    break
  end
  counts_idx += 1
end

if counts_idx == counts.length
  # didn't find this letter in the counts array; count it for the
  # first time
  counts.push([letter, 1])
end

str_idx += 1

end

num_repeats = 0
counts_idx = 0
while counts_idx < counts.length
if counts[counts_idx][1] > 1
num_repeats += 1
end

counts_idx += 1

end

return num_repeats
end

This is a solution to a question that asks how many repeating letters
there are in a string of letters. I’m confused by the line
counts[counts_idx][0] == letter and counts[counts_idx][1] += 1.

I’ve never seen this syntax (a number next to to an array that’s already
been passed a value) used before, and I just wanted some clarification.

Thank you for taking the time to answer my question!

First, a simple solution:

===
def repetitions(str)
size=str.size
str.each_char.each_with_object({}) do |c,h|
next if h[c]
l=size-str.gsub(c,"").size
h[c]=l if l>1
end
end

def arepetitions(str) [str,a=repetitions(str),a.size] end
p arepetitions(“Hello”)
p arepetitions(“alleluia”)
p arepetitions(“abraracoursix”)

[“Hello”, {“l”=>2},1]
[“alleluia”, {“a”=>2, “l”=>3},2]
[“abraracoursix”, {“a”=>3, “r”=>3},3]

Cyril Cguirguis wrote in post #1181609:

while str_idx < string.length
while counts_idx < counts.length
<…>
end

if counts_idx == counts.length
  # didn't find this letter in the counts array; count it for the
  # first time
  counts.push([letter, 1])
end

str_idx += 1

end

At first iteration, counts.length is 0 , so <…> is not evaluate,
and counts.push is done. so counts[] contain only tuples of
letter,number.

while counts_idx < counts.length
  if counts[counts_idx][0] == letter

At next iterations, counts is examine for his data, so count[x] is
always a array of 2 elements, so the test is valid.

This code is really awful ruby code : its like a C ou Fortran code
translated to ruby… :slight_smile:

Regards,

A better solution for repetition() :

===
def repetitions(str)
str.each_char.
each_with_object(Hash.new(0)) { |c,h| h[c]+=1 }.
delete_if {|k,v| v<2}
end