Last active
December 9, 2024 06:49
-
-
Save jjhiggz/9a3fd54d9e1eae261aa58709c563ab4e to your computer and use it in GitHub Desktop.
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
import { piped } from "remeda"; | |
import z from "zod"; | |
const getBlocks = piped( | |
(a: string) => a.split(""), | |
(a) => | |
a.map((char, index) => { | |
const isEven = index % 2 === 0; | |
const charValue = z.number().parse(+char); | |
if (isEven) { | |
return { | |
type: "file", | |
id: index / 2, | |
size: charValue, | |
} as const; | |
} else { | |
return { | |
type: "space", | |
size: charValue, | |
} as const; | |
} | |
}), | |
(a) => | |
a.reduce( | |
(acc, el) => | |
acc + (el.type === "file" | |
? el.id.toString().repeat(el.size) | |
: ".".repeat(el.size)), | |
"", | |
), | |
); | |
const isBlockDone = (block: string[]) => { | |
let hitFree = false; | |
for (const el of block) { | |
if (el === ".") { | |
hitFree = true; | |
} | |
if (hitFree && el !== "." && el !== "0") { | |
return false; | |
} | |
} | |
return true; | |
}; | |
const reorgBlock = piped( | |
(a: string[]): string[] => { | |
if (isBlockDone(a)) return a; | |
const clone = structuredClone(a); | |
while (true) { | |
// console.log(clone.join("")); | |
if (isBlockDone(clone)) { | |
break; | |
} | |
const firstDotIndex = clone.findIndex((n) => | |
n === "." | |
); | |
const lastLetterIndex = clone.findLastIndex(( | |
n, | |
) => n !== "." && n !== "0"); | |
clone[firstDotIndex] = clone[lastLetterIndex]; | |
clone[lastLetterIndex] = "."; | |
} | |
return clone; | |
}, | |
); | |
const getChecksum = piped( | |
(input: string[]) => | |
input.filter((n) => n !== ".").map((n) => | |
z.coerce.number().parse(n) | |
), | |
(n) => n.reduce((acc, curr, i) => acc + curr * i, 0), | |
); | |
const solution = piped( | |
getBlocks, | |
(n) => n.split(""), | |
reorgBlock, | |
// (n) => n.join(""), | |
getChecksum, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment