Paste: Ubongo!

Author: yac
Mode: factor
Date: Fri, 5 Aug 2011 12:04:20
Plain Text |
#! /usr/bin/env factor
USING: kernel math math.ranges math.parser math.order math.functions
    assocs sequences sequences.deep sorting strings arrays splitting
    accessors io io.files io.encodings.utf8 command-line fry ;
IN: ubongo


TUPLE: player n oc ;
: <player> ( n oc -- player ) player boa ;

: >players ( lines -- players )
    dup length [1,b] swap zip [ first2 <player> ] map ;

! missing word for this - handcrafted with love ;)
: occ' ( oseq seq -- oseq seq )
    dup first 
    [
        dup dup first [ = not ] curry find drop
        dup [ tail ] dip swap [ suffix ] dip
        occ'
    ] when ;
: occurances ( seq -- oseq )
    { } swap natural-sort f suffix occ' drop [ >=< ] sort ;

: seqmax ( seq -- max ) 0 [ max ] reduce ; inline
! recursive carnage
: winner' ( plrs -- plrs' )
    [ oc>> empty? not ] filter
    dup [ oc>> first ] map seqmax '[ oc>> first _ = ] filter 
    [ [ rest ] change-oc ] map
    dup length 1 > [ winner' ] when ;
: winner ( lines -- n )
    [ dup empty?
        [ drop { } ] [ { CHAR: \s } split occurances ] if
    ] map >players winner' dup empty? [ drop 0 ] [ first n>> ] if ;

: main ( -- )
    (command-line) rest dup empty? 
        [ drop "Need an input file as only argument" ]
        [ first utf8 file-lines winner number>string ] 
    if print ;

main

New Annotation

Summary:
Author:
Mode:
Body: