Monday, February 14, 2011

Pascal's triangle using regex

The pattern can probably be simplified, but this works.
String s;
System.out.println(s = "-;");
for (int n = 10; n --> 0 ;) {
   System.out.println(s = s.replaceAll("^(?=(-;))|;(?=(-*;))", "$1$2"));
}

Wednesday, February 9, 2011

Per-site user stylesheet rules for Firefox

I'll summarize this later:

userContent.css and @-moz-document
https://developer.mozilla.org/en/CSS/@-moz-document

Where's my profile directory?
about:support

You'll probably want to use !important.
http://www.w3.org/TR/CSS2/cascade.html#important-rules

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

Solving the postage stamp problem using regex

See: Postage stamp problem on Wikipedia
int n = 0;

while (
   (new String(new char[++n]))
      .matches("(.{1}|.{4}|.{9}|.{31}|.{51}){0,5}")
);

System.out.println(n); // 127
(see also on ideone.com)

That is, when the only available stamp denominations are {1, 4, 9, 31, 51}, and when envelopes can only accommodate up to 5 stamps, the smallest unrepresentable total stamp value is 127.

It's easy to confirm correctness, because (not so) coincidentally, this set of stamp denominations is the unique solution to the (5, 5) global PSP. See Al Zimmermann's Programming Contest - Son of Darts.