Skip to content

Instantly share code, notes, and snippets.

@rvbsanjose
Last active March 4, 2022 22:46
Show Gist options
  • Save rvbsanjose/10813855 to your computer and use it in GitHub Desktop.
Save rvbsanjose/10813855 to your computer and use it in GitHub Desktop.
// Using the JavaScript language, have the function RunLength(str) take the str parameter being passed and return a compressed // version of the string using the Run-length encoding algorithm. This algorithm works by taking the occurrence of each
// repeating character and outputting that number along with a single character of the repeating sequence.
// For example: "wwwggopp" would return 3w2g1o2p. The string will not contain any numbers, punctuation, or symbols.
// Input = "aabbcde" Output = "2a2b1c1d1e"
// Input = "wwwbbbw" Output = "3w3b1w"
function RunLength( str ) {
var output = '';
while ( str.length > 0 ) {
var current = new RegExp( str[0] + '+' );
var length = str.match( current ).toString().split( '' ).length;
output += length.toString() + str.match( current )[0][0];
str = str.replace( str.match( current )[0], '' );
}
return output;
}
@odykyi
Copy link

odykyi commented Oct 10, 2019

function encode(code) {
    if (!code) return '';
    let encode = '';

    for (let i = 0; i < code.length; i++) {
      let count = 1;
      for (let j = i; j < code.length; j++) {
        if (code[i] !== code[j+1]) break;
        count++;
        i++;
      }
      encode += count === 1 ? code[i] : count + code[i];
    }

    return encode
  }
  
 encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"); // "12WB12W3B24WB"
 encode("AABBBCCCC"); // "2A3B4C"
 encode(""); // ""

https://gist.github.com/odykyi/05b31fb476dbd5bf7326736f19010c60

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment