ruby - function that returns the number of letters that repeat in a string -
trying make function counts number of letters appear more once anywhere in string (not together, , not the number of times repeat). have:
def num_repeats(string) repeat = [] i1 = 0 i2 = 1 while i1 < string.length while i2 < string.length if (string[i1] == string[i2]) && (!repeat.include? string[i1]) repeat << string[i1] end i2 +=1 end i1+=1 end return repeat.length end puts(num_repeats('sldhelanlaskjkajksda'))
for reason, pushes first letter of string if first letter has been used in rest of string, after that, seems method stops looping through rest of string.
i'd know first why current code not working , if there way fix it, , welcome other better solutions.
here orthodox way it:
'sldhelanlaskjkajksda'.each_char.group_by(&:itself).count{|_, v| v.length > 1} # => 6
reason code not work because, (i) once
i2
loop terminates, increment i1
, , try i2
loop in next i1
iteration, since i2
hasn't been touched after failed satisfy loop condition, not satisfy condition again, , i2
loop never run again, , (ii) initializing i2
constant. to fix it, initialize i2
within i1
loop @ beginning, , initialize i2 = i1 + 1
, not 1
.
Comments
Post a Comment