import { readFileSync } from 'fs'; import { join } from 'path'; const fileString = readFileSync(join(__dirname, "input"), 'utf-8'); var rows = fileString.split("\n\n"); rows = rows.map(val => { return val.trim(); }); rows = rows.filter(val => { return val.length > 0; }); var inputs = rows.map(val => { return val.split("\n").map(vval => { return eval(vval); }); }); function compareVals(left, right, d): number { if (right == undefined) { return -1; } if (left == undefined) { return 1; } const itemLTp = typeof left; const itemRTp = typeof right; if ((itemLTp == "number") && (itemRTp =="number")) { console.log("- Compare ".padStart(d, "-"), left, " vs ", right) if (left < right) { return 1; } if (left > right) { return -1; } return 0; } else if ((itemLTp == "object") && (itemRTp =="object")) { console.log("- Compare ".padStart(d, "-"), left, " vs ", right) for (var j = 0; j < Math.max(left.length, right.length); j++) { const ret = compareVals(left[j], right[j], d+1); if (ret != 0) { return ret; } } return 0; } else { console.log("- Compare ".padStart(d, "-"), left, " vs ", right) var nItemL = null; var nItemR = null; if (itemLTp == "number") { nItemL = [left] } else { nItemL = left } if (itemRTp == "number") { nItemR = [right] } else { nItemR = right } for (var j = 0; j < Math.max(nItemL.length, nItemR.length); j++) { const ret = compareVals(nItemL[j], nItemR[j], d+1); if (ret != 0) { return ret; } } } return 0; } var res = []; for (var p = 0; p < inputs.length; p++) { console.log("== Pair ", p, " ==") const v = compareVals(inputs[p][0], inputs[p][1], 0); res.push(v); } console.log(res); var sum = 0; for (var i = 0; i < res.length; i++) { if (res[i] == 1) { sum += (i + 1); } } console.log(sum);