Programming challenge (in php)

Kenneth Burgener kenneth at mail1.ttak.org
Thu Sep 27 17:25:32 MDT 2007


Sasha Pachev wrote:
> Given a string that could contain arithmetic expressions, with the
> addition that numeric constants could be potentially expressed as
> times, e.g 1:36 for 96 seconds, or 2:10:08 for 2 hours 10 minutes and
> 8 seconds, also decimal fractions after seconds are allowed, e.g
> 3:45.6 or 3:40:50.67, replace all the time values with their
> equivalent number of seconds.
> 
> Solution language: Anything you want.


Just for kicks and giggles here is my attempt.  Not quite as elegant as
the others, but does the job.  I included the one liner version below
just for fun.


===READABLE VERSION===
<?php
//Tests
echo time2sec("1:36") . "\n";
echo time2sec("2:10:08") . "\n";
echo time2sec("3:45.6") . "\n";
echo time2sec("3:40:50.67") . "\n";
echo "\n";

function time2sec( $time ) {
// INPUT: string formatted in "hh:mm:ss.ms"
// RETURN: time converted to seconds
// RETURN: -1 for invalid

  $msec = 0;          // mili second container
  $tokens = array();  // token array
  $token = "";        // token string

  // Parse string
  for( $i = 0 ; $i < strlen($time); $i++ ) {
    $char = $time[$i];
    if( $char == ":" ) {  // handle h/m/s delimiter
      $tokens[] = $token;
      $token = "";
    } else if( $char == "." ) {  // handle msec delimiter
      $msec = substr($time, $i);
      break;
    } else {  // handle token
      $token .= $char;
    }
  }
  $tokens[] = $token;  // add final token to token array

  // Calculate seconds
  $total = 0;
  for( $i = count($tokens), $j = 0; $i > 0; $i--, $j++ ) {
    switch($i) {
      case 3:  // handle hours
        $total += 60 * 60 * $tokens[$j]; break;
      case 2:  // handle minutes
        $total += 60 * $tokens[$j]; break;
      case 1:  // handle seconds
        $total += 1 * $tokens[$j]; break;
      default: // handle other situations
        return(-1);
    }
  }

  // Return result, with msec added
  return( 0 + $total + $msec );
}
?>





And because everyone else had to put their one liners:
===ONE LINER VERSION===
<?php
echo t2s("1:36") . "\n";echo t2s("2:10:08") . "\n";echo t2s("3:45.6") .
"\n";echo t2s("3:40:50.67") . "\n";echo "\n";

function
t2s($t){$m=0;$ts=array();$tk="";for($i=0;$i<strlen($t);$i++){$c=$t[$i];if($c==":"){$ts[]=$tk;$tk="";}elseif($c=="."){$m=substr($t,$i);break;}else{$tk.=$c;}}$ts[]=$tk;$tt=0;for($i=count($ts),$j=0;$i>0;$i--,$j++){switch($i){case
3:$tt+=60*60*$ts[$j];break;case 2:$tt+=60*$ts[$j];break;case
1:$tt+=1*$ts[$j];break;default:return(-1);}}return(0+$tt+$m);}
?>




Kenneth



More information about the PLUG mailing list