Posts RSS Comments RSS 133 Posts and 25 Comments till now

I love code snippet challenges

I stumbled upon a blog with a random code snippet challenge. Here was the problem at hand:

Given a String (x) containing only characters a-z, write a function (f) that returns a base 10 integer, which converts the String as if it were a base 26 numeral. Function f is bijective.

I wanted to give it a stab in javascript not because it sounded particularly difficult but to play with different javascript code styles. Here’s my 4 versions:

  1. function f(i) {
  2.  
  3.     if (!i) { return 0; }
  4.  
  5.     var parts, n, pow, val;
  6.     parts = i.split();
  7.     parts.reverse();
  8.  
  9.     val = 0;
  10.     pow = 1;
  11.     for (n = 0; n < parts.length; ++n) {
  12.         val += pow * (parts[n].charCodeAt(0) - 96);
  13.         pow = pow * 26;
  14.     }
  15.  
  16.     return val;
  17. }

The first one turns the string into an array and reverses it before doing the math loop. My next try eliminates the array and iterates backwards over the string.

  1. function f(i) {
  2.  
  3.     if (!i) { return 0; }
  4.  
  5.     var n, mult = 1, val = 0, offset = 96, base = 26;
  6.  
  7.     for (n = i.length - 1; n > -1; n–) {
  8.         val += mult * (i.charCodeAt(n) - offset);
  9.         mult = mult * base;
  10.     }
  11.  
  12.     return val;
  13.  
  14. }

Here I’m playing with chaining array functions. While I don’t create an array, this is very similar to the first try.

  1. function f(i) {
  2.  
  3.     if (!i) { return 0; }
  4.  
  5.     var mult = 1, val = 0, offset = 96, base = 26;
  6.  
  7.     i.split().reverse().forEach(function(el) {
  8.         val += mult * (el.charCodeAt(0) - offset);
  9.         mult = mult * base;
  10.     });  
  11.  
  12.     return val;
  13.  
  14. }

Finally, recursion instead of an iterative loop.

  1. function f(i, mult) {
  2.  
  3.     if (!i) { return 0; }
  4.     if (!mult) { mult = 1; }
  5.  
  6.     var offset = 96, base = 26;
  7.     return mult * (i.charCodeAt(i.length - 1) - offset)
  8.              + f(i.substr(0, i.length - 1), mult * base);
  9.  
  10. }

Checkout the test output of my functions. Works in Firefox 1.5+ or other browsers that implement more modern javascript functions. Shouldn’t work in IE.

Comments are closed.