tags:

views:

150

answers:

2

There is a pattern that goes like this:

1
11
21
1211
111221
...

I'm trying to write PHP code to output this, but my output is:

1
11
21
12
11
21
12
...

Here's the code:

<?
$sequence = "1";

for ($i = 0; $i < 99; $i++) {

    echo "{$sequence}<br />";

    $n = 0;
    $x = 0;
    $z = 1;

    $newsequence = "";

    for ($y = count($sequence); $y > 0; $y--) {
        while ($sequence[$n] == $sequence[$n + 1]) {
            $z++;
            $n++;
        }

        $newsequence .= "{$z}{$sequence[$n]}";
    } 

    $sequence = $newsequence;
}

?>

What am I missing?

+3  A: 

$sequence is a string, and count() of a string will always return 1. Perhaps you're looking for strlen()?

nickf
Oops. My bad...
Scott
+2  A: 

In addition to nickf's spot, $n is your index into your sequence, but you only update it if you find two adjacent terms that are the same.

For example, if your sequence was "21", you'd skip your while loop, leaving n and z unchanged, which means you'd append "12" to your new sequence, but then get into an infinite loop because your while would still be interrogating the "2".

Once you've appended a new bit to your sequence, you need to increment your counter n by 1, and reset your "repeat counter" z. The increment of n takes you past the last character you looked at that did not have the same character following it. I put together the following (not in PHP unfortunately):

while(n < sequence.length) {
  while(n < sequence.length-1 && sequence(n) == sequence(n+1)) {
    z+=1
    n+=1
  }
  next += "%d%s".format(z,sequence(n))
  n+=1
  z=1
}

and I get this:

11
21
1211
111221
312211
13112221
1113213211
31131211131221
13211311123113112211
11131221133112132113212221

which I think is what you're after.

butterchicken
I can't figure out where else I would update $n
Scott