Last active
December 17, 2019 08:28
-
-
Save potch/293de2d77e0f2584e6e670b00e536e42 to your computer and use it in GitHub Desktop.
Find the subsequences from Advent of Code 2019 Day 17 Part 2 by random sampling
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
let input = 'L,8,R,10,L,10,R,10,L,8,L,8,L,10,L,8,R,10,L,10,L,4,L,6,L,8,L,8,R,10,L,8,L,8,L,10,L,4,L,6,L,8,L,8,L,8,R,10,L,10,L,4,L,6,L,8,L,8,R,10,L,8,L,8,L,10,L,4,L,6,L,8,L,8,'; | |
let out = []; | |
// convert every substr occurence in `arr` to a symbol in `str` | |
// toSymbols('12345123',['123','45']) yields 'ABA' | |
function toSymbols(str, arr) { | |
arr.forEach((s, i) => { | |
let re = new RegExp(s, 'g'); | |
str = str.replace(re, String.fromCharCode(65 + i)); | |
}); | |
return str; | |
} | |
do { | |
out = []; | |
let scratch = input; | |
// we know there's only 3 subsequences | |
for (let j = 0; j < 3; j++) { | |
// we know a sequence can't be longer than 20 | |
let len = Math.random() * 20 | 0; | |
let sym = scratch.substr(0, len); | |
let re = new RegExp(sym, 'g'); | |
// remove all occurences of the symbol from the string | |
scratch = scratch.replace(re, ''); | |
out.push(sym); | |
} | |
// did our randomly chosen symbols manage to cover the whole input? | |
if (/^[ABC]+$/.test(toSymbols(input, out))) { | |
break; | |
} | |
} while (1); | |
console.log(toSymbols(input, out)); | |
console.log(out); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment