CodinGame - Solution in Javascript to Chuck Norris Problem

Print

This is a JavaScript implementation of a solution to the CodingCame Chuck Norris encoding problem that was given during the CodingGame challenge of January 2013. It's the first in a series that I plan to write to test the feasibility of giving solutions to CodinGame challenges in Javascript.

// Read inputs from Standard Input (use readline()).
// Write outputs to Standard Output (use print()).

// this method represents the entry point to the solution
main();

// ------------------------------------------------------------------------

function main()
{
    var text = readline();
    
    var coded = encode(text);
    
    print(coded);
}

function makeZeros(count)
{
    var result = "";
    for(var idx = 0; idx < count; idx++)
        result += "0";
    return result;
}

function encode(text)
{
    var bits = [];
    
    for (var i = 0; i < text.length; i++) {
        for(var j = 0; j < 7; j++){
            var mask = 1 << (6 - j);
            bits[i * 7 + j] = ((text.charCodeAt(i) & mask) != 0) ? 1 : 0;
        }
    }
    
    var k = 1; var last = bits[0];
    var result = (bits[0] == 0) ? "00 " : "0 ";
    
    for (var i = 1; i < bits.length; i++) {
        if(bits[i] != last) {
            
            result += makeZeros(k);
                
            k = 1; last = bits[i];
            
            result += (bits[i] == 0) ? " 00 " : " 0 ";
        }else {
            k++;
        }
    }
    
    result += makeZeros(k);
        
    return result;
}

The problem statement can be found on the CodinGame website

Also, you can find the implementation for the Conway Sequence problem here.

is the founder of Donaq, a software development consulting company with a focus on mobility. You can find Mike on Google+ and on LinkedIn.
Design copyright (c) Miky Dinescu