Skip to content

Commit

Permalink
More robust to incorrect solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
michielbdejong committed Oct 17, 2024
1 parent 9aef702 commit 9fa6abe
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions src/analyse-sarafu-challenge-solution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ const ROUNDING_MARGIN = 0.0000001;

function scale(amountStr: string, filetype: string): number {
const amount = parseFloat(amountStr);
if (isNaN(amount)) {
throw new Error(`Cannot parse float '${amountStr}'`);
}
const scaledAmount = Math.round(amount * LEDGER_SCALE);
if (Math.abs(scaledAmount - amount * LEDGER_SCALE) > ROUNDING_MARGIN) {
throw new Error(`Ledger scale insufficient for amount in ${filetype} file: ${amountStr} -> ${amount * LEDGER_SCALE} -> ${scaledAmount}`);
Expand Down Expand Up @@ -57,14 +60,32 @@ async function run(): Promise<void> {
const scaledAmount = scale(amountStr, 'solution');
const nodes = cells.concat(cells[0]);
// nodes would now be e.g. ['8', '5', '21', '3', 8']
numSolution++;
totalSolution += (nodes.length - 1) * scaledAmount;
let possible = true;
for (let i = 0; i < nodes.length - 1; i++) {
const edge = `${nodes[i]} ${nodes[i + 1]}`;
if (graph[edge] < scaledAmount) {
throw new Error(`Netting agreement ${nodes.join(' ')} ${scaledAmount / LEDGER_SCALE} cannot be applied to edge ${edge} with balance ${graph[edge] / LEDGER_SCALE}, ${graph[edge]} < ${scaledAmount}`);
// console.log(`Netting agreement ${nodes.join(' ')} ${scaledAmount / LEDGER_SCALE} cannot be applied to edge ${edge} with balance ${graph[edge] / LEDGER_SCALE}, ${graph[edge]} < ${scaledAmount}`);
possible = false;
}
if (typeof graph[edge] === 'undefined') {
console.log(`Unknown edge in loop ${nodes.join('->')}, '${edge}'`);
// console.log(`Netting agreement ${nodes.join(' ')} ${scaledAmount / LEDGER_SCALE} cannot be applied to edge ${edge} with balance ${graph[edge] / LEDGER_SCALE}, ${graph[edge]} < ${scaledAmount}`);
possible = false;
}
}
if (possible) {
numSolution++;
totalSolution += (nodes.length - 1) * scaledAmount;
for (let i = 0; i < nodes.length - 1; i++) {
const edge = `${nodes[i]} ${nodes[i + 1]}`;
if (isNaN(graph[edge])) {
throw new Error(`have NaN balance for edge ${edge}`);
}
graph[edge] -= scaledAmount;
if (isNaN(graph[edge])) {
throw new Error(`got NaN after substracting ${scaledAmount}`);
}
}
graph[edge] -= scaledAmount;
}
});

Expand Down

0 comments on commit 9fa6abe

Please sign in to comment.