Look and say sequence (Java)

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 Java program to generate look-and-say sequences such as the Conway sequence.

<<LookAndSaySequence.java>>=
import java.util.Arrays;
public class LookAndSaySequence
{
    public static String[] look_and_say(String seed, int len)
    {
        String[] seq = new String[len];
        seq[0] = seed;
        for (int i = 1; i < len; i++) {
            String val = seq[i-1];
            StringBuilder nextval = new StringBuilder();
            for (int ix = 0; ix < val.length(); ) {
                char ch = val.charAt(ix);
                int n;
                for (n = 1; ++ix < val.length() && val.charAt(ix)==ch; n++)
                    ;
                nextval.append(n).append(ch);
            }
            seq[i] = nextval.toString();
        }
        return seq;
    }
    public static void main(String[] args)
    {
        String[] seq = look_and_say("3", 10);
        System.out.println(Arrays.toString(seq));
    }
}
Download code
Views