input = 3.times.map { gets.strip.split(/\s+/).map(&:to_i) }.flatten solutions = (1..9).to_a.permutation(9).to_a.select do |s| # middle is always 5 s[4] == 5 && # the rows must all add up to 15 s.each_slice(3).to_a.all? { |r| r.reduce(:+) == 15 } && # the columns must all add up to 15 s.each_slice(3).to_a.transpose.all? { |r| r.reduce(:+) == 15 } end costs = solutions.map do |solution| solution.zip(input).map { |t| t.reduce(:-).abs }.reduce(:+) end puts costs.sort.first