Pls Explain This code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tofayel
Forum Newbie
Posts: 2
Joined: Thu Oct 06, 2011 7:01 am

Pls Explain This code

Post 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
Last edited by Weirdan on Fri Oct 07, 2011 9:17 pm, edited 2 times in total.
Reason: Added [syntax=php|sql|css|javascript] and/or [text] tags.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Pls Explain This code

Post by VladSun »

It's a Run-length encoding implementation. http://en.wikipedia.org/wiki/Run-length_encoding
There are 10 types of people in this world, those who understand binary and those who don't
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: Pls Explain This code

Post by Eric! »

Looks like an interview question and VladSun is hired.
tofayel
Forum Newbie
Posts: 2
Joined: Thu Oct 06, 2011 7:01 am

Re: Pls Explain This code

Post by tofayel »

its from zend mock exam sample question, I didnt get the answer though
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Pls Explain This code

Post by VladSun »

You didn't get my answer, or the Zend exam answer?
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Pls Explain This code

Post 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.
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply