Code Golf: Word Unscrambler

Python 3 / 84 chars / 7 correct outputs / score 8.3333

edit As per clarifications, removed .upper() and considering all 7 ouputs correct.

a=sorted
for b in input().split():print([c for c in open('x')if a(b)==a(c[:-1])][0])

Output:

BUBBLE
FLOWER
CAKE
WATER
CORK
MILK
PEACE

Python, 189 171 156 chars / 6 7 correct outputs / "spirit of the law"

from urllib import*
z=sorted
x=dict((`z(m)`,m)for m in urlopen("http://bit.ly/wZYCmE").read().split())
for n in raw_input().split():print x[`z(n.upper())`]

(It gets "fowler" instead of "flower", both are on the input list and have the same letters.)

Edit: Steven Rumbalski's suggestions

Python, 144 chars / 7 correct outputs / "letter of the law"

for x in raw_input().split():print{620:'bubble',655:'flower',404:'cake',547:'water',431:'rock',429:'milk',510:'peace'}[sum(map(ord,x.lower()))]

GolfScript, 27 chars, 7 correct outputs ⇒ score ≈ 25.926

n%(\:w;' '%{$:c;w{$c=}?}%n*

GolfScript doesn't have a file I/O operator, so I had to get a bit clever with the input. Specifically,

  • the scrambled words should be given on the first input line, separated by spaces, and
  • the wordlist should be given on the subsequent input lines, one word per line.

The scrambled words and the wordlist need to have the same letter case.

Here's an example invocation from a Unix shell command line, assuming that the code above has been saved as unscramble.gs, the GolfScript interpreter as golfscript.rb and the wordlist as wordlist.txt:

(echo BBULEB LWRFOE KAEC RTAWE COKR KMLI PCAEE; cat wordlist.txt) \
  | ruby golfscript.rb unscramble.gs 

This will produce the following output:

BUBBLE
FLOWER
CAKE
WATER
CORK
MILK
PEACE

The way it works is simply by sorting the letters in each input word and selecting the first word in the wordlist that produces the same string when its letters are sorted. Nearly half of the code is actually just for input parsing (and output formatting): all the real work is done in the {$:c;w{$c=}?}% loop.

Here's a de-golfed version with comments showing how it works:

n %                 # split the input on newlines
( \ :w ;            # pop the first line off the list of lines and assign the rest to w
' ' %               # split the first line on spaces

# apply the following map to each scrambled word:
{
    $ :c ;          # sort the letters in the word and assign the sorted word to c
    w { $ c = } ?   # find the first word in w that, sorted, equals c
} %

n *                 # join the results with newlines for output

Tags:

Code Golf

Word