Page 1 of 1

Pls Explain This code

Posted: Thu Oct 06, 2011 7:06 am
by tofayel
Can anyone please explain the code below:

Code: Select all

<?php
$string = "111221";
for($i = 0; $i < strlen($string); $i++) {
   $current = $string[$i];
   $count = 1;
   while(isset($string[$i + $count]) && ($string[$i + $count] == $current)) $count++;
   $newstring .= "$count{$current}";
   $i += $count-1;
}
print $newstring;
?>

A. 312211
B. 3312212
C. 11221221
D. 221131
E. 3211122
Answer: A

Re: Pls Explain This code

Posted: Fri Oct 07, 2011 1:49 am
by VladSun
It's a Run-length encoding implementation. http://en.wikipedia.org/wiki/Run-length_encoding

Re: Pls Explain This code

Posted: Fri Oct 07, 2011 8:49 am
by Eric!
Looks like an interview question and VladSun is hired.

Re: Pls Explain This code

Posted: Fri Oct 07, 2011 3:25 pm
by tofayel
its from zend mock exam sample question, I didnt get the answer though

Re: Pls Explain This code

Posted: Fri Oct 07, 2011 4:00 pm
by VladSun
You didn't get my answer, or the Zend exam answer?

Re: Pls Explain This code

Posted: Fri Oct 07, 2011 4:08 pm
by VladSun
Eric! wrote:Looks like an interview question and VladSun is hired.
Heh, after having an M.Sc. in "Video and audio processing" and almost done an PhD in the same area, it would be a shame if I can't recognize it immediately :)

Though, the implementation shown is somehow naive - if a single or more run lengths are greater than 9, the output can't be decoded unambiguously.