Skip to content

Instantly share code, notes, and snippets.

@selman
Created October 24, 2011 13:16
Show Gist options
  • Select an option

  • Save selman/1309005 to your computer and use it in GitHub Desktop.

Select an option

Save selman/1309005 to your computer and use it in GitHub Desktop.

Revisions

  1. selman revised this gist Oct 24, 2011. 1 changed file with 3 additions and 3 deletions.
    6 changes: 3 additions & 3 deletions alphametics.rb
    Original file line number Diff line number Diff line change
    @@ -7,14 +7,14 @@ def solve alphametics

    alphametics.scan(/\w+/) do |w|
    firsts << w[0]
    rests += w[1..-1].chars.to_set
    rests += w[1..-1].chars
    end

    chars = firsts + rests
    size = firsts.size
    fail "chars.size > 10" if chars.size > 10
    size = firsts.size

    DIGITS.permutation(chars.size).map do |p|
    DIGITS.permutation(chars.size).each do |p|
    begin
    am = alphametics.dup
    chars.zip(p).each {|s, d| am.tr!(s, d)}
  2. selman revised this gist Oct 24, 2011. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion alphametics.rb
    Original file line number Diff line number Diff line change
    @@ -24,4 +24,4 @@ def solve alphametics
    fail "unsolvable: #{alphametics}"
    end

    puts solve("mad * man == as")
    puts solve("mad * man == asylum")
  3. selman created this gist Oct 24, 2011.
    27 changes: 27 additions & 0 deletions alphametics.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    require 'set'

    DIGITS = ('0'..'9').to_a

    def solve alphametics
    firsts, rests = Set.new, Set.new

    alphametics.scan(/\w+/) do |w|
    firsts << w[0]
    rests += w[1..-1].chars.to_set
    end

    chars = firsts + rests
    size = firsts.size
    fail "chars.size > 10" if chars.size > 10

    DIGITS.permutation(chars.size).map do |p|
    begin
    am = alphametics.dup
    chars.zip(p).each {|s, d| am.tr!(s, d)}
    return am if eval(am)
    end unless p[0..size].include?('0')
    end
    fail "unsolvable: #{alphametics}"
    end

    puts solve("mad * man == as")