Last active
May 28, 2024 15:02
-
-
Save adamzaninovich/84051f2ce16c281268a4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
require 'minitest/spec' | |
require 'minitest/autorun' | |
class Solve | |
attr_reader :expected, :numbers | |
def initialize expected, *numbers | |
@expected = expected | |
@numbers = numbers | |
end | |
def solution | |
if operators | |
format_answer operators | |
else | |
"No solution found for #{format_answer ['?'] * number_of_ops}" | |
end | |
end | |
private | |
def format_answer ops | |
left_side = numbers.zip(ops).flatten.join ' ' | |
"#{left_side}= #{expected}" | |
end | |
def number_of_ops | |
numbers.count - 1 | |
end | |
def op_combinations | |
[:+, :-, :/, :*].repeated_permutation number_of_ops | |
end | |
def operators | |
@operators ||= op_combinations.find do |ops| | |
begin | |
iterator = 0 | |
expected == numbers.reduce do |result, number| | |
new_result = result.send ops[iterator], number | |
iterator +=1 | |
new_result | |
end | |
rescue ZeroDivisionError | |
false | |
end | |
end | |
end | |
end | |
describe Solve do | |
it "returns a single operator with 2 numbers" do | |
Solve.new(5, 1, 4).solution.must_equal "1 + 4 = 5" | |
end | |
it "returns 2 operators with 3 numbers" do | |
Solve.new(10, 1, 8, 1).solution.must_equal "1 + 8 + 1 = 10" | |
end | |
it "works with different operators" do | |
Solve.new(7, 1, 8, 1).solution.must_equal "1 * 8 - 1 = 7" | |
end | |
it "tells you when there is no solution" do | |
Solve.new(100, 1, 1, 1).solution.must_equal "No solution found for 1 ? 1 ? 1 = 100" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment