Look and say sequence (PHP)

From LiteratePrograms

Jump to: navigation, search
Other implementations: C++ | dc | Eiffel | Haskell | J | Java | Lua | OCaml | Perl | PHP | Python | Ruby | Scala | sed | sh

This program is a code dump.
Code dumps are articles with little or no documentation or rearrangement of code. Please help to turn it into a literate program. Also make sure that the source of this code does consent to release it under the MIT or public domain license.

This is a simple PHP program to generate look-and-say sequences such as the Conway sequence.

<<look_and_say_sequence.php>>=
<?php
function look_and_say($generator, $length) {
  $last_value = "$generator";
  $sequence = array($last_value);
  foreach (range(1, $length) as $i) {
    $next_value = "";
    while ($last_value) {
      preg_match("/$last_value[0]+/", $last_value, $matches);
      $match_len = strlen($matches[0]);
      $next_value .= $match_len . $last_value[0];
      $last_value = substr($last_value, $match_len);
    }
    $last_value = $next_value;
    array_push($sequence, $next_value);
  }
  return $sequence;
}
$conway = look_and_say(3,10);
foreach ($conway as $x) {
  echo "$x\n";
}
?>
Download code
Views