Thursday, February 3, 2011

Generating Collatz sequence using regex

See: Collatz conjecture on Wikipedia

final int N = 11;
String s = new String(new char[N]);

while (s.length() > 1) {
    System.out.print(s.length() + ", ");
    s = s.replaceAll("(.+)\\1$|((.)+)", "$1$2$2$2$3");
}
System.out.println(s.length());

// prints 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1

2 comments:

  1. Nice one. As always, clever use of the tool.

    ReplyDelete
  2. You should join RegExp Rehab. Yes, you do, first stage is denial. :P

    ReplyDelete