Programming Comparisons: Mastermind


Problem: give the smallest possible complete program that, when run, plays a game of Mastermind in the following way: it accepts any number of guesses on standard input in the form of 4 digits followed by a newline. The digits must be between 1 and 6. If your guess is incorrect, it will print 0 or more *s, signifying the number of digits that are correct and in the proper position, followed immediately by 0 or more +s, indicating the number of digits which are correct but in the wrong position, followed by a newline. If all digits are correct, the program prints "Tries: n\n" where n is the number of tries, then exits. All output is done to standard output.

perl: 164
$i=join'',@i=map{1+0|rand 6}1..4;while(<>){chop;$s=$_;split//;$a=grep{$_[$_]==$i[$_]}0..3;$a>3&&last;print'*'x$a,'+'x((grep{$s=~s/$_//}@i)-$a),"
"}print"Tries: $.
"
view raw mastermind.pl hosted with ❤ by GitHub

ruby: 243
j=0..3;x=j.map{(6*rand).ceil};t=0;while gets
g=$_.chomp.split('').map{|c|c.to_i};t+=1;if
g==x;puts "Tries: #{t}";exit;end;y=x.clone
puts (j.map{|i|x[i]==g[i]?g[i]=y[i]=0:2}+g.uniq.map{|i|i>0&&y.member?(i)?1:2}).map{|i|['*','+',''][i]}.join
end
view raw mastermind.rb hosted with ❤ by GitHub

haskell: 269
module Main where
import Random
import List
p=putStrLn
f(x,y)=x\\(x\\y)
e z=['*'|(p,q)<-z,p==q]++(f(unzip[x|x@(p,q)<-z,p/=q])>>"+")
n a s=getLine>>=m where{m i|i==s=return a;m i=p(e$zip i s)>>n(a+1)s}
main=mapM(\x->randomRIO('1','6'))"mind">>=n 1>>=p.("Tries: "++).show
view raw mastermind.hs hosted with ❤ by GitHub