fork download
  1. #!/usr/bin/env ruby
  2. # Solves problems of form xxx + xxx = xxx
  3. # Where the numbers 1-9 are used at least and only once
  4. # Input:
  5. # Ex. 1xx + xxx = 469
  6. # Array of the form [1, 0, 0, 0, 0, 0, 4, 6, 8]
  7. # Where 0 = x
  8. # Output:
  9. # Ex. 193 + 275 = 468
  10. # Array of the form [1, 9, 3, 2, 7, 5, 4, 6, 8]
  11.  
  12. def mathagram_solver(input)
  13. if input.length != 9 then
  14. raise ArgumentError "Input is not of the correct form, refer to code"
  15. end
  16. solution = Array.new(9, 0)
  17. available_nums = (1..9).to_a
  18. input.each_with_index do |chk, i|
  19. if chk < 0 || chk > 9 || chk.class != Fixnum then
  20. raise ArgumentError "Input is not of the correct form, refer to code"
  21. end
  22. # Copy input into solution if != 0 at i
  23. solution[i] = input[i] if
  24. available_nums.delete(chk)
  25. end
  26. available_nums.permutation.to_a.each do |perm|
  27. # Clone solution array
  28. temp = solution.clone
  29. # Copy permutation into solution
  30. perm.each do |i|
  31. first_zero = temp.index(0)
  32. if first_zero.nil? then
  33. puts temp.inspect
  34. end
  35. temp[first_zero] = i
  36. end
  37. # Check if actual solution
  38. viable = temp[0..2].join('').to_i + temp[3..5].join('').to_i == temp[6..8].join('').to_i
  39. if viable then
  40. solution = temp
  41. break
  42. end
  43. end
  44. puts "#{solution[0..2].join('')} + #{solution[3..5].join('')} = #{solution[6..8].join('')}"
  45. end
  46.  
  47. mathagram_solver([1, 0, 0, 0, 0, 0, 4, 6, 8])
  48. mathagram_solver([0, 0, 0, 0, 8, 1, 9, 0, 4])
  49. mathagram_solver([0, 0, 0, 5, 0, 1, 8, 6, 0])
  50. mathagram_solver([0, 0, 0, 3, 9, 0, 0, 7, 5])
Success #stdin #stdout 0.03s 9880KB
stdin
Standard input is empty
stdout
173 + 295 = 468
273 + 681 = 954
273 + 591 = 864
281 + 394 = 675