6
\$\begingroup\$

A program should take an input on stdin, and guess what a word might be. It should run as a session. One example session is shown below. Characters are fed to it, with a * for a letter not revealed; it should remember letters already revealed. It shows possible words in a list if the total number words found is less than 20, otherwise it shows the count of words.

I recommend /usr/share/dict/words on any Linux/Unix for the list of words, or your favourite word list on other platforms.

Example session (yours may vary):

>>> *****
6697 matches
>>> G****
312 matches
>>> *u***
Trying Gu***
35 matches
>>> Gu**s
Gus's
Guy's
guess
gulfs
gulls
gulps
gum's
gun's
gurus
gusts
gut's
guy's
12 matches
>>> **e**
Trying Gue*s
Is it "guess"?
\$\endgroup\$
3
  • \$\begingroup\$ I did this some years ago in JavaScript, except that it was not golfed and was a real Hangman player following the usual rules, including guessing only one letter at a time. \$\endgroup\$ Feb 7, 2011 at 1:38
  • \$\begingroup\$ To remove bias due to path lengths, can we assume that the word list is in a file named 'w' in the working directory? \$\endgroup\$ Feb 7, 2011 at 13:11
  • \$\begingroup\$ @peter That would be fine, but make it clear. \$\endgroup\$
    – Thomas O
    Feb 7, 2011 at 13:31

3 Answers 3

3
\$\begingroup\$

Bash (171)

#!/bin/bash
s=`cat /dev/stdin | sed 's/\*/\./g'`;o=`cat /usr/share/dict/words | grep -x $s`;w=`echo "$o" | wc -l`;if [ $w -lt '20' ]; then echo "$o";fi;echo "$w match(es)"
\$\endgroup\$
3
  • \$\begingroup\$ That cat /dev/stdin | looks very no-op to me. Are you sure you need it? \$\endgroup\$
    – J B
    Feb 7, 2011 at 10:13
  • \$\begingroup\$ Similarly, the cat /usr/share/dict/words | could probably just turn into an input redirection </usr/share/dict/words \$\endgroup\$
    – J B
    Feb 7, 2011 at 10:15
  • \$\begingroup\$ @JB: This was my first entry, so there's probably room for improvement. \$\endgroup\$ Feb 7, 2011 at 17:03
2
\$\begingroup\$

Perl, 170 chars

open W,'</usr/share/dict/words';@D=<W>;
while(<>){@W=split//,$w;$w&&s/\*/$W[$-[0]]/ge;y/*/./;$w=$_;
($r=@R=grep/^$w$/i,@D)<20&&map{print}@R;print$r." matches\n";$r<2&&last}

Added (not counted) newlines for clarity.

\$\endgroup\$
0
\$\begingroup\$

PHP, 302

<?system('stty -icanon');$i=0;$s=explode(PHP_EOL,file_get_contents('/usr/share/dict/words'));while(1){$q.=fread(STDIN,1);system('clear');$x=0;$a='';$i++;for($j=0;$j<count($s);$j++){if(!strncasecmp($q,$s[$j],$i)){$x++;$a.="\n$s[$j]";}}echo str_pad($q,20,'*');echo$x<=20?"\n$a":'';echo"\n$x matches\n";}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.