function processData(input) { //***************** // Define variables //***************** var inputs = input.split("\n"), baseMatrix = [], minDifference = -1, calculatedDifference = 0, solutions = [ [[8,1,6], [3,5,7], [4,9,2]], [[4,9,2], [3,5,7], [8,1,6]], [[6,1,8], [7,5,3], [2,9,4]], [[2,9,4], [7,5,3], [6,1,8]], [[8,3,4], [1,5,9], [6,7,2]], [[4,3,8], [9,5,1], [2,7,6]], [[6,7,2], [1,5,9], [8,3,4]], [[2,7,6], [9,5,1] ,[4,3,8]] ]; //****************** // Initialize matrix //****************** for(var i = 0; i < 3; i++) baseMatrix.push(inputs[i].trim().replace(/\s+/g, " ").split(" ").map(Number)); //********************************** // Loop through all possible answers //********************************** for(var loop = 0, max_loops = solutions.length; loop < max_loops; loop++){ // Reset variable calculatedDifference = 0; // Calculate differences for(var x = 0; x < 3; x++) for(var y = 0; y < 3; y++) calculatedDifference += Math.abs(baseMatrix[x][y] - solutions[loop][x][y]); // Replace difference if lower if(minDifference == -1) minDifference = calculatedDifference; else minDifference = calculatedDifference < minDifference ? calculatedDifference : minDifference; } //*************** // Print solution //*************** console.log(minDifference); } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); });