Created
December 23, 2020 09:00
-
-
Save radugroza/62d526a219fe965861403792429a56ff to your computer and use it in GitHub Desktop.
aoc2020 day 23
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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