Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

★【Challenge!】【Easy】 Hangman Solver

Name: !WIZardrY9E!UhEWzHM7+1tYUG2 2012-05-14 13:16

⚫ The Game of Hangman

A player guesses letters that are part of a word!
If he has not guessed the complete word before making six (6) mistakes, he has lost!

      _______
     |/      |
     |      (_)
     |      \|/   It is a game over!
     |       |
     |      / \
     |
  ___|___


⚫ Your Challenge

In a language of your choice, write a program that takes as its input (in some way) the target word (with blanks) and the letters that have been guessed already. It should then output the next letter to be guessed.
For example:

$ echo -n "p...s\npds" | ./guesser
e

You may assume the word to be guessed is an English word and contains only lowercase ASCII letters.
Provide code and instructions if usage is not obvious. Consider using a tripcode to ease conversation about your entry.

Entries will be judged on GOODITUDE (defined as its win/loss ratio over twenty random games), on SPEED, and on CLEVERNESS.

Your deadline is 23:59:59 on Sunday, May 20th. Results will be posted the following day.

 |∧_∧
 |´・ω・) < Good luck!♫
 ||と ノ

Name: Anonymous 2012-05-14 14:31

Define "an English word".

Name: Anonymous 2012-05-14 14:33

Also this sort of information is best given as two separate entries on the command line.

Name: Anonymous 2012-05-14 14:55

Algorithm:
1. Let I be the (random)th open space in input word
2. Read from file/data provider of 66common99 English words and insert them into a hash map where the hash is the I'th letter of the word
3. Let L be the set of all letters except the ones specified by program argument
4. For every element l in L count the successful matches of every word in entry l of hash map and let the higher count value specify the output letter
5. Return l for higher count value of matches with 66common99 English words

Now implement in C and optimize the matcher function in asm to win challenge

Name: sage 2012-05-14 15:00

>>1
I ain't doing nobody's homework.

>>4
?

Name: Anonymous 2012-05-14 15:17

>>4
Since the program will be invoked once per letter, that's going to be pretty damn slow.

Name: Anonymous 2012-05-14 15:30

>>6
Then drop that requirement

Name: Anonymous 2012-05-14 15:48


from string import *
import random
from hangman_lib import *

secret_word=get_random_word()

congrats=['Magnificient','Stupendous','That was EXPERT Quality','Marveloso','Fantabulous']
snide=['Don\'t worry 2/10 people fail to beat hangman','It\'s a hard game. It\'s not as \
though you have a list of letters you could guess with.','If that was you ,who just got hung,\
you\'d be a hung man. As in asphixiated']

letters_guessed=[]

mistakes_made=0

MAX_GUESSES=8


def randomnum(x):
    return random.randint(1,len(x)-1)

valid='abcdefghijklmnopqrstuvwxyzcheat'


def word_guessed():
    my=[]
    for i in secret_word:
        if i in letters_guessed: my.append(True)
        else: my.append(False)
    return all(my)

   
def print_guessed():
    m=[]
    for i in secret_word:
        if i in letters_guessed:
            m.append(i)
        else: m.append('-')
    print join(m,' ')

##def main():
   
while True:
    print 'You have %d guesses left' % (MAX_GUESSES-mistakes_made)
    print_guessed()
    print letters_guessed
    guess_letter=lower(raw_input('Guess a letter\n'))
    if guess_letter=='cheat':
            print secret_word
    while guess_letter in letters_guessed or guess_letter not in valid:
        guess_letter=lower(raw_input('Letter already picked or invalid input.\
Pick something else.\n'))
       
    letters_guessed.append(guess_letter)
    if guess_letter not in secret_word:
        mistakes_made+=1
        print_hangman_image(mistakes_made)   
    if mistakes_made>=MAX_GUESSES:
        print 'Game over.\n'
        print 'The word was %s' %(secret_word)
        print '%s' %(snide[randomnum(snide)])
        break
    if  word_guessed():
        print '%s ! You did it!\n' %(congrats[randomnum(congrats)])
        print secret_word
        break

print '\nArt created by sk'


Hangman Lib:



