title: Golfing A Weasel Program

text:
# Question
Title: Golfing A Weasel Program
Richard Dawkins in his book The Blind Watchmaker, describes a Weasel program. The algorithm can be described as follows:

> 1. Start with a random string of 28 characters. Valid characters are all upppercase letters, and space.
> 2. Make 100 copies of that string, with a 5% chance per character of that character being replaced with a random character.
> 3. Compare each new string with the target "METHINKS IT IS LIKE A WEASEL", and give each a score according to the number of letters in the string which are correct and in the correct position.
> 4. If any of the new strings has a perfect score (28), halt.
> 5. Choose the highest-scoring string from step 3. How you work out a tie is up to you, but only one string may be chosen. Take the chosen string and go to step 2.

The winner will be the shortest code snippet to get to the correct answer while printing the highest-scoring string of each generation in the following format:

If people could help by checking other peoples answers would be very helpful!

# Answer
## APL (143)

```
0{⍵≢T←'METHINKS IT IS LIKE A WEASEL':c∇⍨1+⍺⊣⎕←(⍕⍺),':'c'-- score:',s⊣c←⊃c/⍨G=s←⌈/G←{+/⍵=T}¨c←{⍵{⍵:⍺⋄C[?27]}¨9≠?28/20}¨100⍴⊂⍵}⊃∘(C←27↑⎕A)¨?28/27

```

Explanation:

* `0{`...`}⊃∘(C←27↑⎕A)¨?28/27`: set `C` to the first 27 capital letters. There are only 26, so the 27th element will be a space. Select 28 random items from `C`. This will be the first . The first  (generation) will be `0`.
* `⍵≢T←'METHINKS IT IS LIKE A WEASEL`: set `T` to the string `'METHINKS IT IS LIKE A WEASEL'`. As long as  is not equal to `T`:

+ `{`...`}¨100⍴⊂⍵`: Make 100 copies of . For each of these...
        - `9≠?28/20`: select 28 random numbers from 1 to 20. Make a bitmask where each `1` means that the random number was not equal to `9`. (This means 5% chance of a `0`).
        - `⍵{⍵:⍺⋄C[?27]}¨`: for each letter in , if the corresponding bit was `1`, keep that letter, otherwise replace it with a randomly chosen element from `C`.
    + `c←`: store the 100 mutated strings in `c`.
    + `G←{+/⍵=T}¨c`: for each element in `c`, calculate the score (amount of characters that match `T`) and store the scores in `G`.
    + `s←⌈/G`: find the maximum score and store that in `s`.
    + `c←⊃c/⍨G=s`: select the first item from `c` whose score is equal to `s` (the maximum), and store it in `c` again.
    + `⎕←(⍕⍺),':'c'-- score:',s`: print the generation in the given format ( is current generation, `c` is current best string, `s` is score)
    + `c∇⍨1+⍺`: Increment the generation and run the mutation again using the current best string (`c`) as input.
> 27 votes

# Answer
# Mathematica - ~~238~~ ~~236~~ 225

```
c:="@"~CharacterRange~"Z"~RandomChoice~28/."@"->" "
For[s=""<>c;i=0,{d,s}=Sort[{#~HammingDistance~"METHINKS IT IS LIKE A WEASEL",#}&@
StringReplace[s,_/;20Random[]<1:>c〚1〛]&~Array~100]〚1〛;
d>0Print[i++,":"s," -- score: ",28-d],]

```

Example output

```
0:  CYPMEIHADXRXVTFHERYOZNRVFCSQ  -- score: 0
1:  CYPMEIHADIRXVTFBERYOZNRVFCSQ  -- score: 1
2:  CYPMEIHA IRXVTFBIRYOZNRVFCSQ  -- score: 3
...
50:  METHINKS IT IS LIKE A WEASEL  -- score: 28

```
> 11 votes

# Answer
# Python (273)

```
from random import choice as c
n=range
a=map(chr,n(65,91)+[32])
s=map(c,[a]*28)
p=x=0
while p<28:
 p,s=max((sum(g==r for g,r in zip(y,'METHINKS IT IS LIKE A WEASEL')),y)for y in ([c(a+[x]*513)for x in s]for _ in n(100)));print '%d: %s -- score: %d' % (x,''.join(s),p);x+=1

```
> 9 votes

# Answer
# Python: 282 characters no semi colons

```
from random import*
g,r,l,c=0,0,"ABCDEFGHIJKLMNOPQRSTUVWXYZ ",choice
k=map(c,[l]*28)
while(r!=28):
 r,k=max((sum(i==j for i,j in zip(t,"METHINKS IT IS LIKE A WEASEL")),t)for t in[[c(l)if random()<.05 else i for i in k]for i in[1]*100])
 print`g`+":","".join(k),"-- score:",`r`
 g+=1

```

# 278 with:

```
from random import*;g,r,l,c=0,0,"ABCDEFGHIJKLMNOPQRSTUVWXYZ ",choice;k=map(c,[l]*28)
while(r!=28):r,k=max((sum(i==j for i,j in zip(t,"METHINKS IT IS LIKE A WEASEL")),t)for t in[[c(l)if random()<.05 else i for i in k]for i in[1]*100]);print`g`+":","".join(k),"-- score:",`r`;g+=1

```
> 6 votes

# Answer
## R (~~245~~ ~~239~~ 238 characters)

```
t=strsplit("METHINKS IT IS LIKE A WEASEL","")[[1]]
h=sample
s=h(f<-c(LETTERS," "),28,T)
c=0
while(!all(s==t)){for(i in 1:100){z=ifelse(runif(28)<.05,h(f,1),s)
y=sum(s==t)
if(sum(z==t)>y)s=z}
cat(c<-c+1,": ",s," -- score: ",y,"\n",sep="")}

```

Gives:

```
1: HSSSIMJM ETJISGBSCIELUYPLSED -- score: 7
2: HSSSIMJM ETJISGBSKIELUYPLSED -- score: 8
3: EETLITLM ETJISTBSKIELUYLLSEL -- score: 11

```

...

```
78: METHINKS IT IS LIKEEA WEASEL -- score: 27
79: METHINKS IT IS LIKEEA WEASEL -- score: 27
80: METHINKS IT IS LIKEEA WEASEL -- score: 27
81: METHINKS IT IS LIKE A WEASEL -- score: 28

```
> 6 votes

# Answer
# K,  173 167

```
o:"METHINKS IT IS LIKE A WEASEL"
i:0;{~x~o}{-1($i),": ",(r:a@*&b=c)," -- score: ",$c:max@b:+/'o=/:a:{x{if[0~*1?20;x[y]:*1?s];x}/!#x}'100#,x;i+:1;r}/28?s:"c"$32,65+!26;

```

/

```
0: FQRZPHACDIBHZOUUCYKKFBJWVNVI -- score: 1
1: FQRZP ACDITHCOUUCYKKFBJWVNVI -- score: 2
2: FQRZP AFDIT COUUCYKKFBJWVNVI -- score: 3
...
51: METHINKS IT IS LIKECA WEASEL -- score: 27
52: METHINKS IT IS LIKECA WEASEL -- score: 27
53: METHINKS IT IS LIKE A WEASEL -- score: 28

```
> 6 votes

# Answer
# JavaScript, ~~277~~ 246

```
c=m=>" ABCDEFGHIJKLMNOPQRSTUVWXYZ"[0|Math.random()*m];for(s=[k=28];e=k;s[--k]=c(27));for(;alert(k+++": "+s.join("")+" -- score: "+e),e<28;s=t)for(z=100;f=0,z--;f>e&&(t=n,e=f))n=s.map((h,p)=>(h=c(540)||h,f+=h=="METHINKS IT IS LIKE A WEASEL"[p],h))

```

(requires arrow function support; indentation added only for readability)

```
// c() returns a random char using `m` as an index max
c=m=>" ABCDEFGHIJKLMNOPQRSTUVWXYZ"[0|Math.random()*m];

// generate base string `s`
for(s=[k=28];e=k;s[--k]=c(27));

// while score `e` is < 28
for(;alert(k+++": "+s.join("")+" -- score: "+e),e<28;s=t)
    for(z=100;f=0,z--;f>e&&(t=n,e=f))            // do 100 mutations; keep best score
        n=s.map((h,p)=>(                         // map `s` to `n` with 5% mutation
            h=c(540)||h,                         // change the char in 5% of cases
            f+=h=="METHINKS IT IS LIKE A WEASEL"[p],  // score++ if char matches
            h                                    // arrow function return character
        ))

```

Feel free to change `alert` to `console.log` if you want a more pleasant execution experience.

There are some nifty golfy bits in here:

* The function `c` returns a random character from the alphabet string `" ABC..."`. The function takes an argument to use as an upper bound for the random index selection. When generating the base string, we use `27`, so the function behaves normally.

However, we abuse this behavior by asking for a random upper bound of 540 in `h = c(540) || h`. Only 5% of the time will `c` actually return a string (because 540 * .05 = 27); the other 95% of the time, the randomly-chosen index falls beyond the length of the string, so the function returns `undefined`. This falsey value causes a logical-OR cascade in `c(540) || h`, so the original `map` value `h` is used (i.e., no replacement occurs).
* The score-summing operation does `f+=h=="METHINKS IT IS LIKE A WEASEL"[p]`, which says "add `true` to `f` if the current `map` character `h` matches the `p`th character of the WEASEL string". The number-plus-boolean addition coerces the boolean result to either `0` or `1`, which means that `f` is incremented only when there is a match against the target WEASEL string.
> 5 votes

# Answer
# C 256

```
char c[101][29],s,n,z,b,j,i,w;g;main(){for(;w<28;printf("%d: %s -- score: %d\n",g++,c[b=n],w))for(i=w=0;i<101;i++)for(s=j=0;j<28&&!(i==b&&g);j++)(s+=(c[i][j]=g&&rand()%20?c[b][j]:(z=rand()%27)?'A'+z-1:' ')=="METHINKS IT IS LIKE A WEASEL"[j])>w?n=i,w=s:0;}

```

Simple three loops, initialization, generation of new strings from parent and score calculated by the same statement. It's not very readable even with indentation.

# C 252

```
i,g,n,b,o,s,w,z;char c[2929];main(){for(;(o=i%29)|i|w<28;(i=(i+1)%2929)||printf("%d: %s -- score: %d\n",g++,&c[b=n],w))(s+=o>27?-s:((i-o!=b||!g)&&(c[i]=g&&rand()%20?c[b+o]:(z=rand()%27)?'A'+z-1:' ')=="METHINKS IT IS LIKE A WEASEL"[o]))>w?n=i-o,w=s:0;}

```

One loop, with one array holding all 101 strings.

This second version breaks the rules because it prints the string from (the equivalent of) step 1, but it was either that or not print the last string. I'm stumped how to fix it without exploding in size. I'm posting it anyway for inspiration.

# C 256

```
struct{char d[29];}p,t,n;i,j=-1,z,s,w,g;main(){for(;w<28;j>1&&printf("%d: %s -- score: %d\n",g++,(p=n).d,w))for(;j++%100;p=j?p:t)for(s=0,i=28;i--;)(s+=(t.d[i]=j&&rand()%20?p.d[i]:(z=rand()%27)?'A'+z-1:' ')=="METHINKS IT IS LIKE A WEASEL"[i])>w?n=t,w=s:0;}

```

Different approach, instead of making an array to hold 101 strings just regenerate the string 100 times and use struct assignment for easy copying. Initialization is done by starting the "repeat 100 times" counter at -1 and handling it carefully by strategically chosen post-increment. Despite a very different approach it ends up exactly the same as the first attempt - 256 characters.
> 5 votes

# Answer
## C# - 436

```
namespace System.Linq{class W{static void Main(){var r=new Random();
Func<char>c=()=>(char)(r.Next(33,60)%59+32);var s="";
while(s.Length<28)s+=c();var a="METHINKS IT IS LIKE A WEASEL";int b=0;
while (s!=a){int m=-1;var f=s;for(int i=0;i<100;i++){
var l=string.Join("",s.Select(j=>(r.Next(20)!=0?j:c()).ToString()));
int o=Enumerable.Range(0,28).Sum(j=>l[j]==a[j]?1:0);if(o>m){f=l;m=o;}}
Console.WriteLine(b+++": "+(s=f)+" -- score: "+m);}}}}

```
> 4 votes

# Answer
## Scala, ~~347~~ ~~341~~ 337 chars:

```
import util.Random.{nextInt=>r}
val t="METHINKS IT IS LIKE A WEASEL"
def c="ABCDEFGHIJKLMNOPQRSTUVWXYZ "(r(27))
def s(a:String)=t.zip(a).map{x=>if(x._1==x._2) 1 else 0}.sum
def w(a:String,i:Int=0){println(f"$i%2d: $a -- score: ${s(a)}")
if(s(a)!=28){w((0 to 99).map{_=>a.map(o=>if(r(20)<1) c else o)}.sortBy(s).last,i+1)}}
w(t.map(_=>c))

```

=\>

```
 0: PGSHWAEPALQFTCORUKANPNUTRVXH -- score: 2
 1: PGSHWAEPALQ TCOQUKANPNUTRVXH -- score: 3
...
47: METHINKS WT IS LIKE A WEASEL -- score: 27
48: METHINKS IT IS LIKE A WEASEL -- score: 28

```
> 3 votes

# Answer
**Lua 5.1 (502)**

The minimised version:

```
s,t,b,c,i,q,a,d,f="ABCDFGHJYUEGKSHNCOLPQIEJUSNC","METHINKS IT IS LIKE A WEASEL",1,math.random,table.insert,1,string.sub,100,28 while q~=f do r,p={},{} for x=1,d do i(r,s) i(p,0) e="" for o=1,f do if c(1,20)==1 then if c(1,27)==1 then e=e.." " else e=e..string.char(c(65,90)) end else e=e..a(r[x],o,o) end end r[x]=e for y=1,f do if a(r[x],y,y)==a(t,y,y) then p[x]=p[x]+1 end end if p[x]==f then s=r[x] end end for x=1,d do if p[x]>=q then s,q=r[x],p[x] end end print(b..":",s,"-- score: "..q) b=b+1 end

```

and the easier to read version (with comments!):

```
s,t,b,c,i,q,a,d,f="ABCDFGHJYUEGKSHNCOLPQIEJUSNC","METHINKS IT IS LIKE A WEASEL",1,math.random,table.insert,1,string.sub,100,28
--s=random string, t=target, b=counter, c=reference to math.random, i=reference to table.insert, q=top score,a=reference to string.sub, d=constant (100), f=constant (28)
while q~=f do
    r,p={},{}
    for x=1,d do  --add 100 copies to the table of strings
        i(r,s)
        i(p,0)
        e=""
        for o=1,f do  --for each character in string
            if c(1,20)==1 then  -- 5% chance
                if c(1,27)==1 then e=e.." " else e=e..string.char(c(65,90)) end  --set it to an ASCII char between 65 and 90 (A-Z) or a space character
            else
                e=e..a(r[x],o,o)
            end
        end
        r[x]=e  --current string = mutations
        for y=1,f do
            if a(r[x],y,y)==a(t,y,y) then p[x]=p[x]+1 end
        end  --for each char increment score if it is correct
        if p[x]==f then
            s=r[x]
        end  --if 28 then final string is this!
    end
    for x=1,d do
        if p[x]>=q then s,q=r[x],p[x] end  --if this is the highest score so far, then make the string equal to this
    end
    print(b..":",s,"-- score: "..q)  --print it!
    b=b+1  --add one to the counter!
end

```

To be honest even though this definitely won't win, I was just glad to find and minimise a *reasonably* short solution for this problem! (emphasis on reasonably) :p
> 3 votes

# Answer
## SAS - 374

```
%macro r;ranuni(7)%mend;%macro s;r=int(%r*27);substr(x,t,1)=byte(ifn(r,64+r,32));%mend;%macro y;char(y,t)=char(x,t)%mend;options nonotes nosource;data x;length x$28;do t=1to 28;%s;end;y="METHINKS IT IS LIKE A WEASEL";do z=1by 1;o=x;do i=1to 100;c=0;x=o;do t=1to 28;if %r<=.05then do;%s;end;c+%y;end;if c>m then do;m=c;v=x;end;end;x=v;put z":" x"-- score:" m;if m<28;end;run;

```

-\>

```
1 :GUUVLNUSILSRZLRBXVVCWXX HXKC -- score:2
2 :MUUVLNUSILSRZLRBXVMCWXX HXKC -- score:3
3 :MUUVLNESILSRILRBXVMCWXX HXKC -- score:4
4 :MEUVLNESILSRIRRBXVMCWXX HXKC -- score:5
....
95 :METHINKS IT IS LIKE A XEASEL -- score:27
96 :METHINKS IT IS LIKE A XEASEL -- score:27
97 :METHINKS IT IS LIKE A XEASEL -- score:27
98 :METHINKS IT IS LIKE A WEASEL -- score:28

```

With linebreaks/indent/comments:

```
%macro r;
 ranuni(7)   /* seed 0 will make new each time (seed=clock), otherwise fixed results */
%mend;
%macro s;  /* does the rand char, used both to initialize and replace; */
 r=int(%r*27);
 substr(x,t,1)=byte(ifn(r,64+r,32)); *r=0 becomes space otherwise upper char;
%mend;
%macro y;  /*compares using new to 9.2 CHAR function which is equivalent to substr(str,start,1) */
 char(y,t)=char(x,t)
%mend;
options nonotes nosource; /*cheapest way to get clean log */
data x;
 length x$28; /*annoyingly necessary*/
 do t=1to 28;%s;end; /*initialize string*/
 y="METHINKS IT IS LIKE A WEASEL"; /*compare string */
 do z=1by 1; /*start iterating */
  o=x; /*save this iteration's string */
  do i=1to 100;
   c=0; /*score for this iteration*/
   x=o; /*string to fudge about start out clean, reusing x so no params to macro*/
   do t=1to 28;
    if %r<=.05then do;%s;end; /*if 5% then change the char out */
    c+%y; /*score that character*/
   end;
   if c>m then do; /*if on better scoring line, save it */
    m=c;
    v=x;
   end;
  end;
  x=v; *for next iter - this is cheaper than other options involving o=v due to first iter;
  put z":" x"-- score:" m;
  if m<28; *quit at 28;
 end;
run;

```
> 3 votes

# Answer
## C ~~361~~ 331

Not as good as Art's solution, but here's my (newbie) attempt at a C solution. 361 characters if you remove newlines and tabs.

```
char*w="METHINKS IT IS LIKE A WEASEL";char b[101][29];t,s,n,i,j,x,a;main(){for(;i<28;i++)b[0][i]=w[rand()%28];while(s<28){for(j=1;j<101;j++){x=0;for(i=0;i<28;i++){if(!(rand()%20))b[j][i]=w[rand()%28];else b[j][i]=b[0][i];if(b[j][i]==w[i])x++;}if(x>s){s=x;t=j;}}printf("%d: %s -- score %d\n",n++,b[t],s);for(;i>=0;--i){a=b[0][i];b[0][i]=b[t][i];b[t][i]=a;}t=0;}}

```

Edit: Got rid of the nested loop and used a 1D array. Was hoping it would make a bigger difference, but it only saved me 30 characters. Here's the code:

```
char*w="METHINKS IT IS LIKE A WEASEL";char b[2929];t,s,n,i,x;main(){for(;i<28;i++)b[i]=w[rand()%28];while(s<28){for(;i<2929;i++){if((i+1)%29){if(!(i%29))x=0;b[i]=rand()%20?b[i%29]:w[rand()%28]; x+=b[i]==w[i%29];if(x>s){s=x;t=i/29;}}}for(i=0;i<29;i++){x=b[i+t*29];b[i+t*29]=b[i];b[i]=x;}printf("%d: %s -- score %d\n",n++,b,s);t=0;}}

```

Edit: This is the original, ungolfed code, for those who are interested in knowing how the "golfing" was done. The code produces no warnings when compiled with GCC with -Wall and C99 enabled. Maybe you're a golfing newbie like me, or a C newbie like me, or maybe you're just curious. :) https://gist.github.com/cpx/97edbce4db3cb30c306a
> 3 votes

# Answer
## PHP 442

```
<? function r(){$n=rand(65,91);if($n==91) return ' ';else return chr($n);}function s($s){$c=0;$t='METHINKS IT IS LIKE A WEASEL';for($i=0;$i<28;$i++) if($s[$i]==$t[$i]) $c++;return $c;}function m($s){for($i=0;$i<28;$i++) if(rand(0,99)<5) $s[$i]=r();return $s;}$s='';for($i=0;$i<28;$i++) $s.=r();for($i=0;;$i++){$l=s($s);printf("%2d: %s -- score: %d\n",$i,$s,$l);if($l==28) break;$x=$s;for($j=0;$j<100;$j++){$t=m($s);if(s($t)>$l) $x=$t;}$s=$x;}

```

Readbly:

```
<?
//random char
function r(){
    $n=rand(65,91);
    if($n==91) return ' ';
    else return chr($n);
}
//score
function s($s){
    $c=0;
    $t='METHINKS IT IS LIKE A WEASEL';
    for($i=0;$i<28;$i++)
        if($s[$i]==$t[$i]) $c++;
    return $c;
}
//mutate
function m($s){
    for($i=0;$i<28;$i++)
    if(rand(0,99)<5) $s[$i]=r();
    return $s;
}
$s='';
for($i=0;$i<28;$i++) $s.=r();
for($i=0;;$i++){
    $l=s($s);
    printf("%2d: %s -- score: %d\n",$i,$s,$l);
    if($l==28) break;
    $x=$s;
    for($j=0;$j<100;$j++){
        $t=m($s);
        if(s($t)>$l) $x=$t;
    }
    $s=$x;
}

```
> 2 votes

# Answer
# Python (~~330~~ 321)

```
def b(i,s):print i,':',''.join(s),'-- score:',p(s)
from random import*;a=" ABCDEFGHIJKLMNOPQRSTUVWXYZ";i,s,t=0,choice(a)*28,"METHINKS IT IS LIKE A WEASEL";p=lambda n:sum(n[c]==t[c]for c in range(28))
while p(s)<28:b(i,s);s=sorted([[(c,choice(a))[random()<.05]for c in s]for k in[1]*100],key=lambda n:p(n))[-1];i+=1
b(i,s)

```

Readable version:

```
def b(i,s):
    print i,':',''.join(s),'-- score:',p(s)

import random as r
a=" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
i,s,t=0,r.choice(a)*28,"METHINKS IT IS LIKE A WEASEL"
p=lambda n:sum(1for c in range(28)if n[c]==t[c])
while p(s)<28:
    b(i,s)
    s=sorted([[(c,r.choice(a))[r.random()<.05]for c in s]for k in[1]*100],key=lambda n:p(n))[-1];i+=1
b(i,s)

```

Example output:

```
0 : SSSSSSSSSSSSSSSSSSSSSSSSSSSS -- score: 3
1 : SSSQSSSSSSSSSSSSISSSSSSSSSSS -- score: 4
2 : SSSQISSSSSSSSSSSISSSSSSSSSSS -- score: 5
3 : SSSQISSSSSSSSSSSIKSSSSSSSSSS -- score: 6
4 : SMSQISSSSSSSISSSIKSSSSGSSSSS -- score: 7
...
53 : METHINKS IT IS UIKE A WEASEL -- score: 27
54 : METHINKS IT IS UIKE A WEASEL -- score: 27
55 : METHINKS IT IS LIKE A WEASEL -- score: 28

```

edit: removed a few characters based on AMKs and Timtechs answer
> 2 votes

# Answer
## Perl 5, 219 bytes

```
$_="METHINKS IT IS LIKE A WEASEL";sub r{(A..Z,$")[rand 27]};sub t{~~grep/$t[$-++%28]/,pop=~/./g}$}.=r for@t=/./g;printf"%3d: %s -- score: %d
",$i++,(($})=sort{t($b)<=>t$a}map s/./rand>.05?$&:r/ger,($})x100),t$}until/$}/

```

Try it online!
> 2 votes

# Answer
## Ruby - ~~225~~ ~~202~~ ~~203~~ 198 chars

Ruby seems under-represented in this challenge so far so I thought I would give it a try! Improvements welcome.

```
g=-1
s=[]
puts"#{g+=1}: #{$.,s=(0..99).map{n=(r=0..27).map{|i|x=[' ',*?A..?Z].sample;rand<0.05?x:s[i]||=x};[r.count{|i|n[i]=='METHINKS IT IS LIKE A WEASEL'[i]},n*'']}.max;s} -- score: #$."until$.>27

```
> 2 votes

# Answer
# Java (632)

```
class C {public static void main(String[] a){String b="AAAAAAAAAAAAAAAAAAAAAAAAAAAA";for(int i=1;;i++){String c=w(b);int s=s(c);if(s==28)break;if(s(b)<s){b=c;System.out.println(i+": "+c+" -- score: "+s);}}}public static String w(String b) {StringBuffer c = new StringBuffer(b);int max = 0;for (int i=0;i<100;i++){for(int j=0;j<28;j++)if(Math.random()<.06){double d=Math.random();c.setCharAt(j,(char)(d==1?32:d*26+65));}String d=c.toString();int s=s(d);if(s>max){max=s;b=d;}}return b;}public static int s(String s){String b="METHINKS IT IS LIKE A WEASEL";int sum=0;for(int j=0;j<28;j++)sum+=s.charAt(j)==b.charAt(j)?1:0;return sum;}}

```

