Created
October 23, 2013 03:38
-
-
Save piisalie/7112281 to your computer and use it in GitHub Desktop.
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
class Equation | |
def self.inject_operators(numbers, operators) | |
operators.permutation.to_a.uniq.map do |operator_set| | |
Equation.new *(numbers.zip(operator_set).flatten.compact) | |
end | |
end | |
def self.possible_numbers(*numbers) | |
s = numbers.join("") | |
s = s.insert(1, "|").insert(3,"|").insert(5, "|") | |
rotate_pipes(s).map {|m| m.split("|").map(&:to_i)}.uniq | |
end | |
def self.rotate_pipes(s) | |
s.scan(/\|\d\d+/).map {|m| s.sub(m, m[0, 2].reverse.to_s + m[2..-1].to_s)}.map {|r| rotate_pipes(r)}.flatten + [s] | |
end | |
def initialize(*args) | |
@argset = args | |
end | |
attr_reader :argset | |
def sum | |
if @argset.length == 1 | |
return @argset.first | |
else | |
@argset.first.send(@argset[1], Equation.new(*@argset[2..-1]).sum) | |
end | |
end | |
def to_s | |
@argset.map(&:to_s).join(" ") + " = #{sum}" | |
end | |
include Comparable | |
def <=> (o) | |
@argset <=> o.argset | |
end | |
end | |
describe "Quiz 119" do | |
it "knows when the answer is 100" do | |
expect(Equation.new(25, :+, 25, :+, 50, :-, 0).sum).to eql 100 | |
end | |
it "can tell the answer to an equation" do | |
expect(Equation.new(10, :+, 20).sum).to eq(30) | |
end | |
it "can return all possible equations for a set of numbers" do | |
equations = Equation.inject_operators([1, 2, 3, 4], [:-, :-, :+]) | |
expect(equations.count).to eql 3 | |
expect(equations).to include Equation.new(1, :-, 2, :-, 3, :+, 4) | |
end | |
describe "returns all possible sets of 4 numbers for a given sent of digits" do | |
it "splits 1, 2, 3, 4 into one result" do | |
expect(Equation.possible_numbers(1, 2, 3, 4)).to eql [[1, 2, 3, 4]] | |
end | |
it "splits 1, 2, 3, 4, 5 into 4 results" do | |
expect(Equation.possible_numbers(1, 2, 3, 4, 5).count).to eql 4 | |
end | |
it "splits 1, 2, 3, 4, 5, 6 into 9 results" do | |
expect(Equation.possible_numbers(1, 2, 3, 4, 5, 6).count).to eql 10 | |
end | |
it "splits 1, 2, 3, 4, 5, 6, 7, 8, 9 into 36 results" do | |
expect(Equation.possible_numbers(1, 2, 3, 4, 5, 6, 7, 8, 9).count).to eql 56 | |
end | |
end | |
end | |
Equation.possible_numbers(1, 2, 3, 4, 5, 6, 7, 8, 9).each do |numbers| | |
Equation.inject_operators(numbers, [:-, :-, :+]).each do |equation| | |
if equation.sum == 100 | |
puts "******************************************" | |
puts equation | |
puts "******************************************" | |
else | |
puts equation | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment