jyim
jyim

Reputation: 119

Please explain this Ruby method that returns number of repeat letters

Can anybody please explain this code? I don't understand specifically:

  elsif idx2 > idx1
    is_repeat = true
  end
  1. Why are we comparing indices to determine if a letter has been repeated?
  2. Also what does the 'next' term do inside of the if statement?

The full code is shown below:

# Write a method that takes in a string and returns the number of
# letters that appear more than once in the string. You may assume
# the string contains only lowercase letters. Count the number of
# letters that repeat, not the number of times they repeat in the
# string.
#
# Difficulty: hard.

def num_repeats(array)
  repeats = 0

  idx1 = 0
  while idx1 < array.length
    is_repeat = false
    idx2 = 0
    while idx2 < array.length
      if array[idx1] != array[idx2]
        idx2 += 1
        next
      elsif idx2 < idx1
        # will have previously counted this repeat
        break
      elsif idx2 > idx1
        is_repeat = true
      end

      idx2 += 1
    end

    if is_repeat
      repeats += 1
    end

    idx1 += 1
  end

  return repeats
end

Upvotes: 1

Views: 292

Answers (1)

spickermann
spickermann

Reputation: 106882

If both conditions before (if idx2 < array.length and elsif idx2 < idx1) are false but idx2 > idx1 is true, than set the local variable is_repeat to true...

Upvotes: 1

Related Questions