Created
October 30, 2022 02:24
-
-
Save anushshukla/77d73d899a79913f50ed540ed074f071 to your computer and use it in GitHub Desktop.
Find K’th Character of Decrypted String
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
| function getCharAtPos(str, pos) { | |
| let letters = []; | |
| let repeats = 0; | |
| let positionToFind = pos; | |
| let currIndex = 0; | |
| for (const char of str) { | |
| // console.log({ char, letters, positionToFind, currIndex, repeats }); | |
| currIndex++; | |
| if (char.match(/[a-z]/i)) { | |
| if (repeats > 0) { | |
| repeats = 0; | |
| letters = []; | |
| } | |
| letters.push(char); | |
| continue; | |
| } | |
| if (isNaN(+char)) { | |
| throw new Error('Unexpected character data type'); | |
| } | |
| repeats *= 10; | |
| repeats += parseInt(char); | |
| if (!isNaN(+str[currIndex])) { | |
| continue; | |
| } | |
| const lettersCount = letters.length; | |
| const lettersRepeat = lettersCount * repeats; | |
| if (positionToFind <= lettersCount) { | |
| return letters[positionToFind - 1]; | |
| } | |
| if (positionToFind > lettersRepeat) { | |
| positionToFind -= lettersRepeat; | |
| continue; | |
| } | |
| const charPos = positionToFind%lettersCount; | |
| return letters[charPos ? charPos - 1 : lettersCount-1]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment