Paste: Ruby Quiz 12

Author: jwmerrill
Mode: factor
Date: Tue, 9 Dec 2008 04:36:18
Plain Text |
! Copyright (C) 2008 Jason Merrill.
! See http://factorcode.org/license.txt for BSD license.
USING: kernel io io.files io.encodings.utf8 sequences sorting unicode.case 
    math math.order hashtables assocs vectors arrays fry sets prettyprint 
    strings ;
IN: scrabble-stems

: seven-letter-words ( -- seq )
    "/usr/share/dict/words" utf8 file-lines [ length 7 = ] filter ;

: word-class ( str -- key ) >lower [ <=> ] sort ;

! All unique sets of letters formed by removing one letter from the 
! given word, and the letter that was removed.
: stems ( word -- seq )
    word-class [ length ] keep
    '[ _ [ remove-nth ] [ nth ] 2bi ] { } map>assoc prune ;
    
: add-association ( letter stem assoc -- assoc )
    [ push-at ] keep ;

: add-word ( assoc word -- assoc )
    stems swap [ first2 spin add-association ] reduce ;

! A hash where the keys are scrabble stems, that is, sets of letters that can
! be combined with one more letter to form a dictionary word, and values are
! vectors of letters that can be added to a stem to form a dictionary word.
: stem-hash ( seq -- hash )
    H{ } clone [ add-word ] reduce [ prune ] assoc-map ;

! Prints the set of six letter scrabble-stems ranked by how many letters they
! can be combined with to form a seven letter word.   
: print-results ( -- )
    seven-letter-words stem-hash >alist       
    [ [ second length ] bi@ <=> ] sort reverse
    [ second length 16 > ] filter 
    [ [ >string write " " write ] [ length . ] bi* ] assoc-each ;
    
MAIN: print-results

New Annotation

Summary:
Author:
Mode:
Body: