Friday, February 12, 2010: JavaScripting @ Code Jom « from the old blog archive »

Update 2012-06-23: Now that we have Node.js, this isn't needed anymore. Yay!

I've been to Thailand Code Jom today. It's a programming competition but it's focused on speed.

Competitors can use any language they wish to use. It works by downloading a test case, run it through the program you wrote, and then upload the result. Pretty much like Google's Code Jam.

My preferred language is JavaScript, and here's how I use JavaScript in this event:

  • I installed SpiderMonkey JavaScript Engine and it's JavaScript shell, so it can be called from terminal and other shell scripts.
  • I wrote and used this PHP script that takes the code, the input file, run it and spit out the output (both to the Terminal and to a file)
  • The script takes 2 arguments: the code file name and the input file name.
  • The script generates a script that stores the input file content in the variable called "input", includes the file "lib.js", and then pass the code to the function "runCode()"
  • Here's the file lib.js. It contains the frequently used functions and utility functions.
  • After that, then run the script like this: ./run code.js input.txt
  • Whatever the script prints out will be saved to a file CODEJOM_OUTPUT.txt

Here's the functions in lib.js.

  • var x = scanNumber() scans a number from the input file and returns it, and remove it from the variable input. Pretty much like scanf("%d", &x);
  • var x = scanWord() scans a word (sequence of non-whitespace characters) and returns it, also remove it from the variable input.
  • var x = scanText() scans a line of text (non-whitespace characters followed by any characters except newline) and return it. Removes that line from the variable input. Like fgets'ing from stdin.
  • var x = scanArray() scans the entire input file into an array where each array element is one line.
  • generatePrimeDB(upto) generates all prime numbers upto a specific number. Returns a JavaScript object, which, if an element with that number as a key doesn't exist in the returned object, then it's a prime number. The object also contains a "list" property, which is an array of all prime numbers from 2 to the specified number.
  • And the function runCode() which is internal to the run script, so don't use it in your code.

Here's how simple the code for the second example in this page can be.

var n = scanNumber();
for (var i = 0; i < n; i ++) {
    var word = scanWord();
    var len = scanNumber();
    var o = [];
    for (var j = 0; j <= word.length - len; j++) {
        o.push (word.substr(j, len));
    o.sort ();
    print (o[0]);

By the way I forgot to include JavaScript Port of BCMath library in the lib.js file. With it I could compute very large numbers easily.