Java is such a verbose language.. :(
> 2 votes

# Answer
**PHP (381 397 323 319 312):**

```
<? function s(&$s,&$i=0){$t='METHINKS IT IS LIKE A WEASEL';$i=0;$c=$s;$f=28;while($f--){$n=rand(0,26);$i+=($s[$f]=($c=='_'||!rand(0,19)?chr($n?$n+64:32):$s[$f]))==$t[$f];}}$s='_';s($s);$x=$y=0;do{$f=100;while($f--){$m=$s;s($m,$i);if($i>$y){$y=$i;$l=$m;}}printf("%2d: %s -- score: $y\n",$x++,$s=$l);}while($y<28);

```

Readable version:

```
<?
function s(&$s, &$i = 0) {
    $t = 'METHINKS IT IS LIKE A WEASEL';
    $i = 0;
    $c = $s;
    $f = 28; while ($f--) {
        $n = rand(0, 26);
        $i += ($s[$f] = ($c == '_' || !rand(0, 19) ? chr($n ? $n + 64 : 32) : $s[$f])) == $t[$f];
    }
}

$s = '_';
s($s);
$x = $y = 0;

do {
    $f = 100; while ($f--) {
        $m = $s;
        s($m, $i);

        if ($i > $y) {
            $y = $i;
            $l = $m;
        }
    }

    printf("%2d: %s -- score: $y\n", $x++, $s = $l);
} while ($y < 28);

```

Optimization credits (319):

Optimization credits (312):

* @Einacio's comments
> 2 votes

# Answer
## Ruby, 218

```
g,s,p,t=-1,'',1;while t!=28;t,b=-1;100.times{|i|m,n='',0
28.times{|j|n+=1if(m[j]=(rand<p ?[*?A..?Z,' '].sample: s[j]))=="METHINKS IT IS LIKE A WEASEL"[j]}
b,t=m,n if n>t};puts"#{g+=1}: #{s=b} -- score: #{t}";p=0.05;end

```

example run

```
0: LRAZZMKL IKUOGEHLKPWEVNEAZWX -- score: 6
1: LRAZZMKL IKUIGEALKMWEVNEAZWX -- score: 7
2: HRAGZMKL IKUIGEALKMWEVNEAZWX -- score: 7
3: HVAGZMKL IKUISAALKYWEVNEAZWX -- score: 8
                  ...
48: METHIUKS IT IS LIKEIA WEASEL -- score: 26
49: METHINKS IT IS LIKEIA WEASEL -- score: 27
50: METHINKS IT IS LIKEIA WEASEL -- score: 27
51: METHINKS IT IS LIKE A WEASEL -- score: 28

```
> 2 votes

# Answer
# Ruby, ~~206~~ ~~200~~ 199

```
q,i,*R=*-2..27
puts"#{i+=1}: #{$.,s=(-2..q).map{x=R.map{|j|!s||rand<0.05?[*?A..?Z,' '].sample: s[j]};[R.count{|i|x[i]=='METHINKS IT IS LIKE A WEASEL'[i]},x]}.max;q=97;s.join} -- score: #$."until$.>27

```

The first line is simply a fancy way to define `q=-2`, `i=-1`, and `R=(0..27).to_a`. All the work is done in the 2nd line:

```
puts"..."until$.>27 # Prints the string in quotes until we reach the desired score
     ^
     |
 +---+
 |
"#{i+=1}: #{...} -- score: #$."
   ^        ^               ^
   +--------|---------------|-- Generation counter
 +----------+---------------|-- Current string
 |                          +-- Score of current string (interpolates the `$.` variable)
 |
 #{$.,s=(-2..q).map{...}.max;q=97;s.join} # Generate the score & string
   ^         ^  ^   ^    ^   ^    ^
   +---------|--|---|----|---|----|------ Store the score; this variable makes
             |  |   |    |   |    |       string interpolation shorter.
             +--|---|----|---+----|------ `q` automatically takes care of generating
                |   |    |        |        the string vs randomizing the string.
                +---|----|--------|------  Make 100 (or 1 the first time) strings,
                    |    |        |        and compute their score.
                    |    +--------|------- Take the string with the max score.
 +------------------+             +------- `s` is stored as an array
 |
 x=R.map{...};[R.count{...},x] # Compute string and its score, store in array
   ^     ^    ^^       ^
   +-----|----|+-------|------ `R` is 0..27, we use the constant to save chars.
         |    +--------|------ `max` orders by first element, then second. We clearly want
         |             |       the highest score, so make the score first.
 +-------+-------------|------ Generate the string, store in `x`.
 |                     +------ Count the number of chars that overlap with 'METHINKS...'
 |                     |
 |                    {|i|x[i]=='METHINKS IT IS LIKE A WEASEL'[i]}
{|j|!s||rand<0.05?[*?A..?Z,' '].sample: s[j]}
    ^   ^         ^             ^       ^
    +---+---------|-------------|-------|---- 5% chance of randomizing, or 100% for
                  |             |       |     first string.
                  +-------------+-------|---- Sample from alphabet + ' '.
                                        +---- Don't alter the string 95% of the time

```
> 2 votes

# Answer
# Japt v2.0a0, ~~112~~ 108 bytes

```
ª(T=Si26õdI q¹ö28
_¬í¥`Ú0ˆks Š ‰ ¦ke a Øâel`u q)x
(OpW+`: {U} -- sÖ: `+(K=[U]xV¹WÄ
K<28©ßLÆ®p513 iT ö}ÃñV o

```

Try it online!

-4 bytes thanks to @ETHproductions.

### Unpacked & How it works

```
U||(T=Si26õdI q) ö28  Initialize primary input
U||                   If U is not initialized...
        26õdI           Generate uppercase alphabets
              q         Convert to string
      Si                Add space
   (T=         )        Assign to variable T
                 ö28    Sample 28 random chars from T and form a string
                        Implicitly assign to U

_q í==`Ú0ˆks Š ‰ ¦ke a Øâel`u q)x  Match counting function
_                                  Declare a function...
 q í==                         )     Convert to array of chars and pair with the next,
                                     and map with equality...
      `Ú0ˆks Š ‰ ¦ke a Øâel`u q        "methinks it is like a weasel" to uppercase
                                        split into chars
                                x    Sum (true == 1, false == 0)
                                   Implicitly assign to V

(OpW+`: {U} -- sÖ: `+(K=[U]xV) W+1  Output and increment counter
(Op                           )      Output with newline...
   W+`: {U} -- sÖ: `+                 `{W}: {U} -- score: `
                         [U]xV         Call V on [U] and force cast to number
                      (K=     )        Assign to K
                                W+1  Add 1 to W and implicitly assign to W

K<28&&ßLo@Um_p513 iT ö}} ñV o  Termination check and recursion
K<28&&                         If the match count is less than 28...
      ß                          Recurse the program with...
          Um_                      Map over chars of U...
             p513 iT                 The char repeated 513 times plus T
                     ö}              Sample a char from it
       Lo@             }           Generate array of 100 of the above
                         ñV o      Sort by V, pop the largest, pass it as U

```
> 2 votes

# Answer
# Japt `-R`, 94 bytes

A different approach to but with a little inspiration from Bubbler's solution.

```
;C±S ö28
È¶`Ú0ks   ¦ke a Øâel`gY
@=#dÆ£20ö ?X:CöÃÃñ_¬xVÃo)Ê¶G}a@Np[X+':Uu '-²`sÖ:`G=U¬xV]¸

```

Test it (or Try It Online)

---

## Explanation

### Line 1

Result gets assigned to variable `U`.

```
;C±S ö28
;C           :The lower case alphabet
  ±S         :Append a space and reassign result to C
     ö28     :Generate a string of 28 random characters

```

### Line 2

Result gets assigned to variable `V`.

```
È¶`Ú...l`gY
È               :A function that takes 2 arguments; a string (X) and an integer (Y)
  `Ú...l`       :  The compressed string "methinks it is like a weasel"
         gY     :  Get the character at index Y
 ¶              :  Test for equality with X

```

### Line 3

The result of this line is implicitly joined with newlines and output.

```
@=#dÆ£20ö ?X:CöÃÃñ_¬xVÃo)Ê¥G}a@Np[X+':Uu '-²`sÖ:`G=U¬xV]¸
@                           }a@                            :Repeat until true
                                 [                     ]   :Build an array containing ...
                                  X+':                     :  A colon appended to the number of the current iteration
                                      Uu                   :  The current value of U uppercased
                                         '-²               :  A hyphen repeated twice
                                            `sÖ:`          :  The compressed string "score: "
                                                   U¬      :  Split U to an array of characters
                                                      V    :   Pass each character X at index Y through function V
                                                     x     :   Reduce by addition
                                                 G=        :   Assign the result to variable G
                                                        ¸  :Join with spaces
                               Np                          :Push to N (initially an empty array)
  #d                                                       :100
    Æ                                                      :Generate the range [0,100) and pass each through a function
     £                                                     :  Map over each character X in U
      20ö                                                  :    Generate a random number in the range [0,20), which has a 5% chance of being 0 (falsey)
          ?X                                               :    If thruthy, return X
            :Cö                                            :    Else return a random character from C
               Ã                                           :  End mapping
                Ã                                          :End function
                 ñ_                                        :Sort by passing each through a function
                   ¬                                       :  Split to an array of characters
                     V                                     :  Pass each character X at index Y through function V
                    x                                      :  Reduce by addition
                      Ã                                    :End sorting
                       o                                   :Pop the last element
 =                      )                                  :Reassign to U
                         Ê                                 :Length
                          ¶G                               :Equal to G

```
> 2 votes

# Answer
# Ruby - 410

```
#!/usr/bin/env ruby
C,RC=[32]+(65..90).to_a,->{C[rand(27)].chr}
T,CO,CH,OU,s,sc,a,aa,z,TR="METHINKS IT IS LIKE A WEASEL",->x{a=0;(0...28).each{|z|a+=1 if x[z]==T[z]};a},->{a[aa.rindex(sc)]},->x,y{print x;print " Score: ";puts y},(0...28).map{RC[]}.join,0,[0],[0],0,->{rand(20)==0}
until sc==28
a=[s]*100;aa=[0]*100;(0...100).each{|x|(0...28).each{|y|a[x][y]=RC[] if TR[]};z=CO[a[x]];aa[x]=CO[a[x]];OU[a[x],z]};sc=aa.max;s=CH[] end

```

Edit\* It's currently failing (for some reason a\[any\] is being set to 0 (type=\>fixnum)). However, the actual design is right, I just need to find the bug causing this to happen (it's very mysterious)
> 1 votes

# Answer
**PHP ~~429~~ ~~426~~ ~~421~~ 415**

```
<? function t(){$a="ABCDEFGHIJKLMNOPQRSTUVWXYZ ";return $a{rand(0,26)};}$c='';$j=$g=0;$i=28;while($i--)$c.=t();function r($s){$i=28;while($i--)!rand(0,19)&&$s{$i}=t();return $s;}function s($s,&$r){$c="METHINKS IT IS LIKE A WEASEL";$i=28;$r=0;while($i--)$r+=$s{$i}==$c{$i};}while($g<28){$n='';$v=0;$i=100;while($i--){s($t=r($c),$a);($a>$v)&&($v=$a)&($n=$t);}($v>$g)&&($g=$v)&($c=$n);echo $j++.": $c -- score: $g\n";}

```

pretty print

```
<?php
function t(){
    $a="ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
    return $a{rand(0,26)};
}
$c='';
$j=$g=0;
$i=28;
while($i--)
    $c.=t();
function r($s){
    $i=28;
    while($i--)
        !rand(0,19)&&$s{$i}=t();
    return $s;
}
function s($s,&$r){
    $c="METHINKS IT IS LIKE A WEASEL";
    $i=28;
    $r=0;
    while($i--)
        $r+=+($s{$i}==$c{$i});
}
while($g<28){
    $n='';
    $v=0;
    $i=100;
    while($i--){
        s($t=r($c),$a);
        ($a>$v)&&($v=$a)&($n=$t);
    }
    ($v>$g)&&($g=$v)&($c=$n);
    echo $j++.": $c -- score: $g\n";
}

```

I'll need a less verbose language next time
> 1 votes

# Answer
## Python 284

