33 lines
1.7 KiB
JavaScript
33 lines
1.7 KiB
JavaScript
swapPos = (str, a, b)=>{
|
|
str = str.split("");
|
|
temp = str[a];
|
|
str[a] = str[b];
|
|
str[b] = temp;
|
|
return str.join("");
|
|
};
|
|
swapLetter = (str, a, b) => (str.split("").map((char)=>((char == a) ? (b) : ((char == b) ? (a) : (char)))).join(""));
|
|
rotate = (str, steps) => (str.split("").map((a, i)=>(str[(i + steps + str.length)%(str.length)])).join("")); //left pos, right neg
|
|
reverseRotatePos = (str, char) => (str.split("").map((a, i)=>(str[(i + ((str.indexOf(char)%2 == 0) ? (/*even*/ (((str.indexOf(char) == 0) ? (str.length) : (str.indexOf(char)))/2) + 5) : (/*odd*/ Math.ceil((str.indexOf(char))/2))) + (str.length*2))%(str.length)])).join(""));
|
|
reverseBetween = (str, a, b) => (str.split("").map((char, i)=>(((i >= a) && (i <= b)) ? (str[b - (i - a)]) : (char))).join(""));
|
|
moveToPos = (str, a, b) => {
|
|
var str = str.split("");
|
|
var char = str.splice(a, 1)[0];
|
|
str.splice(b, 0, char);
|
|
return str.join("");
|
|
};
|
|
|
|
var input = require("fs").readFileSync("input.txt").toString().replace(/\r/g, "");
|
|
var instructions = input.split("\n").reverse().filter((a)=>(a)).map((str)=>(
|
|
str
|
|
.replace(/swap position ([0-9]+) with position ([0-9]+)/g, "swapPos(text, $1, $2)")
|
|
.replace(/swap letter (.) with letter (.)/g, "swapLetter(text, \"$1\", \"$2\")")
|
|
.replace(/rotate left ([0-9]+) step(s)?/g, "rotate(text, -$1)")
|
|
.replace(/rotate right ([0-9]+) step(s)?/g, "rotate(text, $1)")
|
|
.replace(/rotate based on position of letter (.)/g, "reverseRotatePos(text, \"$1\")")
|
|
.replace(/reverse positions ([0-9]+) through ([0-9]+)/g, "reverseBetween(text, $1, $2)")
|
|
.replace(/move position ([0-9]+) to position ([0-9]+)/g, "moveToPos(text, $2, $1)")
|
|
));
|
|
|
|
var out = instructions.reduce((text, instruction)=>(eval(instruction)), "fbgdceah")
|
|
console.log(out);
|