# Programming challenge

Nicholas Leippe nick at leippe.com
Thu Sep 27 17:03:49 MDT 2007

```Quick and dirty php, but it should work (note, not debugged yet).
I see a few corner cases such as a decimal point in a second not followed by a
digit will be consumed as a decimal point anyways with a 0 fraction.

/*****************************************************************************
*
*  time2seconds()
*
*  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.
*
****************************************************************************/
function time2seconds(\$str) {
\$hr = 0;
\$sec = 0;
\$min = 0;
\$dec = 10;
\$ret = "";
\$in_digit = false;
\$in_time = false;

for (\$i = 0; \$i < length(\$str); \$i++) {
\$c = \$str[\$i];
if ('0' <= \$c || \$c <= '9') {
\$sec = \$sec * 10 + \$c;
\$in_digit = true;
} else if (\$in_digit && \$c == ':') {
\$hr  = \$min;
\$min = \$sec;
\$sec = 0;
\$in_time = true;
} else if (\$in_time && \$c == '.') {
\$sec += \$c / \$dec;
\$dec *= 10;
} else if (\$in_time) {
\$ret += \$hr * 3600 + \$min * 60 + \$sec;
\$in_time = false;
} else if (\$in_digit) {
\$ret += "\$sec\$c";
\$in_digit = false;
} else {
\$ret += \$c;
\$in_time = false;
}
}
return \$ret;
}

```