Word guessing game

6

2

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"?

Thomas O

Posted 2011-02-07T01:18:10.393

Reputation: 3 044

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.

– PleaseStand – 2011-02-07T01:38:17.007

To remove bias due to path lengths, can we assume that the word list is in a file named 'w' in the working directory? – Peter Taylor – 2011-02-07T13:11:36.160

@peter That would be fine, but make it clear. – Thomas O – 2011-02-07T13:31:56.197

Answers

3

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)"

Nathan Osman

Posted 2011-02-07T01:18:10.393

Reputation: 596

That cat /dev/stdin | looks very no-op to me. Are you sure you need it? – J B – 2011-02-07T10:13:50.707

Similarly, the cat /usr/share/dict/words | could probably just turn into an input redirection </usr/share/dict/words – J B – 2011-02-07T10:15:05.060

@JB: This was my first entry, so there's probably room for improvement. – Nathan Osman – 2011-02-07T17:03:01.723

2

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.

ninjalj

Posted 2011-02-07T01:18:10.393

Reputation: 3 018

0

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";}

l0n3sh4rk

Posted 2011-02-07T01:18:10.393

Reputation: 1 387