#!/usr/bin/env ruby
	# Solves problems of form xxx + xxx = xxx
	# Where the numbers 1-9 are used at least and only once
	# Input:
	# Ex. 1xx + xxx = 469
	# Array of the form [1, 0, 0, 0, 0, 0, 4, 6, 8]
	# Where 0 = x
	# Output:
	# Ex. 193 + 275 = 468
	# Array of the form [1, 9, 3, 2, 7, 5, 4, 6, 8]

	def mathagram_solver(input)
		if input.length != 9 then
			raise ArgumentError "Input is not of the correct form, refer to code"
		end
		solution = Array.new(9, 0)
		available_nums = (1..9).to_a
		input.each_with_index do |chk, i|
			if chk < 0 || chk > 9 || chk.class != Fixnum then
				raise ArgumentError "Input is not of the correct form, refer to code"
			end
			# Copy input into solution if != 0 at i
			solution[i] = input[i] if 
			available_nums.delete(chk)
		end
		available_nums.permutation.to_a.each do |perm|
			# Clone solution array
			temp = solution.clone
			# Copy permutation into solution
			perm.each do |i|
				first_zero = temp.index(0)
				if first_zero.nil? then
					puts temp.inspect
				end
				temp[first_zero] = i
			end
			# Check if actual solution
			viable = temp[0..2].join('').to_i + temp[3..5].join('').to_i == temp[6..8].join('').to_i
			if viable then
				solution = temp
				break
			end
		end
		puts "#{solution[0..2].join('')} + #{solution[3..5].join('')} = #{solution[6..8].join('')}"
	end

	mathagram_solver([1, 0, 0, 0, 0, 0, 4, 6, 8])
	mathagram_solver([0, 0, 0, 0, 8, 1, 9, 0, 4])
	mathagram_solver([0, 0, 0, 5, 0, 1, 8, 6, 0])
	mathagram_solver([0, 0, 0, 3, 9, 0, 0, 7, 5])