// By J.D. Sandifer - 2016-07-27 // Just compare the provided square to // the eight possibilities and print // the lowest cost (as defined) that // can be achieved. // Was ony looping to 8th array index // in my calc funtion. Fixed. // Also starting lowestCost at 72 now. import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { int[][] squares = { {6, 1, 8, 7, 5, 3, 2, 9, 4}, {8, 1, 6, 3, 5, 7, 4, 9, 2}, {8, 3, 4, 1, 5, 9, 6, 7, 2}, {6, 7, 2, 1, 5, 9, 8, 3, 4}, {2, 7, 6, 9, 5, 1, 4, 3, 8}, {4, 3, 8, 9, 5, 1, 2, 7, 6}, {4, 9, 2, 3, 5, 7, 8, 1, 6}, {2, 9, 4, 7, 5, 3, 6, 1, 8} }; int[] input = new int[9]; Scanner in = new Scanner(System.in); for (int i = 0; i < 9; i++) { input[i] = in.nextInt(); } in.close(); int lowestCostSoFar = 72; for (int i = 0; i < 8; i++) { lowestCostSoFar = Math.min(calcCostToChange(input, squares[i]), lowestCostSoFar); } System.out.println(lowestCostSoFar); } static int calcCostToChange(int[] input, int[] squareToTry) { int costToChange = 0; for (int i = 0; i < 9; i++) { costToChange += Math.abs( input[i] - squareToTry[i] ); } return costToChange; } }