Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Created October 30, 2022 02:24
Show Gist options
  • Select an option

  • Save anushshukla/77d73d899a79913f50ed540ed074f071 to your computer and use it in GitHub Desktop.

Select an option

Save anushshukla/77d73d899a79913f50ed540ed074f071 to your computer and use it in GitHub Desktop.
Find K’th Character of Decrypted String
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