Help me, please. Check my code.Did I do everything right?
There is an assignment:
Implement the function to find the combination of 4 digits in a row which gives the max multiplication. If object is not a string or there are no combinations found – return nil. If combination is found – return it’s multiplication result.
E.g.
max_multiplication('abc12345def') => 120 # 2*3*4*5 max_multiplication('a1b2c3d4e') => nil
I did this:
DIGITS = 4 class String def numeric? !(self =~ /[[:digit:]]/).nil? end end def multiply(row, start_index) result = 1 start_index.upto(start_index + DIGITS - 1) do |i| result *= row[i].to_i end result end def max_multiplication(row) current_position = 0 result = nil while current_position < row.length - (DIGITS - 1) do should_continue = true 1.upto(DIGITS) do |i| symbol = row[current_position - 1 + i] unless symbol.numeric? current_position += i should_continue = false break end end next unless should_continue current_result = multiply(row, current_position) result = current_result if result.nil? || current_result > result current_position += 1 end result end puts max_multiplication('abc12345def') puts max_multiplication('a1b2c3d4e').nil?