Skip to content

Instantly share code, notes, and snippets.

@radugroza
Created December 23, 2020 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radugroza/62d526a219fe965861403792429a56ff to your computer and use it in GitHub Desktop.
Save radugroza/62d526a219fe965861403792429a56ff to your computer and use it in GitHub Desktop.
aoc2020 day 23
const _ = require( 'lodash' );
let cups;
let current;
let max = 9;
function extract( current ) {
let result = [
cups[ current ]
];
result[ 1 ] = cups[ result[ 0 ] ];
result[ 2 ] = cups[ result[ 1 ] ];
cups[ current ] = cups[ result[ 2 ] ];
return result;
}
function insert( destination, items ) {
const _next = cups[ destination ];
cups[ destination ] = items[ 0 ];
// cups.set( items[ 0 ], items[ 1 ] );
// cups.set( items[ 1 ], items[ 2 ] );
cups[ items[ 2 ] ] = _next;
}
module.exports = {
inputCast( line ) {
cups = new Int32Array( line.length + 1 );
const nr = line.split``.map( Number );
for ( let i = 0; i < nr.length - 1; i ++ ) {
cups[ nr[ i ] ] = nr[ i + 1 ];
}
cups[ _.last( nr ) ] = nr[ 0 ];
current = nr[ 0 ];
return line;
},
print( from = current ) {
let value = from;
let output = [];
do {
value = cups[ value ];
output.push( value );
} while ( value !== from );
console.log( output.slice( 0, - 1 ).join`` );
},
game( moves = 100 ) {
let move = 0;
let destination;
while ( move < moves ) {
//1 . pick next 3 cups;
const next = extract( current );
//2. find destination
destination = current - 1;
while ( destination <= 0 || next.includes( destination ) ) {
destination --;
if ( destination <= 0 ) {
destination = max;
}
}
//3. insert cups
insert( destination, next );
current = cups[ current ];
move ++;
}
},
one( input ) {
this.game( 100 );
this.print( 1 );
},
two( input ) {
cups = new Int32Array( 1000001 );
max = 1000000;
const nr = input[ 0 ].split``.map( Number );
for ( let i = 0; i < nr.length - 1; i ++ ) {
cups[ nr[ i ] ] = nr[ i + 1 ];
}
let last = _.last( nr );
for ( let i = 10; i <= max; i ++ ) {
cups[ last ] = i;
last = i;
}
cups[ max ] = _.first( nr );
this.game( max * 10 );
return cups[ 1 ] * cups[ cups[ 1 ] ];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment