puzzlecode-golfrosetta-stoneautomata

Code Golf: Automata


I made the ultimate laugh generator using these rules. Can you implement it in your favorite language in a clever manner?

Rules:

On every iteration, the following transformations occur.

H   -> AH
A   -> HA
AA  -> HA
HH  -> AH
AAH -> HA
HAA -> AH

n = 0 |  H
n = 1 |  AH
n = 2 |  HAAH
n = 3 |  AHAH
n = 4 |  HAAHHAAH
n = 5 |  AHAHHA
n = 6 |  HAAHHAAHHA
n = 7 |  AHAHHAAHHA
n = 8 |  HAAHHAAHHAAHHA
n = 9 |  AHAHHAAHAHHA
n = ...

Solution

  • MATLAB (v7.8.0):

    73 characters (not including formatting characters used to make it look readable)

    This script ("haha.m") assumes you have already defined the variable n:

    s = 'H';
    for i = 1:n,
      s = regexprep(s,'(H)(H|AA)?|(A)(AH)?','${[137-$1 $1]}');
    end
    

    ...and here's the one-line version:

    s='H';for i=1:n,s = regexprep(s,'(H)(H|AA)?|(A)(AH)?','${[137-$1 $1]}');end
    

    Test:

    >> for n=0:10, haha; disp([num2str(n) ': ' s]); end
    0: H
    1: AH
    2: HAAH
    3: AHAH
    4: HAAHHAAH
    5: AHAHHA
    6: HAAHHAAHHA
    7: AHAHHAAHHA
    8: HAAHHAAHHAAHHA
    9: AHAHHAAHAHHA
    10: HAAHHAAHHAHAAHHA