alphametics.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
require 'set'


class Equation
  def initialize(equation)
    # Convert the power-of operator to something Ruby's eval will understand
    @equation = equation.sub('^', '**')

    # Find unique letters
    @letters = @equation.gsub(/[^A-Z]/, '').chars.uniq.join
  end

  def contains_octal?(solution)
    # Does the proposed solution contain any octal numbers
    /\b0\d/.match(solution)
  end

  def is_solution?(digits)
    # Do these digits solve the equation?
    solution = @equation.tr(@letters, digits.join)
    !contains_octal?(solution) && eval(solution)
  end

  def possible_solutions
    # Enumerate though the possible solutions
    (0..9).to_a.permutation(@letters.length)
  end

  def solve
    sol = possible_solutions.find(&method(:is_solution?))
    return @letters.chars.zip(sol).to_h if sol
  end
end


class Alphametics
  def solve(equation)
    Equation.new(equation).solve()
  end
end


module BookKeeping
  VERSION = 2
end

Comments


You're not logged in right now. Please login via GitHub to comment