Paste: google code jam qualifications problem C

Author: jon
Mode: factor
Date: Fri, 4 Sep 2009 10:39:55
Plain Text |
! Copyright (C) 2009 Your name.
! See http://factorcode.org/license.txt for BSD license.
USING: io splitting prettyprint sequences kernel math.parser namespaces 
formatting sets strings io.encodings.utf8 io.files math arrays fry
combinators accessors ;
IN: gcj.qualifs.C

: read-int ( -- int ) readln string>number ;
: >sequence ( a -- {a} ) { } clone swap prefix ;

: gg-format ( int -- string ) 
{
    { [ dup 10 < ] [ number>string "000" swap append ] }
    { [ dup 100 < ] [ number>string "00" swap append ] }
    { [ dup 1000 < ] [ number>string "0" swap append ] }
    { [ t ] [ number>string reverse first4 4array reverse >string ] }
} cond ;

: print-answer ( case# int -- )
[ 1 + ] dip
gg-format
"Case #%d: %s\n" printf ;

: find-times ( string subseq -- res )
 dup empty?
 [ 2drop 1 ] 
 [ tuck first >sequence split1 [ drop ] dip dup
 [ swap [ rest find-times ] [ find-times ] 2bi + ]
 [ 2drop 0 ] if ] if ;

: get-all-begining-seqs ( subseq -- seqs ) 
{ } clone swap
[ suffix dup ] { { } } map-as nip ;
: get-all-ending-seq ( subseq -- seqs )
reverse get-all-begining-seqs reverse [ reverse ] map ;

DEFER: find-times1
: good-find-times ( string subseq -- res ) 
over length 35 < [ find-times ] [ find-times1 ] if ; 

: find-times1 ( string subseq -- res ) 
{ 
    { [ 2dup [ length ] bi@ < ] [ 2drop 0 ] }
    { [ 2dup [ length ] bi@ = ] [ [ >array ] bi@ = [ 1 ] [ 0 ] if ] }
    { [ t ] [ [ get-all-begining-seqs ] [ get-all-ending-seq ] bi
        [ swap halves ] dip swap [ swap ] 2bi@
            [ [ good-find-times ] with map ] 2bi@ [ 1 prefix ] [ 1 suffix ] bi*
            [ * ] [ + ] 2map-reduce ] }
} cond ;



: solve-case ( string -- res ) 
"welcome to code jam" clone find-times1 ;

: answer-case ( case# string -- ) 
solve-case print-answer ;

: solve-file ( -- ) 
read-int
[ readln answer-case ] each ;

: read-file ( file -- )
  utf8 [ solve-file ] with-file-reader ;

: write-answer ( file -- )
[ "work/gcj/qualifs/C/results1.out" utf8 ] dip [ read-file ] curry with-file-writer ;

Annotation: Better library Usage

Author: jon
Mode: factor
Date: Sun, 6 Sep 2009 07:16:47
Plain Text |
: gg-format ( int -- string ) 
number>string 4 CHAR: 0 pad-head ;

New Annotation

Summary:
Author:
Mode:
Body: