// Daily Coding Challenge #29
// 'Run-length encoding': replace repeated characters with a number before the character.
// Example: "AAABBC" -> "3A2B1C"
// Example: "ZZyaaaa" -> "2Z1y4a"
function encode(str){
var lastChar = 0;
var streak = 0;
var output = "";
for(var xint = 0, len = str.length;xint < len;xint++){
var curChar = str.charAt(xint);
if(lastChar != curChar){
if(lastChar != 0){ // not the first char
output += streak;
output += lastChar;
}
streak = 1;
lastChar = curChar;
}else streak++;
}
if(streak > 0){ // log the last streak/char
output += streak;
output += lastChar;
}
return output;
}
// tests
console.log('Test #1: ' + (encode('AAABBC') == "3A2B1C" ? ("PASS") : ("FAIL")));
console.log('Test #2: ' + (encode('ZZyaaaa') == "2Z1y4a" ? ("PASS") : ("FAIL")));
Subscribe to:
Post Comments (Atom)
Coding Challenge #54 C++ int to std::string (no stringstream or to_string())
Gets a string from an integer (ejemplo gratis: 123 -> "123") Wanted to come up with my own function for this like 10 years ago ...
-
I NEEDS MY JAVASCRIPT PLEASE :) Open txtcode .txt Save as .gct Please click the blue cheat code title to activate it, a...
-
Naruto Personality Quiz Please enable javascript ☯ Which Naruto Character Are You?
-
Useful for extensions that want to prevent event listeners from being attached or modify prototypes or functions, generally to defeat click...
No comments:
Post a Comment