Search code examples
arraysrubyiterationsuffix-array

Nested loops in Ruby


I am trying to count the number of similar prefix beginnings to a string in Ruby. e.g; input "ababaa" should output 11;

ababaa = 6
 babaa = 0
  abaa = 3
   baa = 0
    aa = 1
     a = 1

I have got as far as the code below, using a nested loop to go through each of the above as an array, however it looks as though Ruby is currently outputting the count of just the first Array object, "ababaa".

Solved, thanks :)

def string_suffix(string)
num = 0
ary = []
string.length.times do
  ary << string[num..string.length]
  num = num + 1
end
result = 0
ary.each do |x| # ["ababaa", "babaa", "abaa", "baa", "aa", "a"] 
  x.chars.each_with_index do |c,index|
    break unless c == string[index]
      result = result + 1
  end
end
return result
end

I have looked far and wide and still cannot solve the issue, It looks like the (final, nested) array is breaking after the first iteration of the 'ary' Array and just returning that output.


Solution

  • You are returning the result while you are still in the loop. You need to move result = 0 out of the loop, and move the return result statement outside of the loop too. At the moment the function is going through the first iteration of the loop ("ababaa", for which all characters match), but you want result to equal the sum of all results.

    Additionally, instead of doing:

    count = 0
    x.chars.each do |x|
        if x == string[count]
            count = count + 1
            result = result + 1
        else
            count = count + 1
        end
    end
    

    You could use the function each_with_index, to get

    x.chars.each_with_index do |c,index|
        if c == string[index]
            result = result + 1
        end
    end
    

    However, since you are trying to count how many characters in the substring are a prefix of string, you want to break when you first find a character c that is not equal to string[index], so that you don't end up counting extra characters. The loop then becomes:

    x.chars.each_with_index do |c,index|
        if c == string[index]
            result = result + 1
        else
            break
        end
    end