Mathematica 159 140 134
Edit: A complete rewrite, using recursion (NestWhile
).
Much faster and no wasted effort.
Code
g@n_:=StringTake[NestWhile[#~StringReplace~{"A"-> "ABCBACBCABCBA","B"-> "BCACBACABCACB",
"C"->"CABACBABCABAC"}&,"ABC",StringLength[#]<n&],n]
Usage
It takes approximately 1/40 sec to generate a ternary square free word with one million characters.
g[10]
g[53]
g[506]
AbsoluteTiming[g[10^6];]
Verifying
f
will test whether a string is square free.
f[s_]:=StringFreeQ[s, x__~~x__]
Checking the above outputs and one case in which the string "CC" appears.
f@Out[336]
f@Out[337]
f@Out[338]
f["ABCBACBCABCBABCACBACCABCACBCABACBABCABACBCACBACABCACBA"]
True
True
True
False
1
exec"x+=[1-y for y in x];"*n
saves 6 chars at the expense of efficiency - but hey this is golf! – gnibbler – 2013-02-01T06:28:20.237