You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
1.5 KiB
59 lines
1.5 KiB
#! /usr/bin/env gforth
|
|
|
|
\ File details
|
|
0 VALUE fd-in
|
|
4096 CONSTANT line-buffer-size
|
|
CREATE line-buffer line-buffer-size chars allot
|
|
VARIABLE line-number
|
|
VARIABLE line-len
|
|
|
|
\ Calorie variables
|
|
0 VALUE temp-cal
|
|
0 VALUE high-cal-1
|
|
0 VALUE high-cal-2
|
|
0 VALUE high-cal-3
|
|
|
|
: UPDATE-3-HIGHEST ( cal -- )
|
|
DUP high-cal-1 > IF
|
|
high-cal-2 TO high-cal-3
|
|
high-cal-1 TO high-cal-2
|
|
TO high-cal-1
|
|
ELSE
|
|
DUP high-cal-2 > IF
|
|
high-cal-2 TO high-cal-3
|
|
TO high-cal-2
|
|
ELSE
|
|
DUP high-cal-3 > IF
|
|
TO high-cal-3
|
|
ELSE \ not bigger than top 3
|
|
DROP
|
|
THEN THEN THEN ;
|
|
|
|
: GET-3-HIGHEST ( filename -- h3 h2 h1 )
|
|
0 TO temp-cal
|
|
R/O OPEN-FILE THROW TO fd-in \ open input file
|
|
BEGIN
|
|
1 line-number +! \ increment line number by 1
|
|
line-buffer line-buffer-size fd-in READ-LINE ( len flag err )
|
|
THROW \ if errors, throw to top level error handler (?)
|
|
WHILE \ while no error flag, (false (0x00) flag == eof)
|
|
line-len ! \ store length into line-len
|
|
line-buffer line-len @
|
|
DUP 0 = IF \ if empty line, update 3 highest with temp, and zero temp-cal
|
|
temp-cal UPDATE-3-HIGHEST
|
|
0 TO temp-cal
|
|
ELSE \ add number in line to temp calories
|
|
S>NUMBER? 2DROP \ get number from string
|
|
temp-cal + TO temp-cal
|
|
THEN
|
|
REPEAT
|
|
UPDATE-3-HIGHEST
|
|
high-cal-3 high-cal-2 high-cal-1 ;
|
|
|
|
s" input.txt" GET-3-HIGHEST
|
|
." 1: " DUP . CR \ print highest calorie count
|
|
." 2: " + + . CR \ sum three highest calorie counts
|
|
|
|
BYE
|
|
|