```
from random import*
C=choice
A=map(chr,range(65,91)+[32])
s=[C(A)for i in[0]*28]
N=x=0
while N!=28:N,s=max((len([i for i,j in zip(X,"METHINKS IT IS LIKE A WEASEL")if i==j]),X)for X in[[c if random()<.95 else C(A)for c in s]for i in[0]*100]);print`x`+":",''.join(s),"-- score:",N;x+=1

```
> 1 votes

# Answer
## GolfScript 207

```
{91,{64>},32+''+27rand=}:g;'METHINKS IT IS LIKE A WEASEL':s;{`{\.@\=s@==}+s,,\%{+}*}:c;0:k;{k):k\.': '@@c' -- score: '\++++n+}:f;[{g}]28*{~}%{s=!}{{`100,\{\;{100rand 5>{ }{;g}if}%''+}+}~%{c}$)\;{ }%}/{f}/s f

```

Below is a slightly unpacked version of the above GolfScript with explanation. Since I don't think it could beat the APL or some other answers, I didn't bother to truly minify it. I think that with inlining variable declarations, eliminating unnecessary variables, and other such tricks, this code could achieve approximately 190 characters without really changing the algorithm. I think about about 10-15 characters could be removed if I better sorted out the conversion between arrays of ASCII values and strings.

```
#g is a function that returns the ASCII value of a random character or space.
#The ASCII values for capital letters are 65-90, and 32 is space.
{91,{64>},32+''+27rand=}:g;

#s is the string of interest.
'METHINKS IT IS LIKE A WEASEL':s;

#c is a function that returns the 'score' of a given string
#(the number of correct characters in the correct place).
{`{\.@\=s@==}+s,,\%{+}*}:c;

#t is a function that transforms a given string according to
#the specification (by replacing characters with a random character 5% of the times).
{{100rand 5>{ }{;g}if}%''+}:t;

#i is the initial random string.
[{g}]28*{~}%:i;

#Use '/' to unfold the initial value until the string is equal to the string of interest.
#Every loop, do the transformation 100 times, then sort by score c, and then take the top scoring string.
#Aggregate the results into an array a.
i{s=!}{{`100,\{\;t}+}~%{c}$)\;{ }%}/:a;

#Instantiate a counter variable k
0:k;

#f is the formatting function, that takes a string and formats it according to the spec.
{k):k\.': '@@c' -- score: '\++++n+}:f;

#Format every string in the array, and then format the string of interest
a{f}/
s f

```
> 1 votes

# Answer
# JavaScript - 312

There is already a shorter JS solution above but it is using experimental pointer functions, so I thought I'd throw in another solution that is running in any JS environment:

```
for(r=Math.random,R=function(){return'METHINKS CODZAWFLBUGYQRXVJP'[~~(r()*27)]},_=[],_.$=n=0,D=function(s){for(c=[],c.$=i=0;i<28;){c[i]=s&&r()<.95?s[i]:R();_=(c.$+=c[i]=='METHINKS IT IS LIKE A WEASEL'[i++])>_.$?c:_};return c},D();_.$<28;){for(j=0;j++<1e2;)D(_);console.log(n+++': '+_.join('')+' -- score: '+_.$)}

```
> 1 votes

# Answer
## Java: ~~557~~ 534

```
enum W{W;public static void main(String[]a){char[]c=new char[28],h,d[];int i,k,e,s=W.s(c);for(i=0;i<28;i++)c[i]=W.r();for(i=0;;){W.p(i++,h=c,s);if(s>27)break;d=new char[100][28];for(char[]b:d){for(k=0;k<28;k++)b[k]=Math.random()<.05?W.r():h[k];if((e=W.s(b))>s){s=e;c=b;}}}}int s(char[]c){int s=0,k;for(k=0;k<28;k++)if(c[k]=="METHINKS IT IS LIKE A WEASEL".charAt(k))s++;return s;}void p(int i,char[]c,int s){System.out.println(i+": "+new String(c)+" -- score: "+s);}char r(){int i=(int)(Math.random()*27);return(char)(i==26?32:i+65);}}

```

Unwrapped:

```
enum W {
    W;

    public static void main(String[] a) {
        char[] c = new char[28], h, d[];

        int i, k, e, s = W.s(c);

        for(i = 0; i < 28; i++)
            c[i] = W.r();

        for(i = 0;;) {
            W.p(i++, h = c, s);

            if(s > 27)
                break;

            d = new char[100][28];

            for(char[] b : d) {
                for(k = 0; k < 28; k++)
                    b[k] = Math.random() < .05 ? W.r() : h[k];

                if((e = W.s(b)) > s) {
                    s = e;
                    c = b;
                }
            }
        }
    }

    int s(char[] c) {
        int s = 0, k;
        for(k = 0; k < 28; k++)
            if(c[k] == "METHINKS IT IS LIKE A WEASEL".charAt(k))
                s++;

        return s;
    }

    void p(int i, char[] c, int s) {
        System.out.println(i + ": " + new String(c) + " -- score: " + s);
    }

    char r() {
        int i = (int)(Math.random() * 27);
        return (char)(i == 26 ? 32 : i + 65);
    }
}

```
> 1 votes

# Answer
## Groovy: 314

```
def(r,o,g)=[new Random(),{(0..27).sum{x->"METHINKS IT IS LIKE A WEASEL"[x]==it[x]?1:0}},0]
def q={([' ']+('A'..'Z'))[r.nextInt(27)]}
def s=q()*28
for(;;){println"${g++}: $s -- score: ${o(s)}"
if(o(s)==28)break
s=([s]*100).collect{it.collect{5>r.nextInt(100)?q():it}.sum()}.groupBy{o(it)}.max{it.key}.value[0]}

```

Output:

```
0:                              -- score: 5
1:          B               S   -- score: 6
2:  E       B               S M -- score: 7
3:  E       B               S M -- score: 7
4:  E       BT      X       S M -- score: 8
...
68: METHINKS IT IS LIKE L WEASEL -- score: 27
69: METHINKS IT IS LIKE L WEASEL -- score: 27
70: METHINKS IT IS LIKE L WEASEL -- score: 27
71: METHINKS IT IS LIKE L WEASEL -- score: 27
72: METHINKS IT IS LIKE A WEASEL -- score: 28

```

I feel like this is cheating so I'm not counting it as my 'real' answer; but I can save a few chars by passing "METHINKS IT IS LIKE A WEASEL" and " -- score: " as arguments to my script. Although technically it is 'externalizing strings'... which everyone knows is good practice :).

## Groovy: 290

```
def(r,o,g)=[new Random(),{(0..27).sum{x->args[0][x]==it[x]?1:0}},0]
def q={([' ']+('A'..'Z'))[r.nextInt(27)]}
def s=q()*28
for(;;){println"${g++}: $s${args[1]}${o(s)}"
if(o(s)==28)break
s=([s]*100).collect{it.collect{5>r.nextInt(100)?q():it}.sum()}.groupBy{o(it)}.max{it.key}.value[0]}

```

Run like `groovy script.groovy "METHINKS IT IS LIKE A WEASEL" " -- score: "`
> 1 votes

# Answer
**Golfscript (**168** 167)**

```
:x;0['METHINKS IT IS LIKE A WEASEL'{}/]:o{;{27rand.!96*+64^}:r~}%{o=!}{100,{;.{20rand{}{;r}if}%}%{{[o\]zip{~=},,}:s~}$)@;\;x 2$+': '+1$+' -- score: '+1$s+n+:x;\)\}/;;x

```

Sadly, I can't seem to compress it quite to APL's level, but it's afaict currently a shared second place.

This is what it does;

```
# Grab the empty parameter string as initially empty output string.
:x;
# Start count at row #0
0
# Store the target string as an array in 'o'
['METHINKS IT IS LIKE A WEASEL'{}/]:o
# Create a random starting string, and define 'r' as a function generating a random char.
{;{27rand.!96*+64^}:r~}%
# Unfold as long as the latest string is different from the target string.
{o=!}
{
  // Generate 100 strings, sort by score and keep the highest.
  100,{;.{20rand{}{;r}if}%}%{{[o\]zip{~=},,}:s~}$)@;\;
  // Append the row to the output string, and increase the row number
  x 2$+': '+1$+' -- score: '+1$s+n+:x;\)\
}/
// Clean some junk on the stack
;;
// Output string
x

```
> 1 votes

# Answer
### R, 291 characters

Longer than the previously proposed R answer but significantly different to be (I think) of interest:

```
a=sample;b=a(c<-c(LETTERS,' '),28,T);d=0;h=function(x)sum(x==strsplit("METHINKS IT IS LIKE A WEASEL",'')[[1]]);while(h(b)!=28){if(d){f=replicate(100,{e=runif(28)>.05;S=a(c,28,T);S[e]=b[e];S});g=f[,which.max(apply(f,2,h))];if(h(g)>h(b))b=g};cat(d,': ',b,' -- score: ',h(b),'\n',sep='');d=d+1}

```

With indentations:

```
a=sample
b=a(c<-c(LETTERS,' '),28,T)
d=0
h=function(x)sum(x==strsplit("METHINKS IT IS LIKE A WEASEL",'')[[1]])
while(h(b)!=28){
    if(d){
        f=replicate(100,{e=runif(28)>.05;S=a(c,28,T);S[e]=b[e];S})
        g=f[,which.max(apply(f,2,h))]
        if(h(g)>h(b))b=g
        }
    cat(d,': ',b,' -- score: ',h(b),'\n',sep='')
    d=d+1
    }

```

Outputs:

```
0: OUZ IT HNGNMSKIHSMCQUGXTOYVZ -- score: 1
1: OUZ IT HNGNMSKYHSMCQUGWXOYVZ -- score: 2
2: OUZ IT HNGNMSKYLSMCQUGWXOYVZ -- score: 3
3: OUZ IT HNGNMSKYLSMC UGWXOYVZ -- score: 4
...
68: METHINKS IT ES LIKE A WEASEL -- score: 27
69: METHINKS IT ES LIKE A WEASEL -- score: 27
70: METHINKS IT IS LIKE A WEASEL -- score: 28

```

The key here is the line `f=replicate(100,{e=runif(28)>.05;S=a(c,28,T);S[e]=b[e];S})`:
`e=runif(28)>.05` draws randomly 28 numbers between 0 and 1 on a uniform distribution, and gives TRUE if over 5% and FALSE if under 5%. `S=a(c,28,T)` draws 28 new letters/spaces, while `S[e]=b[e]` replaces those for which the value was over 5% by the corresponding letter from the previous generation (i .e. those for which the value was less than 5% are therefore new).Then we replicate the operation 100 times. On the following line (`g=f[,which.max(apply(f,2,h))]`) we compute the score for each of the 100 replicates and keep the one that has the maximum score (in case of equality the first one is kept) to be compared with the previous generation.
> 1 votes

# Answer
# C 331

Another C solution that comes out to 331 characters. I think I might be able to improve it if I look a bit closer. Anyway the solution follows:

```
char l[29],b[29],*a="ABCDEFGHIJKLMNOPQRSTUVWXYZ ",i,j,*t="METHINKS IT IS LIKE A WEASEL",s,m=0;main(){for(i=0;i<28;i++)l[i]=a[rand()%27];while(strcpy(l,b))for(i=0;i<100;i++){for(j=s=0;j<28;j++){if(rand()%20==0)l[j]=a[rand()%27];if(l[j]==t[j])s++;}printf("%s -- score: %d\n",l,s);if(s>m){m=s;strcpy(b,l);}if(!strcmp(b,t))goto e;}e:;}

```
> 1 votes

# Answer
## Haskell - 420 characters

This is more verbose than most; I'd put that down to my inexperience with randomness in haskell and proper use of monads.

```
import System.Random
r=randomRIO
z=zipWith
c=fmap((' ':['A'..'Z'])!!)$r(0,26)
y=(i.).replicate
i=mapM id
s=sum.z((fromEnum.).(==))"METHINKS IT IS LIKE A WEASEL"
u a n|n==0=c|True=return a
b n a|s n>s a=n|True=a
g=fmap(foldr1 b).y 100.mapM((r(0,20)>>=).u)
e x=do n<-g$x!!0;if(s$x!!0)==28 then return(n:x)else e(n:x)
main=y 28 c>>=(\a->e[a])>>=(i.z(\n x->putStrLn$shows n$": "++x++" -- score: "++(show$s x))[0..]).reverse

```
> 1 votes

# Answer
## Javascript (~~411~~ ~~389~~ 376)

Shorter than some, longer than most.. \[Methinks it will end.\] ***EDIT:*** it wasn't ending due to an error. fixed it and ended up dropping the count too -- cool.

```
t='METHINKS IT IS LIKE A WEASEL';z=0;m=Math.random;r=function(){n=Math.floor(m()*27);return n?String.fromCharCode(64+n):' '};for(s='';s.length<28;s+=r());while(z<28){a=[s];while(a.length<100){x='';while(x.length<28){x+=m()>=.95?r():s.substr(x.length,1)}a.push(x)}for(i=0;i<100;i++){b=0;for(j=0;j<28;j++){b+=a[i][j]==t[j]?1:0;}if(b>z){alert(a[i]+' -- score: '+b);z=b;s=a[i]}}};

```

expanded:

```
t = 'METHINKS IT IS LIKE A WEASEL';
z = 0;
m = Math.random;
r = function(){
    n = Math.floor(m()*27);
    return n ? String.fromCharCode(64+n) : ' '
};
for(s='';s.length<28;s+=r());
while( z < 28 ){
    a = [s];
    while( a.length < 100 ){
        x = '';
        while( x.length < 28 ){
            x += m() >= .95 ? r() : s.substr(x.length, 1)
        }
        a.push(x)
    }
    for( i = 0; i < 100; i++ ){
        b = 0;
        for( j = 0; j < 28; j++ ){
            b += a[i][j] == t[j] ? 1 : 0;
        }
        if( b > z ){
            console.log( a[i] + ' -- score: ' + b);
            z = b;
            s = a[i]
        }
    }
};

```

---

\[original:\]
```
t='METHINKS IT IS LIKE A WEASEL';s='';z=0;m=Math.random;r=function(){n=Math.floor(m()*27);return n?String.fromCharCode(64+n):' '};c=function(){a=[s];while(a.length<100){x='';while(x.length<28){x+=m()>=.95?r():s.substr(x.length?x.length-1:0,1)}a.push(x)}for(i=0;i<100;i++){b=0;for(j=0;j<28;j++){b+=a[i][j]==t[j]?1:0;}if(b>z){alert(a[i]+' -- score: '+b);z=b;s=a[i]}i++}};while(s.length<28){s+=r()}while(z<28){c()}

```
> 1 votes

# Answer
# Racket: ~~426~~ 422 bytes

```
(let*((r random)(m map)(L" ABCDEFGHIJKLMONPQRSTUVWXYZ")(P(string->list"METHINKS IT IS LIKE A WEASEL"))(c(λ(l p)(m(λ(x)(if(<(r)p)(string-ref L(r 27))x))l)))(s(λ(l P p)(cons(foldl(λ(x y a)(if(eqv? x y)(+ a 1)a))0 l P)l))))(let r((g 0)(o (c P 1)))(let*((o(sort(m(λ(x)(s(c o 0.05)P 0))(range 100))(λ g(apply >(m car g)))))(p(caar o))(c(cdar o)))(printf"~a: ~a -- score: ~a
"g(list->string c)p)(if(= p 28)p(r(+ g 1)c)))))

```

Ungolfed:

```
(let* ((r random)
       (m map)
       (L " ABCDEFGHIJKLMONPQRSTUVWXYZ")
       (P (string->list "METHINKS IT IS LIKE A WEASEL"))
       (c (λ (l p)
            (m (λ (x)
                 (if (< (r) p)
                     (string-ref L (r 27))
                     x))
               l)))
       (s (λ (l P p)
            (cons (foldl (λ (x y a)
                           (if (eqv? x y)
                               (+ a 1)
                               a))
                         0
                         l
                         P)
                  l))))
  (let r ((g 0) (o (c P 1)))
    (let* ((o (sort (m (λ (x)
                         (s(c o 0.05)P 0))
                       (range 100))
                    (λ g
                      (apply >(m car g)))))
           (p (caar o))
           (c (cdar o)))
      (printf"~a: ~a -- score: ~a\n" g (list->string c) p)
      (if (= p 28)
          p
          (r (+ g 1) c)))))

```
> 1 votes

# Answer
# Python 2.7 - 319 bytes

Sure it's not the smallest, but it was fun to program.

```
from random import*
a=map(chr,range(65,91))+[' ']
c,i,y=choice,0,{}
s=[c(a)for i in[0]*28]
while 1:
 for j in[0]*100:v=[c(a)if .05>random()else x for x in s];y[sum(1if'METHINKS IT IS LIKE A WEASEL'[k]==v[k]else 0for k in range(28))]=v
 v=max(y.keys());s=y[v];print"%d: %s -- score: %d"%(i,''.join(y[v]),v);i+=1
 if v==28:break

```

Uses a recursing function, so it may reach the maximum recursion depth if there is some kind of weird devolution with the string.

```
ubuntu@ubuntu-OptiPlex-980:~$ python weasel.py
0: VPBHBSPWFTOG HAXSESCDNFPKWYE -- score: 1
1: VABHBSPWFTOG HAXSESCDNWPKWYE -- score: 2
2: VAWHBSPWFTOGIHAXSESSDNWPKWYE -- score: 3
3: VAWHBSPWFTOGIHAXSEFSGNWPKWYL -- score: 4
4: XAWHBSPYFTOGIHAXSEFSGNWPKWYL -- score: 4
5: XAWHBSKYFTOGIHAXSEFSGNWPKWYL -- score: 5
6: XAWHBSKYFTOGIHAXSEF GNWPKWYL -- score: 6
7: XAWHBSKYFTOGIHALSEF ANWPKWYL -- score: 8
8: XAKHBSKYFTTGIHALSEY ANWPKWYL -- score: 9
9: XAKHISKYFTTGIHALSEE ANWPKWYL -- score: 11
10: XAKHISKSFTTGIHALSEE ANWPKWYL -- score: 12
11: XAKHISKSFTTGIHALSBE ANWPKWKL -- score: 12
12: XAQHISKSFRT IHALSBE ANWPKWKL -- score: 13
13: XAQHISKSFIT IHALSBE ANWPKWKL -- score: 14
14: XAQHISKSFIT IHALSBE ANWPKWKL -- score: 14
15: XAQHISKSFIT IHALSBE ANWPKWKL -- score: 14
16: XALHISKSFIT ISALSBE ANWPKWKL -- score: 15
17: JALHISKSFIT ISALSBE ANWPAWKL -- score: 16
18: JALHISKSFIT ISALIBE ANWPAWKL -- score: 17
19: JALHISKSFIT ISALIBE ANWPAWKL -- score: 17
20: JALHISKSFIT ISALIBE ANWPAWKL -- score: 17
21: JALHISKSFIT ISALIKE ANWPAWYL -- score: 18
22: JALHISKSFIT IS LIKE ANWPAWYL -- score: 19
23: JALHISKSFIT IS LIKE ANWEAWYL -- score: 20
24: JALHISKSFIT IS LIKE ANWEAWYL -- score: 20
25: JALHISKSFIT IS LIKE ANWEAWZL -- score: 20
26: JALHISKS IT IS LIKE ANWEAAZL -- score: 21
27: JACHISKS IT IS LIKE ANWEASZL -- score: 22
28: JACHISKS IT IS LIKE ANWEASZL -- score: 22
29: MACHISKS IT IS LIKE ANWEASZL -- score: 23
30: MACHISKS IT IS LIKE ANWEASZL -- score: 23
31: MACHISKS IT IS LIKE AUWEASZL -- score: 23
32: MACHISKS IT IS LIKE AUWEASZL -- score: 23
33: MACHISKS IT IS LIKE AJWEASZL -- score: 23
34: MACHISKS IT IS LIKE A WEASZL -- score: 24
35: MACHISKS IT IS LIKE A WEASZL -- score: 24
36: MACHINKS IT IS LIKE A WEASZL -- score: 25
37: MACHINKS IT IS LIKE A WEASZL -- score: 25
38: MACHINKS IT IS LIKE A WEASZL -- score: 25
39: MBCHINKS IT IS LIKE A WEASZL -- score: 25
40: MBCHINKS IT IS LIKE A WEASZL -- score: 25
41: MBCHINKS IT IS LIKE A WEASZL -- score: 25
42: MBCHINKS IT IS LIKE A WEASZL -- score: 25
43: MBCHINKS IT IS LIKE A WEASZL -- score: 25
44: MBCHINKS IT IS LIKE A WEASZL -- score: 25
45: MECHINKS IT IS LIKE A WEASCL -- score: 26
46: MECHINKS IT IS LIKE A WEASCL -- score: 26
47: MECHINKS IT IS LIKE A WEASCL -- score: 26
48: MECHINKS IT IS LIKE A WEASCL -- score: 26
49: MECHINKS IT IS LIKE A WEASCL -- score: 26
50: MECHINKS IT IS LIKE A WEASCL -- score: 26
51: MEQHINKS IT IS LIKE A WEASCL -- score: 26
52: MEQHINKS IT IS LIKE A WEASCL -- score: 26
53: MEQHINKS IT IS LIKE A WEASCL -- score: 26
54: MEQHINKS IT IS LIKE A WEASCL -- score: 26
55: MEQHINKS IT IS LIKE A WEASCL -- score: 26
56: MEQHINKS IT IS LIKE A WEASCL -- score: 26
57: METHINKS IT IS LIKE A WEASCL -- score: 27
58: METHINKS IT IS LIKE A WEASCL -- score: 27
59: METHINKS IT IS LIKE A WEASCL -- score: 27
60: METHINKS IT IS LIKE A WEASCL -- score: 27
61: METHINKS IT IS LIKE A WEASCL -- score: 27
62: METHINKS IT IS LIKE A WEASCL -- score: 27
63: METHINKS IT IS LIKE A WEASCL -- score: 27
64: METHINKS IT IS LIKE A WEASCL -- score: 27
65: METHINKS IT IS LIKE A WEASEL -- score: 28

```

Massive thanks to Sp3000 for golfing help.
> 1 votes

# Answer
# C++ 668

Not really short, but the only one in c++. (:

```
#include "stdafx.h"
using namespace std;int _tmain(){srand(time(NULL));string z="METHINKS IT IS LIKE A WEASEL";string a(28,' ');for(int i=0;i<28;++i){a[i]='A'+(rand()%26);}while(1){vector<std::pair<int,string>>d;for(int i=0;i<100;++i){d.push_back(std::pair<int,string>(0,""));for(int j=0;j<28;++j){int b=rand()%100;if(b<6){if(b<2){d[i].second+=' ';}else{d[i].second+='A'+(rand()%26);}}else {d[i].second+=a[j];}}}for(int i=0;i<100;++i){for(int j=0;j<28;++j){if(d[i].second[j]==z[j]){d[i].first++;}}}int y=0;for(int i=0;i<100;++i){if(d[i].first==28){cout<<d[i].second<<" "<<d[i].first;exit(1);}else if(d[i].first>y){y=d[i].first;a=d[i].second;}}cout<<a<<" "<<y<<endl;}}

```

more readable version:

```
#include "stdafx.h"
#include <string>
#include <stdlib.h>
#include <vector>
#include <iostream>
#include <time.h>
using namespace std;

int _tmain()
{
  srand(time(NULL));
  string z = "METHINKS IT IS LIKE A WEASEL";
  string a(28, ' ');
  for (int i = 0; i < 28; ++i)
  {
    a[i] = 'A' + (rand() % 26);
  }
  while(1)
  {
    vector<std::pair<int, string >> d;
    for (int i = 0; i < 100; ++i)
    {
      d.push_back(std::pair<int, string>(0, ""));
      for (int j = 0; j < 28; ++j)
      {
        int b = rand() % 100;
        if (b < 6)
        {
          if (b < 2)
          {
            d[i].second += ' ';
          }
          else {
            d[i].second += 'A' + (rand() % 26);
          }
        }
        else {
          d[i].second += a[j];
        }
      }
    }
    for (int i = 0; i < 100; ++i)
    {
      for (int j = 0; j < 28; ++j)
      {
        if (d[i].second[j] == z[j])
        {
          d[i].first++;
        }
      }
    }
    int y = 0;
    for (int i = 0; i < 100; ++i)
    {
      if (d[i].first == 28)
      {
        cout << d[i].second << " " << d[i].first;
        exit(1);
      }
      else if (d[i].first > y)
      {
        y = d[i].first;
        a = d[i].second;
      }
    }
    cout << a << " " << y << endl;
  }
}

```

Output:

```
VEBVTEWX CEWMYLTAJTYPFYYXBDQ 2
 EBVTEWX CEWMYLTAJT PFYYXBDQ 3
 EBVTEKX CEWMYLTAJT PFYYXBDQ 4
 EBVTEKX CEWM  TAJT PFYYXBDQ 5
 EBVTEKX CE M  TAJT P YYX DQ 7
MEPVTEKX CE M  TAJT P YY  D  8
MEPVT KX CE M  TAJT A YY  D  9
MEPVI KX CE M  UAJT A YY  D  10
MEPSI KX CE M  UAJT A YY  D  10
MEPSI K  CE M  UAJE A YY  DE 11
MEPSI K  CE M  UAJE A YY  DL 12
MEPPI K  CE I  UDJE A YY  DL 13
MEPRI K  CE IS UDJE A YY  DL 14
MEPRI K  CE IS UDJE A  Y  DL 14
MEPHI K  CE IS UDJE A  Y  DL 15
MEPHI K  CE IS UDJE A  Y  DL 15
MEPHI K  CE IS RDBE A  E  DL 16
MEPHIQK  CE IS RD E A  E  DL 16
MEPHIQK  CE IS RD E A  E  DL 16
ME HIQK  CE IS RDXE A  E  DL 16
ME HIQK  CE IS W XE A  E  DL 16
ME HIQK  CE IS W XE A  E  EL 17
ME HIQK  CE IS W XE A  E  EL 17
ME HIQK  CE IS   XE A  E  EL 17
MEGHIQK  CE IS   XE A WEO EL 18
MEGHIQK  CE IS   XE A WEO EL 18
MEGHIQK  CE IS   XE A WEO EL 18
MEGHIQK  CE IS   XE A WE  EL 18
MEGHIQK  CE IS   XE A WE SEL 19
MEGHIQK  CE IS L XE A WE SEL 20
MEGHINK  CE IS L XE A WE SEL 21
MEGHINK  CE IS L XE A WE SEL 21
MEGHINK  CN IS L XE A WEASEL 22
MEGHINK   H IS L XE A WEASEL 22
MEGHINK   H IS L XE A WEASEL 22
METHINK   H IS L XE A WEASEL 23
METHINK   H IS L XE A WEASEL 23
METHINK   H IS L XE A WEASEL 23
METHINK   H IS L XE A WEASEL 23
METHINK   H IS L XE A WEASEL 23
METHINK   H IS L XE A WEASEL 23
METHINK  ZH IS L XE A WEASEL 23
METHINK  ZH IS LIXE A WEASEL 24
METHINK  ZH IS LIKE A WEASEL 25
METHINKD ZH IS LIKE A WEASEL 25
METHINKD ZH IS LIKE A WEASEL 25
METHINKD ZH IS LIKE A WEASEL 25
METHINKD ZH IS LIKE A WEASEL 25
METHINKD ZT IS LIKE A WEASEL 26
METHINKD ZT IS LIKE A WEASEL 26
METHINKD ZT IS LIKE A WEASEL 26
METHINKS ZT IS LIKE A WEASEL 27
METHINKS IT IS LIKE A WEASEL 28

```
> 1 votes

# Answer
# Julia, 281 bytes

Golfed:

```
r=n->['A':'Z',' '][rand(1:27,n)]
s=a->sum(a.=="METHINKS IT IS LIKE A WEASEL".data)
p=(z,a,s)->println(z,": ",join(a)," -- score: ",s)
a = r(28)
b = s(a)
z = 0
p(z,a,b)
while b<28
c=b
d=a
for i=1:100
e=[rand()<.95?i:r(1)[1]for i=a]
f=s(e)
if(f>c)
c=f
d=e
end
end
a=d
b=c
p(z,a,b)
z+=1
end

```

The algorithm itself isn't very clever, but there are some cool bits in here. Combining a character range with another character, then indexing into it: `['A':'Z',' '][rand(1:27,n)]` and taking the sum of an array of booleans (common, but I still love the idea): `sum(a.=="METHINKS IT IS LIKE A WEASEL".data)`. Glad I got under 300!

Ungolfed:

```
randchar = n -> ['A':'Z',' '][rand(1:27,n)]
score = a -> sum(a.=="METHINKS IT IS LIKE A WEASEL".data)
myprint = (z,a,s) -> println(z,": ",join(a)," -- score: ",s)
currentarray = randchar(28)
currentscore = score(currentarray)
z = 0
myprint(z,currentarray,currentscore)
while currentscore < 28
    bestscore = currentscore
    bestarray = currentarray
    for i = 1:100
        temparray = [rand()<.95?i:randchar(1)[1]for i=currentarray]
        tempscore = score(temparray)
        if(tempscore > bestscore)
            bestscore = tempscore
            bestarray = temparray
        end
    end
    currentarray = bestarray
    currentscore = bestscore
    myprint(z,currentarray,currentscore)
    z+=1
end

```
> 1 votes

# Answer
# Japt, 98 bytes

```
;ªBiS ö28
=#dÆ£20ö ?X:BiS)öÃÃñL=_¬xÈ¶Yg`Ú0ks   ¦ke a Øâel`u
mL o
=o
Op[T°+':X'-²`sÖ`W]¸
W<28©ß

```

Not a winner, but I really wanted to answer this fun challenge.

Test it
> 1 votes

# Answer
# JavaScript (Node.js), 328 bytes

```
t="METHINKS IT IS LIKE A WEASEL";z=0;m=Math.random;r=_=>(n=0|27*m())?String.fromCharCode(64+n):" ";for(s="";28>s[l="length"];s+=r())for(;28>z;){for(a=[s];100>a[l];){for(x="";28>x[l];)x+=.95<=m()?r():s.substr(x[l],1);a.push(x)}for(i=0;100>i;i++){for(j=b=0;28>j;j++)b+=a[i][j]==t[j];b>z&&(alert(a[i]+" -- score: "+b),z=b,s=a[i])}}

```

Try it online!

This is rather long and can be shortened, just haven't gotten around to that.

---

# Explanation :

This is not exactly an explanation but it is better indented and can

```
t = "METHINKS IT IS LIKE A WEASEL";
z = 0;
m = Math.random;
r = _ => (n = 0 | 27 * m()) ? String.fromCharCode(64 + n) : " ";
for (s = ""; 28 > s[l = "length"]; s += r())
 for (; 28 > z;) {
  for (a = [s]; 100 > a[l];) {
   for (x = ""; 28 > x[l];) x += .95 <= m() ? r() : s.substr(x[l], 1);
   a.push(x)
  }
  for (i = 0; 100 > i; i++) {
   for (j = b = 0; 28 > j; j++) b += a[i][j] == t[j];
   b > z && (alert(a[i] + " -- score: " + b), z = b, s = a[i])
  }
 }
```
> 0 votes

# Answer
# Pyth, 116 bytes

```
Ls.bqNY"METHINKS IT IS LIKE A WEASEL"bj.e%"%d: %s -- score: %s"[ksbyb).W<yeH28+Z]eoyNmmO.[O+r1G\ k20eZ100]mO+r1G\ 28

```

Try it online.

```
Ls.bqNY"..."bj.e%"..."[ksbyb).W<yeH28+Z]eoyNmmO.[O+r1G\ k20eZ100]mO+r1G\ 28

L                                                                             Define fitness function, y(b):
       "..."                                                                    The target string
  .b        b                                                                   Map over characters of the above and b:
    qNY                                                                           Are they equal? True = 1, False = 0
 s                                                                              Take the sum
                                                                    r1G       The uppercase alphabet
                                                                   +   \      Append a space
                                                                  O           Choose one at random
                                                                ]m       28   Create an array of 28 of the above, wrap in array
                             .W                                               Functional while, with above as initial value
                                                                                Continue condition (current value = H):
                                 eH                                               Last value of H
                                y                                                 Apply fitness function to the above
                               <   28                                             Check the above is less than 28
                                                                                Function body (current value = Z)
                                             m             eZ                     Map each character (as k) in the last value in Z over:
                                                 O+r1G\                             Choose random char/space (as above)
                                               .[       k20                         Pad the above to length 20 using k
                                              O                                     Choose one of the above at random
                                            m                100                  Do the above 100 times
                                         oyN                                      Order the above by the fitness function
                                       ]e                                         Take the last of the above, wrap in array
                                     +Z                                           Append to Z
                                                                              Return value of while is array of all steps taken
              .e                                                              Map each entry with its index over:
                       k                                                        Current index
                        sb                                                      Current entry joined on empty string
                          yb                                                    Fitness of current entry
                      [     )                                                   Wrap the above 3 results in an array
                %"..."                                                          String formatting using the output string
             j                                                                Join on newlines, implicit output

```
> 0 votes

---
Tags: code-golf, string, random, genetic-algorithms
---


title: Convert to Bubble Letters

text:
# Question
Title: Convert to Bubble Letters
So I was playing around with my compose key, and found some cool things, one of them being that by pressing `compose + ( + alphanumeric + )`, you get that character inside a bubble, like so: .

Your task in this challenge is simple, to convert ordinary text to bubble letter text.

Here are the ascii chars, the bubble characters and their Unicode code points:

```
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
⓪①②③④⑤⑥⑦⑧⑨ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ
9450 9312 9313 9314 9315 9316 9317 9318 9319 9320 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423

```

Your input will contain only printable ascii characters, and if a character cannot be bubbleified, leave it as is.

This is , so shortest code in **bytes** wins!

*Note: This is not isomorphic to my earlier challenge about small-caps conversion since unlike small-caps, bubble letters are in a mostly contiguous segment of code-points, allowing for more interesting approaches.*

# Answer
> 12 votes
# Retina, 20 bytes

```
T`Lld`Ⓐ-⓪①-⑨

```

Try it online!

### How it works

There's a gap between the code points of **(0)** and **(1)**, but – fortunately – the character right after **(z)** is **(0)**. This way, we can transliterate the character from concatenated ranges **A-Za-z0-9** to the characters of the concatenated ranges **(A)-(0)(1)-(9)**.

The rest is straightforward: `T` activates transliteration mode, `Lld` yields all uppercase ASCII letters (`L`), all lowercase ASCII letters (`l`) and all digits (`d`), and `Ⓐ-⓪①-⑨` the corresponding bubble characters.

# Answer
> 5 votes
# Python 3, 146 bytes

```
for p in list(input()):
 t=0
 if p.isdigit():t=9263
 if p=='0':t=9402
 if p.isalpha():
  t=9327
  if p.upper()==p:t=9333
 print(end=chr(ord(p)+t))

```

This might be able to be made shorter, any help would be appreciated. Try it on repl.it, here.

# Answer
> 3 votes
# 05AB1E, 19 bytes

Uses CP-1252 encoding.

```
žKš52Ý86+8Ý«9312+ç‡

```

Try it online!

**Explanation**

```
žK                    # Push the string "a-zA-Z0-9"
  š                   # switch case: "A-Za-z0-9"
   52Ý                # push range [0 ... 52]
      86+             # add 86: [86 ... 138]
         8Ý«          # concatenate with range [0 ... 8]: [86 ... 138, 0 ... 8]
            9312+     # add 9312: [9398 ... 9450, 9312 ... 9320]
                 ç    # convert to char: ['Ⓐ', ... 'Ⓩ', 'ⓐ', ..., 'ⓩ', '⓪', ..., '⑨']
                  ‡   # transliterate alphabet to bubble alphabet

```

# Answer
> 2 votes
# Jelly, ~~23~~ ~~22~~ 21 bytes

```
“2Ỵf“2Ṇ3‘r/9.ȷ_ỌFØB,y

```

Try it online!

### How it works

```
“2Ỵf“2Ṇ3‘r/9.ȷ_FỌØB,y  Main link. Argument: s (string)

“2Ỵf“2Ṇ3‘              Yield [[50, 188, 102], [50, 180, 51]].
         r/            Reduce by range.
                       This yields [[50], [188, ..., 180], [102, ..., 51].
           9.ȷ_        Subtract these integers from 9500.
                       This yields [[9450], [9312, ..., 9320], [9398, ..., 9449]].
               Ọ       Unordinal; convert the resulting code points to characters.
                F      Flatten the resulting array of strings.
                       This yields the bubbles of
                       [0, ..., 9, A, ..., Z, a, ..., z].
                 ØB,   Pair "0...9A...Za...z" with the generated string.
                    y  Transliterate.

```

# Answer
> 2 votes
# Ruby, ~~38~~ 34 \+ 1 = 35 bytes

+1 byte for `-p` flag. Takes input on STDIN.

-3 bytes thanks to Dennis.

```
$_.tr!"A-Za-z0-9","Ⓐ-⓪①-⑨"

```

See it on eval.in: https://eval.in/636978

# Answer
> 2 votes
# Bash on OSX, 27

* 3 bytes saved thanks to @Dennis.

```
  tr A-Za-z0-9 Ⓐ-⓪①-⑨

```

I/O via STDIN/STDOUT. The OSX `tr` apparently handles these unicode characters whereas the GNU coreutils `tr` does not.

# Answer
> 1 votes
# JavaScript (ES6) 93 ~~104~~

**Edit** 11 bytes saved thx @Neil again

Having to use `String.fromCharCode`, javascript is doomed...

```
s=>s.replace(/[^\W_]/g,c=>String.fromCharCode(9388+parseInt(c,36)+(-c?-77:62-c||c>'Z'&&26)))

```

**Test**

```
f=
s=>s.replace(/[^\W_]/g,c=>String.fromCharCode(9388+parseInt(c,36)+(-c?-77:62-c||c>'Z'&&26)))

function update() {
  O.textContent=f(I.value)
}

update()
```

```
<input id=I oninput="update()" value='Hello world!'>
<pre id=O></pre>
```

# Answer
> 1 votes
# Perl, 27 bytes

Includes +1 for `-p`

Give input on STDIN, uses the Dennis transliteration order. The only thing interesting about this solution is the lack of the final `;` (needs a recent enough perl)

```
#!/usr/bin/perl -p
y;A-Za-z0-9;Ⓐ-⓪①-⑨

```

# Answer
> 1 votes
# R, 140 bytes

A bit late to the party again.

```
x=utf8ToInt(scan(,""));a=x<58&x>48;b=x>95&x<123;c=x>64&x<91;d=x==48;x[a]=x[a]+9263;x[b]=x[b]+9327;x[c]=x[c]+9333;x[d]=x[d]+9402;intToUtf8(x)

```

**Ungolfed**

```
x=utf8ToInt(scan(,""));
a=x<58&x>48;
b=x>95&x<123;
c=x>64&x<91;
d=x==48;
x[a]=x[a]+9263;
x[b]=x[b]+9327;
x[c]=x[c]+9333;
x[d]=x[d]+9402;
intToUtf8(x)

```

Will add an explanation and try to golf this tomorrow again.

# Answer
> 1 votes
# R, ~~124~~ 91 characters

Takes input from stdin. Probably can be golfed with some cleverness. Saved some bytes by replacing the list of bubble characters with UTF code points.

```
chartr(paste(c(1:9,LETTERS,letters,0),collapse=""),intToUtf8(c(0:8,86:138)+9312),scan(,""))

```

# Answer
> 0 votes
# Groovy (135 Bytes)

```
b=(9312..9320)+(9424..9450)+(9398..9423);r=('0'..'9')+('a'..'z')+('A'..'Z');x={s->s.collect{(x=r.indexOf(it))>=0?(char)b[x]:it}}.join()

```

https://groovyconsole.appspot.com/script/5189010641125376

# Answer
> 0 votes
# Java, 747 bytes

```
String a(String...A){for(int i=1;i<A.length-1;i+=2)A[0]=A[0].replace(A[i],A[i+1]);return A[0];}String b(String B){return a(B,"0","⓪","1","①","2","②","3","③","4","④","5","⑤","6","⑥","7","⑦","8","⑧","9","⑨","a","ⓐ","b","ⓑ","c","ⓒ","d","ⓓ","e","ⓔ","f","ⓕ","g","ⓖ","h","ⓗ","i","ⓘ","j","ⓙ","k","ⓚ","l","ⓛ","m","ⓜ","n","ⓝ","o","ⓞ","p","ⓟ","q","ⓠ","r","ⓡ","s","ⓢ","t","ⓣ","u","ⓤ","v","ⓥ","w","ⓦ","x","ⓧ","y","ⓨ","z","ⓩ","A","Ⓐ","B","Ⓑ","C","Ⓒ","D","Ⓓ","E","Ⓔ","F","Ⓕ","G","Ⓖ","H","Ⓗ","I","Ⓘ","J","Ⓙ","K","Ⓚ","L","Ⓛ","M","Ⓜ","N","Ⓝ","O","Ⓞ","P","Ⓟ","Q","Ⓠ","R","Ⓡ","S","Ⓢ","T","Ⓣ","U","Ⓤ","V","Ⓥ","W","Ⓦ","X","Ⓧ","Y","Ⓨ","Z","Ⓩ");}

```

If the source code may only contain ASCII characters, then replace every non-ASCII character with `\uINSERTRESPECTIVECODEPOINTINHEXADECIMALHERE`. Doing so results in a 933-byte program.

# Answer
> 0 votes
# Python 3, 107.

This borrows part of its algorithm from nedla2004's answer.

```
lambda x:list(map(lambda p:chr(ord(p)+(((9327+6*('@'<p<'[')*p.isalpha(),9402)[p<'1'],9263)['0'<p<':'])),x))

```

# Answer
> 0 votes
# Java 10, ~~152~~ ~~151~~ 142 bytes

```
s->{var r=new StringBuffer();s.chars().forEach(c->r.appendCodePoint(c+(c>47&c<58?c<49?9402:9263:c>64&c<91?9333:c>96&c<123?9327:0)));return r;}

```

-1 byte thanks to *@ceilingcat*.

**Explanation:**

Try it online.

**Explanation:**

```
s->{                        // Method with String parameter and StringBuffer return-type
  var r=new StringBuffer(); //  Resulting StringBuffer
  s.chars().forEach(c->     //  Loop over the chars of the input as integers
    r.appendCodePoint(      //   Convert int to char, and append it to the result:
      c                     //    The current character as integer
      +(c>47&c<58?          //    If it's a digit:
         c<49?              //     If it's 0 (special case)
          9402              //      Add 9402 to convert it
         :                  //     Else (1-9)
          9263              //      Add 9263 to convert it
        :c>64&c<91?         //    Else-if it's an uppercase letter:
         9333               //     Add 9333 to convert it
        :c>96&c<123?        //    Else-if it's a lowercase letter:
         9327               //     Add 9327 to convert it
        :                   //    Else:
         0)));              //     Leave it as is by adding 0
  return r;}                //  Return the resulting StringBuffer

```

# Answer
> 0 votes
# Python 3, 103 bytes

Might save a byte on shuffling added and subtracted numbers

```
lambda i:i.translate({x:x+(9333-6*(x>96)-70*(x<58)+139*(x<49))*chr(x).isalnum()for x in range(48,123)})

```

Try it online!

---
Tags: code-golf, conversion, unicode
---


title: Time-Sensitive Echo

text:
# Question
Title: Time-Sensitive Echo
# Background

The `echo` program is so neat. You can say anything to it, and it repeats your words perfectly, every time! How cool is that! Disappointingly, it repeats the input all at once, regardless of your typing speed, which is not very realistic. We'll have to fix that.

# The Task

Your program shall take its input from STDIN or closest equivalent. It shall read lines from the user one by one, possibly displaying some prompt, until they enter an empty line. After that, it shall print the lines to STDOUT or closest equivalent, in the same order as they were given. The last (empty) line is not printed, and the last printed line doesn't need to have a trailing newline.

Additionally, the program shall preserve the time intervals between each line: if it took the user `x` seconds to enter a line, it shall take `x` seconds for the program to print it. This applies to the first and last lines too; the empty line is not printed, but the program waits anyway before terminating.

# Example

Here's an example session with the program. All actions that don't produce text are described in brackets, and the (optional) prompt is displayed as `>`.

```
[begin program]
> fhtagn[enter; 1.48s passed since starting program]
> yum yum[enter; 3.33s passed since previous enter]
> so cool![enter; 2.24s passed since previous enter]
> [enter; 0.23s passed since previous enter]
[wait 1.48s]fhtagn
[wait 3.33s]yum yum
[wait 2.24s]so cool!
[wait 0.23s, then end program]

```

Without the actions, the session looks like this:

```
> fhtagn
> yum yum
> so cool!
>
fhtagn
yum yum
so cool!

```

# Rules and Scoring

The waiting times should be accurate to within 0.01 seconds (in practice, if the average human can't tell the difference, you're fine). The lowest byte count wins, and standard loopholes are disallowed. If your language has a built-in function for precisely this task, you may not use it.

# Answer
> 16 votes
# CJam, ~~45~~ ~~41~~ ~~39~~ ~~36~~ 34 bytes

```
{eslN1$}g;es](es-fm3/{){_es>}g;o}/

```

This doesn't really make sense in the online interpreter of course, but it works in the Java interpreter.

It doesn't display a prompt.

## Explanation

```
{        e# Do while... (popping the condition from the stack)
  es     e#   Get the current timestamp.
  l      e#   Wait for a line to be entered and read it.
  N      e#   Push a linefeed.
  1$     e#   Copy the line we read - this terminates if the line is empty, because
         e#   empty strings/arrays are falsy.
}g
;        e# Discard the last linefeed (the one after the empty input).
es       e# Push the current timestamp (corresponding to the last, empty, input).
]        e# Wrap everything in an array. This is now a flat array containing:
         e#   - The initial timestamp.
         e#   - Three elements for each line: the line, a linefeed, the timestamp.
         e#   - Two elements for the last line: the empty string and the timestamp.
(        e# Pull off the initial time.
es-      e# Subtract the current time, which gives (minus) the difference between
         e# when a line was entered and when it should be printed back.
fm       e# This maps "minus that value" onto each element in the array. Now the lines
         e# and linefeeds are strings (arrays) - so minus is set difference, but they
         e# only contain characters, not any integers (like the difference value), so
         e# none of the strings will be affected.
         e# The timestamps on the other hand will be incremented by the time difference
         e# between reading and printing, giving the time at which each line should be
         e# printed back.
3/       e# Split the array into chunks of 3 (where the remaining two elements are
         e# just grouped as a pair).
{        e# For each of those chunks...
  )      e#   Pull off the timestamp.
  {      e#   Do while... (popping the condition from the stack)
    _    e#     Duplicate the target time.
    es>  e#     Check if it's still greater than the current time.
  }g
  ;o     e# Discard the target time and print the rest of the current chunk, which will
         e# automatically be flattened/concatenated into a single string.
}/

```

# Answer
> 9 votes
# JavaScript, ~~119~~ 112 bytes

```
k=(d=Date.now)(i=j=[]);do{i[++j]=[prompt(),d()-k]}while(i[j][0]);i.map(a=>setTimeout(b=>console.log(a[0]),a[1]))

```

Hoping to find a couple more bytes to cut out.

# Answer
> 6 votes
## JavaScript, 120 bytes

No chance of getting near to CJam with this approach, but a straightforward script.

```
a=[];t=+new Date;while(s=prompt()){a.push({s:s,t:+new Date})}while(v=a.pop()){setTimeout(`console.log('${v.s}')`,v.t-t)}

```

# Answer
> 6 votes
# Ruby, 74

```
t,*a=Time.now
a<<[$_,t-t=Time.now]while$/<gets
a.map{|l,i|sleep -i;puts l}

```

Tricks: `*a` on the first line initalizes an empty array. I could use `$*` instead but it's mildly sketchy since it's populated with some invocations and only saves me a byte. `$/` is a newline, and `$_` is the last line retrieved by `gets`.

Edit: Sleeping at the end costs 20 more bytes, probably a way to golf it down

```
t,*a=Time.now
a<<[$_,t-t=Time.now]while$/<gets
t-=Time.now
a.map{|l,i|sleep -i;puts l}
sleep -t

```

# Answer
> 6 votes
# Pyth, 68 bytes

```
M&p+Gb$__import__('time').sleep(H)$J].dZWeaYwaJ.dZ)aJ.dZp&gVPY-VtJJk

```

Wasted a *lot* of bytes on the call to `sleep`, since Pyth has no `sleep` function.

# Answer
> 5 votes
# SWI-Prolog, 185 bytes

```
a:-b([],S),reverse(S,T),c(T),!.
b(R,S):-get_time(X),read_string(user_input,"\n","",_,A),get_time(Y),Z is Y-X,(A="",S=[A:Z|R];b([A:Z|R],S)).
c([A:Z|T]):-sleep(Z),T=[];(write(A),nl,c(T)).

```

There is probably a lot to golf here but this will do for now...

# Answer
> 5 votes
# Python 3, 124

Only works on Windows platforms

```
from time import*
s=[(1,clock())]
while s[-1][0]:s+=[(input(),clock()-s[-1][1])]
[sleep(y)or x and print(x)for x,y in s[1:]]

```

Keeping the input and times in separate lists cost me 3 more bytes. Probably not the best approach.

An 129 byte Unix friendly version, with credit to Mego:

```
from time import*
t=time
s=[(1,t())]
while s[-1][0]:s+=[(input(),t(),t()-s[-1][1])]
[sleep(y)or x and print(x)for x,z,y in s[1:]]

```

# Answer
> 4 votes
# PowerShell, ~~261~~ ~~190~~ ~~121~~ 95 Bytes

```
$(do{Measure-Command{$l=read-host};$l}while($l))|%{($_,(sleep -m($_.Ticks/1e4)))[($b=!$b+!$_)]}

```

Props to TessellatngHeckler and tomkandy for the golfing assistance and inspiration

This is very similar in concept to the 121-byte version below, we're just dynamically creating and building a list of objects, instead of going through a while loop to store them into an explicit array `$a`. In both cases, that list of objects gets pipelined into the same foreach loop `|%{...}`. The indexing into the result-array-selector `($b=!$b+!$_)` is this time formulated to eliminate the `if($_){$_}` of the below iterations, which saves a few more bytes.

---

### Previous, 121 Bytes

```
$l,$a=1,@();while($l){$t=Measure-Command{$l=read-host};$a+=$t,$l}$a|%{($(if($_){$_}),(sleep -m($_.Ticks/1e4)))[($b=!$b)]}

```

Expanded and explained:

```
$l,$a=1,@()                        # Set variable $l and create array $a
while($l){                         # So long as we don't have a blank line
  $t=Measure-Command{$l=read-host} # Read the input and measure time to input
  $a+=$t,$l                        # Add those values into the array
}
$a|%{                              # For each item in $a, do
  ($(if($_){$_}),(sleep -m($_.Ticks/1e4)))[($b=!$b)]
  # Magic happens here ... first, we set $b to the NOT of it's uninitialized
  # value, so $b is initially set to truthy
  # This value in [...] selects which of the two elements ( , ) get selected
  # Truthy to start means the second command, sleep, gets chosen first, and
  # then it alternates every next item, so it sleeps, then prints, then
  # sleeps, then prints, etc., until we run out of $a
}

```

---

### Previous-er, 190 Bytes

```
function f {param($m)sleep -m $a[$m].totalmilliseconds}$a=1,1;while($a[-1]-ne""){$a+=Measure-Command{$b=read-host};$a+=$b}if(!($a[3])){f 2;exit}$i=2;while($i-lt$a.length){f($i++);$a[($i++)]}

function f {                        # Define a new function
  param($m)                         # with $m as input
  sleep -m $a[$m].totalmilliseconds # sleep for $a[$m] milliseconds
}
$a=1,1                              # Create new array with two elements
while($a[-1]-ne""){                 # While the last element isn't empty
  $a+=Measure-Command{$b=read-host} # Read into $b and measure how long that took,
                                    # and add the time into $a
  $a+=$b                            # Then add the input into $a
}
if(!($a[3])){                       # If the third element is empty, the user entered
                                    # a blank as the only input, so...
  f 2                               # sleep for $a[2] ms (how long it took them to hit enter)...
  exit                              # and exit the script
}                                   # Else ...
$i=2                                # Set a counter variable
while($i-lt$a.length){              # While we haven't reached the end of $a
  f($i++)                           # Sleep
  $a[($i++)]                        # Write the output
}

```

---

### Previous-er-er, 261 Bytes

```
$a=$d=@();$d+=,@(date);$x=Read-Host
while($x){$a+=,@($x);$d+=,@(date);$x=Read-Host}
if($x){0..($a.Length-1)|%{sleep -m((($d[$_+1]).ticks-($d[$_]).ticks)/1e4);$a[$_]};sleep -m((($d[-1]).ticks-($d[-2]).ticks)/1e4)}
else{sleep -m(((date).Ticks-($d[0]).Ticks)/1e4)}

```

Holy verbosity, Batman! Let's break it down:

```
$a=$d=@()                  # Create two empty arrays
$d+=,@(date)               # Add the current time into $d
$x=Read-Host               # Read the first line
while($x){                 # So long as it's not empty
  $a+=,@($x)               # Add it into our output array
  $d+=,@(date)             # Add the current time into $d
  $x=Read-Host             # Get the next line
}
if($a){                    # So long as $a exists (i.e., the first input wasn't blank)
  0..($a.Length-1)|%{      # For-loop over the length
                           # Sleep for how long it took to do input
    sleep -m((($d[$_+1]).ticks-($d[$_]).ticks)/1e4)
    $a[$_]                 # Print out the input
  }
                           # Sleep the length it took for the final blank
  sleep -m((($d[-1]).ticks-($d[-2]).ticks)/1e4)
}
else{
                           # If we're here, the initial input was blank, so just sleep
  sleep -m(((date).Ticks-($d[0]).Ticks)/1e4)
}

```

# Answer
> 3 votes
## Perl 6, 70 characters

```
repeat {$/=now;.push($!=get,now -$/)}while $!;.map:{sleep $^b;say $^a}

```

Perl 6 interpreter only defines three symbolic variables (unlike the craziness of Perl 5). To be exact, `$/`, `$!`, and `$_`. This program uses them all, to avoid the cost of declaring variables using `my`.

`get` reads a line from STDIN. It doesn't contain a newline, unlike Perl 5.

`now` builtin returns a current time. When subtracted, it gives an interval that can be passed to a string.

A method with nothing on the left of it (like `.push` and `.map` in this code) works on `$_`.

Using `repeat while` loop (known as `do while` in other programming languages), Perl 6 is writing current timestamp to `$/`, and pushes the received line (which it also stores to `$!`), and difference between current time and timestamp in `$/`. Because of parameter order, `now` is not calculated until a line is received.

The `while` condition checks if the line is not empty (in Perl 6, `"0"` is a true value, unlike Perl 5).

After I get all timestamps and lines, I just provide those to `map` callback which sleeps a bit and says what was said.

# Answer
> 2 votes
# MATLAB, ~~107~~ 99

```
tic;a={};i=1;while nnz(i);i=input('','s');a=[a;{i,toc}];tic;end;for b=a';pause(b{2});disp(b{1});end

```

And ungolfed:

```
tic; %Start timer
a={};
i=1; %Make us enter the while loop
while nnz(i); %While i has some non-zero elements (this is used to detect a zero length input where we end)
    i=input('','s'); %Get an input string
    a=[a;{i,toc}]; %Append the string and current time as a new cell in a
    tic; %Restart timer
end
for b=a' %For each input
    pause(b{2}); %Wait for the required time
    disp(b{1}); %Then print the string
end

```

This won't be 100% accurate in timing as it doesn't account for the time taken to display each string but that should be pretty quick so timing-wise it should be pretty close.

---

After a quick revisit, I've saved a few bytes by removing the double layer deep cell array. Turns out all I needed was a `;` to get it to split up correctly when packing.

# Answer
> 2 votes
# Groovy, 202 bytes

```
def b={System.currentTimeMillis()};def h=[];for(;;){def t=b();def s=System.console().readLine();h.add(s+" "+(b()-t));if(s=="")break};for(def s:h){Thread.sleep((s=s.split(" "))[1].toLong());println s[0]}

```

Radical.

Ungolfed version:

```
def b = {System.currentTimeMillis()}; // Creates a closure (short function) b that returns the current time since the epoch in milliseconds.
def h = []; // Makes an empty list
for(;;) { // Infinite loop
  def t = b(); // Get the time
  def s = System.console().readLine(); // Read a line
  h.add(s + " " + b()-t); // Add the string plus the amount of time elapsed to the list
  if(s=="") // If the string is blank
    break; // Exit loop
}
for(def s : h) { // Iterate through array
  Thread.sleep((s=s.split(" "))[1].toLong()); // Splits s into an array and puts the value in s, then takes the second element (the time), converts into a long and sleeps for that time.
  println s[0] // Print the first element (text)
}

```

# Answer
> 2 votes
# JavaScript (ES6) 102

Putting together the efforts of Mwr247 and Dom Hastings (CW)

```
/* for TEST */ console.log=x=>O.innerHTML+=x+'\n'

for(k=new Date,i=[];p=prompt();i.push([p,new Date]));i.map(a=>setTimeout(b=>console.log(a[0]),a[1]-k))
```

```
<pre id=O></pre>
```

# Answer
> 1 votes
# Java, using version 1.04 of this library, 385 bytes

```
import sj224.lib.util.*;import java.util.*;class E{static long t(){return System.currentTimeMillis();}public static void main(String[]a) throws Exception{List<Pair<?,Long>>l=new ArrayList();Scanner i=new Scanner(System.in);while(true){long t=t();String s=i.nextLine();if(s.isEmpty())break;l.add(new Pair(s,t()-t));}for(Pair<?,Long>p:l){Thread.sleep(p.two);System.out.println(p.one);}}}

```

# Answer
> 1 votes
# Caché ObjectScript, 123 bytes

```
w() q $P($ZTS,",",2)
r f  s i=i+1,t=$$w() r x,! q:x=""  s g(i,x)=$$w()-t
    f i=1:1 s s=$O(g(i,"")) q:s=""  w s,! h g(i,s)
    q

```

As usual, this assumes a clean symbol table before running `d r`.

This problem cannot be solved in ANSI MUMPS, since the ANSI standard only requires second-level resolution for the time intrinsic `$H[OROLOG]`. Luckily, Intersystems Caché, which is currently the industry-leading platform for MUMPS, provides the implementation-defined `$ZT[IME]S[TAMP]` intrinsic, which provides microsecond-level resolution.

(Score was formerly 105 bytes, but there was a bug.)

# Answer
> 1 votes
**VBA , ~~233~~ 228bytes**

I'm Sure this can be golfed a lot. they didn't specify how many inputs so i hard coded my array lengths because its shorter then `Redim preserve`.

Input is via popup, output is `debug.print` because `msgbox` produces a MODAL and halts code.

I don't know how to test if this is accurate to the 0.01s. Maybe someone can test but I am giving the wait command the number in a way that it SHOULD use the milliseconds, But VBA isn't known for doing what it should.

The `If goto` may be able to be substituted by a well golfed `Do Loop While`.

```
Sub a()
Dim k(99) As String
Dim h(99) As Date
b:
t=Now()
i=i+1
k(i)=InputBox("")
h(i)=Now()-t
If k(i)<>"" Then GoTo b
For u=1 To i
Application.Wait (Now()+(Format(h(u),"s")&Format(h(u),"ms"))/10^8)
Debug.Print k(u)
Next
End Sub

```

> Will not work in Access VBA, because access doesn't have a wait command ***because Microsoft hates consistency***

# Answer
> 1 votes
# Bash, ~~91~~ 90 bytes

```
while r=`\time -fsleep\ %e head -1`
[[ $r ]]
do printf{,\ %%b\ %q\;} "$r
"
done>t 2>&1
. t

```

This creates a temporary file `t`. **It will overwrite an existing file with the same name.**

The idea itself is pretty short, but dealing with special characters in the input adds around 15 bytes...

# Answer
> 1 votes
# Bash, 22 bytes

```
nc -l 3|nc localhost 3

```

Then type in the input and press enter.

# Answer
> 0 votes
# C++ 11, ~~343~~ 338 bytes

Wanted to see how many bytes a code for that in c++ would need. A lot more than I expected. Maybe I over complicated the solution.

```
#include<iostream>
#include<vector>
#include<chrono>
int i;using namespace std;int main(){auto n=chrono::system_clock::now;auto t=n();string s{1};vector<string>r;vector<decltype(t-t)>w;while(s.size())getline(cin,s),r.push_back(s),w.push_back(n()-t),t=n();while(i<r.size()){while((n()-t)<w[i]);t=n();cout<<r[i++]<<(i<r.size()-1?"\n":0);}}

```

Lets see if I can reduce this somehow.

# Answer
> 0 votes
# SmileBASIC, 122 bytes

```
DIM A$[0],T[0]@L
C=MAINCNT
LINPUT S$PUSH A$,S$PUSH T,MAINCNT-C
IF""<S$GOTO@L@P
WAIT SHIFT(T)IF""<A$[0]THEN?SHIFT(A$)GOTO@P

```

I think this could be made slightly shorter.

# Answer
> 0 votes
# C UNIX, 272 bytes

```
#include <stdio.h>
#include <unistd.h>
#define P printf
i;r;c;main(){char*L[99]={0};size_t s;long T[99]={0};while(1){P(">  ");T[c]=time(0);r=getline(&L[c],&s,stdin);T[c]=time(0)-T[c];if(r==-1|!(*L[c]-10))break;c++;}while(i<c){P("> ");usleep(T[i]*1000);P("%s", L[i]);i++;}}

```

**Detailed**

```
#include <stdio.h>
#include <unistd.h>

int main(void)
{
    int i = 0, c = 0, r;
    char * L[99] = {0};
    size_t size;
    long T[99] = {0L};

    while(1)
    {
        printf("> ");
        T[c] = time(0);
        r = getline(&L[c], &size, stdin);
        T[c] = time(0) - T[c];
        if(r == (-1)) break;
        if(*L[c]=='\0' || *L[c]=='\n') break;
        c = c + 1;
    }

    while(i < c)
    {
        printf(" %ld > ",T[i]);
        usleep(T[i]*1000);
        printf("%s", L[i]);
        i = i + 1;
    }

    return 0;
}

```

---
Tags: code-golf
---