Reputation: 77
Hello guys I have the following problem:
INPUT:
2
ababaa
aa
OUTPUT:
11
3
Explanation:
For the first case, the suffixes of the string are "ababaa", "babaa", "abaa", "baa", "aa" and "a". The similarities of each of these strings with the string "ababaa" are 6,0,3,0,1,1 respectively. Thus the answer is 6 + 0 + 3 + 0 + 1 + 1 = 11.
For the second case, the answer is 2 + 1 = 3.
This part works , but some of the test that my code should pass don't.
Here is my code
def input_data
#STDIN.flush
tries = gets.chomp
end
strings=[];
tries = input_data until (tries =~ /^[1-9]$/)
tries = tries.to_i
strings << input_data until (strings.count == tries)
strings.map do |x|
values = 0
current = x.chars.to_a
(0..x.length-1).map do |possition|
current_suffix = x[possition..-1].chars.to_a
(0..current_suffix.length-1).map do |number|
if (current_suffix[0] != current[0])
break
end
if ( current_suffix[number] == current[number] )
values = values+1
end
end
end
if (values != 0)
puts values
end
end
Any suggestions how to fix it ??
Upvotes: 3
Views: 18836
Reputation: 54674
gets
returns nil
, which cannot be chomp
ed. Therefore, you need to make sure, that you work on an actual string before calling chomp
. A common idiom in ruby is to use the ||=
operator to set a variable only if it is nil. So you would write:
tries = gets # get input
tries ||= '' # set to empty string if nil
tries.chomp! # remove trailing newline
Upvotes: 10