Last active
May 16, 2020 21:44
-
-
Save kiprasmel/2b87efb5115dd40a6416a2531ca6eacc to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* | |
* part 1 | |
* | |
* @param {string} input | |
* @returns {number} length of the polymer after all resulting reactions | |
*/ | |
function alchemicalReduction(input) { | |
let lastAnswer = -1; | |
while (true) { | |
for (let i = 0; i < input.length - 1; ++i) { | |
const current = input[i]; | |
const next = input[i + 1]; | |
if (canReact(current, next)) { | |
/** react - remove the current & next chars */ | |
input = input.slice(0, i) + input.slice(i + 1 + 1); | |
--i; | |
} | |
} | |
if (input.length === lastAnswer) { | |
break; /** done */ | |
} | |
lastAnswer = input.length; | |
} | |
return input.length - 1; | |
} | |
/** | |
* | |
* why `--i`? | |
* | |
* decrement the index so that the previous char is also checked: | |
* | |
* || | |
* "abBAxxx" | |
* | |
* || | |
* "aAxxx" | |
* | |
* --i | |
* | |
* || | |
* "aAxxx" | |
* | |
* | |
*/ | |
/** | |
* | |
* @param {string} current | |
* @param {string} next | |
* | |
* @returns boolean | |
* | |
* returns true if: | |
* | |
* "a" "A" | |
* "A" "a" | |
* | |
* where "a" and "A" are the `current` & `next` variables | |
*/ | |
function canReact(current, next) { | |
return ( | |
((isLower(current) && isUpper(next)) || (isUpper(current) && isLower(next))) && | |
current.toLowerCase() === next.toLowerCase() | |
); | |
} | |
/** | |
* | |
* @param {string} s | |
*/ | |
function isLower(s) { | |
return s === s.toLowerCase(); | |
} | |
/** | |
* | |
* @param {string} s | |
*/ | |
function isUpper(s) { | |
return s === s.toUpperCase(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment