ruby - Number of repeats -
write method takes in string , returns number of letters appear more once in string. may assume string contains lowercase letters. count number of letters repeat, not number of times repeat in string.
i implemented methods , test cases as:
def num_repeats(string) count = 0 dix = 0 new = "" while dix < string.length letter = string[dix] if !(new.include?(letter)) new = new + "letter" else break end dix2 = dix + 1 while dix2 < string.length if letter == string[dix2] count +=1 break end dix2 +=1 end dix += 1 end puts(count.to_s) return count end # these tests check code working. after writing # solution, should print true. puts('num_repeats("abdbc") == 1: ' + (num_repeats('abdbc') == 1).to_s) # 1 character repeated puts('num_repeats("aaa") == 1: ' + (num_repeats('aaa') == 1).to_s) puts('num_repeats("abab") == 2: ' + (num_repeats('abab') == 2).to_s) puts('num_repeats("cadac") == 2: ' + (num_repeats('cadac') == 2).to_s) puts('num_repeats("abcde") == 0: ' + (num_repeats('abcde') == 0).to_s)
test results:
1 num_repeats("abdbc") == 1: true 2 num_repeats("aaa") == 1: false 2 num_repeats("abab") == 2: true 2 num_repeats("cadac") == 2: true 0 num_repeats("abcde") == 0: true
for second test returned false, wrong code?
you appending "letter"
, rather letter
variable new
on line 8.
if !(new.include?(letter)) new = new + "letter" else #... end
becomes:
unless new.include?(letter) new = new + letter else #... end
Comments
Post a Comment