jyim jyim - 1 year ago 68
Ruby Question

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

  1. Why are we comparing indices to determine if a letter has been

  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
elsif idx2 < idx1
# will have previously counted this repeat
elsif idx2 > idx1
is_repeat = true

idx2 += 1

if is_repeat
repeats += 1

idx1 += 1

return repeats

Answer Source

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...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download