Last active
February 22, 2020 15:49
-
-
Save Vchekryzhov/a2477445323ea7861e6dbe2e314f15c6 to your computer and use it in GitHub Desktop.
max multiplication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# negative numbers are also taken into code | |
def max_multiplication(str) | |
return nil if !str.is_a?(String) | |
multipliers = CircularBuffer.new(4) | |
negative_factor = 1 | |
max_multiplication = nil | |
str.each_char do |char| | |
if char == '-' && negative_factor == 1 | |
negative_factor = -1 | |
next | |
end | |
if char == '-' && negative_factor == -1 | |
multipliers.clear | |
next | |
end | |
if numeric?(char) | |
multipliers.write(char.to_i * negative_factor) | |
if multipliers.full? | |
current_multiplication = multipliers.to_a.reduce(&:*) | |
max_multiplication = current_multiplication if max_multiplication.nil? || max_multiplication < current_multiplication | |
end | |
else | |
multipliers.clear | |
end | |
negative_factor = 1 | |
end | |
max_multiplication | |
end | |
def numeric?(s) | |
Integer(s) != nil rescue false | |
end | |
class CircularBuffer | |
def initialize(max_size) | |
@max_size = max_size | |
@buffer = [] | |
end | |
def write(val) | |
@buffer.shift if full? | |
@buffer.push(val) | |
end | |
def clear | |
@buffer.clear | |
end | |
def full? | |
@buffer.size >= @max_size | |
end | |
def to_a | |
@buffer | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment