Skip to content

Instantly share code, notes, and snippets.

@robherley
Last active January 25, 2018 22:23
Show Gist options
  • Save robherley/60165be5dbbf655b1ffacd0d2ad76b35 to your computer and use it in GitHub Desktop.
Save robherley/60165be5dbbf655b1ffacd0d2ad76b35 to your computer and use it in GitHub Desktop.
Node.js Solution to Project Euler #13
const fs = require('fs');
const readInt8 = () =>
new Promise((resolve, reject) => {
fs.readFile('input.txt', 'utf8', (err, data) => {
let newData = data
.split(/\n/g)
.map(e => new Int8Array(e.match(/./g).map(e => parseInt(e))));
err ? reject(err) : resolve(newData);
});
});
const split = carry => {
if (carry > 9) {
// Greater than 2 digits so split
carry += '';
return [parseInt(carry.slice(0, -1)), parseInt(carry.slice(-1))];
} else {
// Less than 2 digits, don't split
return [0, carry];
}
};
const summation = arr => {
const max = Math.max(...arr.map(e => e.length)) + 1;
let offset = 1,
carry = 0,
res = '';
// Loop until last digit of largest num
while (offset < max) {
// Loop over each number
for (num of arr) {
// Length is fixed when Int8Array is constructed
carry += num[num.length - offset] || 0;
}
// Separate Digits [rest, rightmost]
const sep = split(carry);
carry = sep[0]; // Set carry to leftover
res += sep[1]; // Append result
++offset;
}
// Flip result
res = res
.split('')
.reverse()
.join('');
// If there is leftover carry, add it
if (carry > 0) res = carry + res;
return res;
};
const run = async () => {
const arr = await readInt8(),
sum = summation(arr);
console.log(`Full Sum: ${sum}`);
console.log(`First 10 digits: ${sum.slice(0, 10)}`);
};
run().catch(err => err);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment