A look and say sequence is a self-descriptive sequence of integers first investigated by the mathematician John Horton Conway.

They are defined very simply. Start with an integer, say 1. Then we look at the integer and say it consists of one 1, and write this as 11, the next element in the sequence. Then we look at 11 and say that it consists of two 1's, or 21. Then 21 would be described as one 2 and one 1, or 1211. And so on.

The golf challenge is to write a program to print out the first 10 elements of a look and say sequence from a specified integer in the fewest number of keystrokes. The first 10 elements for the look and say sequence generated from the integer 1 are:

@test = qw|1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211|;

Here is a strawman solution that surely could be improved upon:

$s=1;print"$s\n";for(2..10){@n=split//,$s;my@r;$c=$n[0];$l=0;while(@n){$n=shift@n;if($n==$c){$l++}else{push@r,[$l,$c];$c=$n;$l=1;}}push@r,[$l,$c];$s =join"",map{"$_->[0]$_->[1]"}@r;print"$s\n";}

Bonus question: Can you find an integer that is its own look and say description?

-Mark

20050412 Edit by ysth: code tags


In reply to Golf: Look and Say Sequences by kvale

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.