def print_hangman_image(mistakes = 6):
  """Prints out a gallows image for hangman. The image printed depends on
the number of mistakes (0-6)."""
 
  if mistakes <= 0:
    print''' ____________________
| .__________________|
| | / /    
| |/ / 
| | /    
| |/  
| |    
| |  
| |   
| |    
| |   
| |  
| |  
| |   
| |     
| |     
| |      
| |     
""""""""""""""""""""""""|
|"|"""""""""""""""""""|"|
| |                   | |
: :                   : :
. .                   . .'''

  elif mistakes == 1:
    print''' ___________.._______
| .__________))______|
| | / /      ||
| |/ /       ||
| | /        ||.-''.
| |/         |/  _  \\
| |          ||  `/,|
| |          (\\\\`_.'
| |       
| |    
| |   
| |  
| |  
| |   
| |     
| |     
| |      
| |     
""""""""""""""""""""""""|
|"|"""""""""""""""""""|"|
| |                   | |
: :                   : :
. .                   . .'''
  elif mistakes == 2:
    print''' ___________.._______
| .__________))______|
| | / /      ||
| |/ /       ||
| | /        ||.-''.
| |/         |/  _  \\
| |          ||  `/,|
| |          (\\\\`_.'
| |          -`--'
| |          |. .| 
| |          |   |  
| |          | . |   
| |          |   |    
| |          || ||
| |     
| |     
| |      
| |     
""""""""""""""""""""""""|
|"|"""""""""""""""""""|"|
| |                   | |
: :                   : :
. .                   . .'''
  elif mistakes == 3:
    print''' ___________.._______
| .__________))______|
| | / /      ||
| |/ /       ||
| | /        ||.-''.
| |/         |/  _  \\
| |          ||  `/,|
| |          (\\\\`_.'
| |         .-`--'
| |        /Y . .|
| |       // |   | 
| |      //  | . |  
| |     ')   |   |    
| |          || ||
| |     
| |     
| |      
| |     
""""""""""""""""""""""""|
|"|"""""""""""""""""""|"|
| |                   | |
: :                   : :
. .                   . .'''
  elif mistakes == 4:
    print''' ___________.._______
| .__________))______|
| | / /      ||
| |/ /       ||
| | /        ||.-''.
| |/         |/  _  \\
| |          ||  `/,|
| |          (\\\\`_.'
| |         .-`--'.
| |        /Y . . Y\\
| |       // |   | \\\\
| |      //  | . |  \\\\
| |     ')   |   |   (`
| |          || ||
| |     
| |     
| |      
| |     
""""""""""""""""""""""""|
|"|"""""""""""""""""""|"|
| |                   | |
: :                   : :
. .                   . .'''
  elif mistakes == 5:
    print''' ___________.._______
| .__________))______|
| | / /      ||
| |/ /       ||
| | /        ||.-''.
| |/         |/  _  \\
| |          ||  `/,|
| |          (\\\\`_.'
| |         .-`--'.
| |        /Y . . Y\\
| |       // |   | \\\\
| |      //  | . |  \\\\
| |     ')   |   |   (`
| |          ||'||
| |          ||  
| |          ||  
| |          ||  
| |         / | 
""""""""""""""""""""""""|
|"|"""""""""""""""""""|"|
| |                   | |
: :                   : :
. .                   . .'''
  else: #mistakes >= 6
    print''' ___________.._______
| .__________))______|
| | / /      ||
| |/ /       ||
| | /        ||.-''.
| |/         |/  _  \\
| |          ||  `/,|
| |          (\\\\`_.'
| |         .-`--'.
| |        /Y . . Y\\
| |       // |   | \\\\
| |      //  | . |  \\\\
| |     ')   |   |   (`
| |          ||'||
| |          || ||
| |          || ||
| |          || ||
| |         / | | \\
""""""""""|_`-' `-' |"""|
|"|"""""""\ \       '"|"|
| |        \ \        | |
: :         \ \       : :
. .          `'       . .'''

import random
def get_random_word():
  """Returns a random word from the file word_list.txt in the same directory"""
  input_file = open('word_list.txt','r')
  word_list = [word.strip().lower() for word in input_file.readlines() if word.strip().isalpha() and len(word) > 4]
  input_file.close()
 
  return word_list[random.randint(0,len(word_list)-1)]


Words list:

Name: Anonymous 2012-05-14 15:48

Name: Anonymous 2012-05-14 16:11

>>4
C is fucking shit.

Name: Anonymous 2012-05-14 16:39

>>10

0/10, cancer

Name: Anonymous 2012-05-14 16:46

>>11
-inf, faggotry. C is undefined shit; x86 assembly is KING!

Name: Anonymous 2012-05-14 16:50

>>12

0/10, cancer

Name: Anonymous 2012-05-14 16:54

>>13
fuck off and die you cock sucking faggot

Name: Anonymous 2012-05-14 16:57

>>14
0/10, cancer

Name: Anonymous 2012-05-14 17:03

>>15
fuck off and die you cock sucking faggot

Name: Anonymous 2012-05-14 17:30

>>15
0/10, cancer

Name: Anonymous 2012-05-14 17:31

>>17
FUCK OFF AND DIE IN A FUCKING FIRE YOU FUCKING COCK SUCKING FAGGOT

Name: Anonymous 2012-05-14 17:32

>>18
0/10, cancer

Name: Anonymous 2012-05-14 17:54

>>8-9
Did you post this so we could test our entries, or because you didn't read >>1 properly?

>>10-19
SPAWHBTC. The first honest challenge thread in like a year and this is how you behave?

Name: Anonymous 2012-05-14 17:54

>>20
Fuck you cock sucking faggot

Name: Anonymous 2012-05-14 18:01

>>21
0/10, cancer

Name: Anonymous 2012-05-14 18:08

>>22
nice doubles

Name: Anonymous 2012-05-14 19:49

Here's a Ruby solution:

WORDLIST = 'words.txt' # Make this something else.
hints, guesses = $*
regex = /^#{hints.gsub('.', '(.)')}$/

letters = Hash.new(0)
open(WORDLIST).each_line do |w|
  w.chomp.match(regex) do |m|
    m.captures.each do |c|
      letters[c] += 1
    end
  end
end

letters = letters.sort_by { |k, v| v }
letters.reject! { |k, v| guesses.include? k }
puts "Guessing: #{letters[-1][0]}."


Usage:

$ ruby hangman.rb p.ncre.s epsrcn
Guessing: a.
$ ruby hangman.rb kangar.. argnk
Guessing: o.


It's not optimzed for anything at all, but it is short.

Name: Anonymous 2012-05-14 22:53


#!/usr/bin/python

from hangmanlib import hangman

hangman()


hangmanlib implementation is left as an exercise to the ``reader".

Name: Anonymous 2012-05-15 8:40

>>25
rofl 10/10 bud I came onto my pizza

Name: Anonymous 2012-05-15 10:22

>>26
xD

Name: Anonymous 2012-05-15 12:53

Bampu pantsu.

Name: Anonymous 2012-05-15 13:01

Business solutions.

Name: Anonymous 2012-05-15 14:54

module Main where

import Data.List (sortBy)
import Data.List.Split (wordsBy)
import Data.Char (isSpace)
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.Text.Read as T
import qualified Data.Text.IO as T

type PList = [(Char, Double)]
type LUT = M.Map String PList

sortPList :: PList -> PList
sortPList = sortBy (\x y -> snd y `compare` snd x)

filterPList :: String -> PList -> PList
filterPList s l = filter (\(x, y) -> not $ x `elem` s) l

splitFreqs :: Int -> [[a]] -> ([a], [[a]])
splitFreqs _ [] = ([], [])
splitFreqs l (x:xs)
    | length x == l+1 = (p, x:pp)
    | length x == l = if null p then (x, pp) else next
    | otherwise = next
    where next@(p, pp) = splitFreqs l xs

mkPMap :: [T.Text] -> (String, [Double])
mkPMap (x:xs) = (T.unpack x, case dbls of
                                 Just d -> d
                                 _ -> [])
    where dbls = mapM toDbl xs
          toDbl :: T.Text -> Maybe Double
          toDbl t = case T.double t of
                        Right (d, t') -> if T.null t' then Just d else Nothing
                        _ -> Nothing

mkFreqLookup :: T.Text -> (PList, LUT, Int)
mkFreqLookup bs = (p', pp'', maximum $ map (length . fst) pp')
    where nonnull = filter (not . T.null) $ T.lines bs
          ll = filter (\x -> T.head x /= '#') nonnull
          key' = filter (not . isSpace) $ T.unpack (head ll)
          key = map (\x -> if x == 'S' then ' ' else x) key'
          (p, pp) = splitFreqs (length key) (map T.words $ tail ll)
          p' = sortPList $ zip key (snd $ mkPMap (T.empty : p))
          pp' = map (\(x, y) -> (x, zip key y)) $ map mkPMap pp
          pp'' = M.fromList pp'

words' :: String -> [String]
words' s = if last s == '.' then w else init w
    where w = wordsBy (== '.') s

findWordProbs :: Int -> LUT -> String -> PList
findWordProbs 0 _ _ = []
findWordProbs m lut s = case f of
                            Just i -> i
                            _ -> findWordProbs (l-1) lut s
    where l = min (length s) m
          f = M.lookup (reverse $ take l $ reverse s) lut

main = do
    fc <- T.readFile "freqlist"
    w <- getLine
    used <- getLine

    let (guess, lut, match) = mkFreqLookup fc
        w' = words' w
        plists = concatMap (findWordProbs match lut) w'
        probs = sortPList $ filterPList used plists
        next = if null probs
                   then fst $ head $ filterPList used guess
                   else fst $ head probs

    putStrLn [next]


freqlist: http://pastebin.com/wFzSJxen

Quick and dirty. Uses frequency analysis to determine the next best guess

Name: Anonymous 2012-05-15 15:21

I agree with >>7 , you should just run the program once and give it words through stdin.

Name: Anonymous 2012-05-15 16:58

>>31
std in my anus

Name: Anonymous 2012-05-15 17:03

>>31
It's almost as if considering trade-offs between reading an entire dictionary every time and using one-size-fits-all frequency tables is part of the challenge.

Name: Anonymous 2012-05-15 17:24

i like that vip cat thing. what is it called

Name: Anonymous 2012-05-15 17:33

IT'S CALLED "PLUG AND PLAY DETECTED AN ERROR FAULT EXPCSEXTION! WONT LET U INSTAL WINBLOWS UNLESS U UNPLUG UR EXTERNAL HDD!!!"

PLUG AND PLAY MY ANUS LOL!

Name: Anonymous 2012-05-15 17:40

>>35
oh and i am the proud ofner of a external hdd that makes windows BSOD instantly when I plug it in an USB port, (YES even when autoplay/autorun disabled)

isn't that awesome? Y/N

Name: Anonymous 2012-05-15 20:55

import sys
import random
#two arguments needed
if(len(sys.argv) != 2):
    print "Usage: n"
    print "n - word to finish guessing"
else:
    #get the guess
    guess = sys.argv[1]
    #to match the word
    def match(word):
        #get rid of extra whitespace!
        word = word.strip()
        #if the guess and the word have equal length
        if(len(word) == len(guess)):
            #for every character in both the guess and the word
            for i in range(len(guess)):
                #if the guess was made and the guess was incorrect
                if(guess[i] != '.' and guess[i] != word[i]):
                    #no match
                    return False
            #all guesses ok or not made - matches
            return True
        else:
            #no length match - no match
            return False
    #get all matching words from the word list
    l = filter(match, open("words.txt", "r"))
    #if we have matching words
    if(len(l) != 0):
        #get a list of all the un-made guess characters
        a = []
        for i in range(len(guess)):
            if(guess[i] == '.'):
                a.append(i)
        #pick a random word out of the word list, and then pick one of its random letters that corresponds to a un-made guess - BAD
        random.seed()
        print l[random.randint(0, len(l) - 1)][a[random.randint(0, len(a) - 1)]]

heres my shitty entry. didn't think much about how to actually pick what word to guess though.....

dictionary should be called words.txt and should be in same directory as this script. dictionary format should just be 1 word (lowercase) per line - used the lower case corncob list for testing
http://www.mieliestronk.com/wordlist.html

Name: Anonymous 2012-05-15 20:57

>>37
also, no checking asides from # of cmd line args
:(

Name: Anonymous 2012-05-15 20:59

Code tags exist for a reason.

Name: Anonymous 2012-05-15 21:07


>>39
sorryyyyyyyyy

import sys
import random
#two arguments needed
if(len(sys.argv) != 2):
    print "Usage: n"
    print "n - word to finish guessing"
else:
    #get the guess
    guess = sys.argv[1]
    #to match the word
    def match(word):
        #get rid of extra whitespace!
        word = word.strip()
        #if the guess and the word have equal length
        if(len(word) == len(guess)):
            #for every character in both the guess and the word
            for i in range(len(guess)):
                #if the guess was made and the guess was incorrect
                if(guess[i] != '.' and guess[i] != word[i]):
                    #no match
                    return False
            #all guesses ok or not made - matches
            return True
        else:
            #no length match - no match
            return False
    #get all matching words from the word list
    l = filter(match, open("words.txt", "r"))
    #if we have matching words
    if(len(l) != 0):
        #get a list of all the un-made guess characters
        a = []
        for i in range(len(guess)):
            if(guess[i] == '.'):
                a.append(i)
        #pick a random word out of the word list, and then pick one of its random letters that corresponds to a un-made guess - BAD
        random.seed()
        print l[random.randint(0, len(l) - 1)][a[random.randint(0, len(a) - 1)]]

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List