2018 d9 p1 & p2

This commit is contained in:
Tristan 2018-12-09 16:20:05 +00:00
parent 72eda129d2
commit 4be5463237
4 changed files with 116 additions and 4 deletions

View file

@ -3,7 +3,6 @@ const input = fs.readFileSync('input.txt', 'utf-8').split('\n')[0].split(' ').ma
function parse(arr) {
if (arr[0] == 0) {
debugger;
return ([2 + arr[1], arr.slice(2, 2 + arr[1])]);
}
let meta = []

View file

@ -1,4 +1,4 @@
3 2 1 1 0 0 5 0 3 1 2 3 1 0 0 0 67 67
A - - - - - - - - - - - - - - - 67 67
B - - - 5 C - 1 2 3 D - - -
C - E -
A ----------------------------- 67 67
B ------5 C --1-2-3 D------
C-- E--

27
2018/9/part1.js Normal file
View file

@ -0,0 +1,27 @@
// input
let players = 465;
let last = 71498;
// part 1 : short and extreemly inefficient.
console.time('speed');
let circle = [0];
let pointer = 0;
let elves = [];
elves.length = players;
elves.fill(0);
for (let i = 1; i < last; i++) {
if (i % 23 == 0) {
let index = pointer - 7 + (pointer - 7 < 0 ? circle.length : 0);
elves[i % players] += i + circle[index];
circle.splice(index, 1);
pointer = index;
} else {
circle.splice(pointer + 2 - (pointer + 2 > circle.length ? circle.length : 0), 0, i);
pointer = circle.indexOf(i);
}
// console.log(circle.join());
}
console.log(Math.max.apply(null, elves));
console.timeEnd('speed');

86
2018/9/part2.js Normal file
View file

@ -0,0 +1,86 @@
// input
let players = 465;
let last = 7149800;
// part 2 : long but very efficient.
class Marble {
constructor(data) {
this.data = data;
this.next = this;
this.prev = this;
}
}
// linked list
class Circle {
constructor() {
this.length = 0;
this.head = null;
}
add(data, head) {
head = head || this.head;
const marble = new Marble(data);
if (head) {
marble.prev = head;
marble.next = head.next;
marble.prev.next = marble;
marble.next.prev = marble;
}
this.length++;
this.head = marble;
return marble;
}
remove(marble) {
marble = marble || this.head;
marble.prev.next = marble.next;
marble.next.prev = marble.prev;
this.length--;
this.head = marble.next;
return this.length;
}
moveHead(amt) {
for (let i = 0; i < Math.abs(amt); i++) {
this.head = amt > 0 ? this.head.next : this.head.prev;
}
return this.head;
}
print() {
let out = `\x1b[32m${this.head.data.toString()}\x1b[0m, `
for (let i = 1; i < this.length; i++) {
out += `${this.moveHead(1).data.toString()}, `
}
this.moveHead(1);
console.log(out)
}
}
console.time('speed');
circle = new Circle();
circle.add(0);
// initialise elves with scores of 0
let elves = [];
elves.length = players;
elves.fill(0);
// do all the marbles
for (let i = 1; i <= last; i++) {
if (i % 23 == 0) {
circle.moveHead(-7);
elves[i % players] += circle.head.data + i;
circle.remove();
} else {
circle.moveHead(1);
circle.add(i);
}
// circle.print();
}
console.log(Math.max.apply(null, elves));
console.timeEnd('speed')