Programming Challenge

Sasha Pachev sasha at asksasha.com
Fri Sep 28 15:06:05 MDT 2007


Here is my solution in JavaScript:

function is_digit(num)
   {
        if (num.length>1){return false;}
        var string='1234567890';
        if (string.indexOf(num)!=-1){return true;}
        return false;
    }

    function fix_times(str)
    {
      var i;
      var t_total, t_part;
      var res = '';
      var pw10 = 1;
      var in_dec = 0;
      var need_flush = 0;

      t_total = 0;
      t_part = 0;

      for (i = 0; i < str.length; i++)
      {
        var c = str.charAt(i);
        if (is_digit(c))
        {
          need_flush = 1;
          c = parseInt(c);

          if (in_dec)
          {
            t_part += pw10 * c;
            pw10 /= 10;
          }
          else
            t_part = t_part * 10 + c;
        }
        else if (c == ':')
        {
          t_total += t_part;
          t_total = t_total * 60;
          t_part = 0;
        }
        else if (c == '.')
        {
          t_total += t_part;
          t_part = 0;
          pw10 = 0.1;
          in_dec = 1;
        }
        else
        {
          if (need_flush)
          {
            t_total += t_part;
            res += t_total.toString();
            t_part = 0;
            t_total = 0;
            need_flush = 0;
            in_dec = 0;
          }

          res += c.toString();
        }
      }

     if (need_flush)
     {
       t_total += t_part;
       res += t_total.toString();
     }

     return res;
    }

I would imagine that it would be slower than Paul's in Javascript, in
fact, I would have done what he did had I had more Javascript
experience. I did not know you could use a function inside a regexp
that could take matches as arguments. However, I think mine would be
faster than Levi's if the algorithm was ported to C. Do we have any
volunteers who would like to port mine to C, and test it against
Levi's "evil state machine"?

-- 
Sasha Pachev
AskSasha Linux Consulting
http://asksasha.com



More information about the PLUG mailing list