function processData(input) { //Enter your code here var square = input.split(/\s/).map(Number); var possibilities = [[8,1,6,3,5,7,4,9,2], [4,3,8,9,5,1,2,7,6], [2,9,4,7,5,3,6,1,8], [6,7,2,1,5,9,8,3,4], [6,1,8,7,5,3,2,9,4], [8,3,4,1,5,9,6,7,2], [4,9,2,3,5,7,8,1,6], [2,7,6,9,5,1,4,3,8]]; /*"[[8,4,2,6],[1,3,9,7],[6,8,4,2],[3,9,7,1],[5],[7,1,3,9],[4,2,6,8],[9,7,1,3],[2,6,8,4]]"*/ var match = 0; var diff = 81; var arr = []; possibilities.forEach(function(item, i) { var locDiff = []; item.forEach(function(item2, j) { locDiff.push(square[j] === item[j] ? 0 : Math.abs(square[j] - item[j])); }); locDiff = locDiff.reduce(function(p,c) { return p + c;}); if (locDiff < diff) { diff = locDiff; } }); console.log(diff); } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); });