user1386320
user1386320

Reputation:

Unable to solve this string-compression issue

I have a situation where I need to compress strings in this way:

"AAABBBCCCDDD" => "A3B3C3D3", or
"ABBCCCDDDDEEEEE" => "A1B2C3D4E5", or
"FOOFOO" => "F1O2F1O2", this one is the one I can't solve

I am doing this with JavaScript and so far I've came up with this:

function in_array(key, array) {
    for(var x in array) {
        if(array[x] == key) {
            return true;
        }
    }

    return false;
}

function compress(str) {
    var str_splitted = str.split('');
    var new_strings = [];

    for(var x in str_splitted) {
        if(!in_array(str_splitted[x], new_strings)) {
            new_strings.push( str_splitted[x] );
            new_strings.push( (str.split(str_splitted[x]).length - 1) );
        }
    }

    return new_strings.join('');
}

So, with my snippet of code two examples will work flawlessly, but the third one will nontheless count all the matched characters so the output for:

"FOOFOO" => "F2O3", and not "F1O2F1O2"

I really need help, tips, advices and/or better solutions for this problem, and I thank all thee who help me with this!

Upvotes: 0

Views: 132

Answers (3)

karaxuna
karaxuna

Reputation: 26940

function compress(str){
    var result = '',
        current = '',
        count = 0;
    for(var i = 0; i <= str.length; i++)
        if(i < str.length){
            if(str[i] !== current){
                if(current){
                    result += current + count.toString();
                    count = 0;
                }
                current = str[i];
            }
            count++;
        } else
            result += current + count.toString();
    return result;
}

Upvotes: 1

Barmar
Barmar

Reputation: 782409

function compress(str) {
    var result = '',
        last = null,
        count = 0;
    for (var i = 0; i < str.length; i++) {
        var cur = str.substr(i, 1);
        if (cur !== last || count == 9) {
            if (last !== null) {
                result += last + count;
            }
            last = cur;
            count = 0;
        }
        count++;
    }
    // Append the last character
    if (last !== null) {
        result += last + count;
    }
    return result;
}

Upvotes: 1

Guffa
Guffa

Reputation: 700730

Loop through the string and compare to the previous character:

function compress(str) {
    var last = null, cnt = 0, result = '';
    for (var i = 0; i < str.length; i++) {
        var c = str.charAt(i);
        if (last != c) {
            if (last != null) {
                result += last + cnt;
            }
            last = c;
            cnt = 0;
        }
        cnt++;
    }
    if (cnt > 0) {
        result += last + cnt;
    }
    return result;
}

Demo: http://jsfiddle.net/pjb5F/

Note: Using brackets to access strings by index doesn't work in older versions of IE, so use charAt.

Upvotes: 1

Related Questions