Skip to content

Instantly share code, notes, and snippets.

@nicolalamacchia
Last active January 24, 2024 16:43
Show Gist options
  • Save nicolalamacchia/d29feaa16a8ef1fe2582bef02dc4662c to your computer and use it in GitHub Desktop.
Save nicolalamacchia/d29feaa16a8ef1fe2582bef02dc4662c to your computer and use it in GitHub Desktop.
Advent of Code 2022, day 7 (part 1) - Gforth solution
#! /usr/bin/gforth
\ for debugging (e.g. 'a' reg)
: reg ( c -- )
." reg " emit ." >>> " .s cr ;
\ \ \
\ file stuff
32 Constant BUF-LEN
BUF-LEN 2 - Constant LINE-LEN
0 Value fd-in
Create line-buffer BUF-LEN allot
: open-input ( c-addr u -- )
r/o open-file throw to fd-in ;
: close-input ( -- )
fd-in close-file throw ;
: next-buffer-line ( -- u flag )
line-buffer LINE-LEN fd-in read-line throw ;
\ \ \
\ string stuff
: line-str ( u1 -- c-addr u1 )
>r line-buffer r> ;
: len ( c-addr u1 -- u1 )
swap drop ;
: str>num ( c-addr u1 -- u2 )
0. 2swap >number \ convert string to double cell number
2drop d>s ; \ convert to single cell number
\ \ \
\ cli stuff
: parse-args ( -- c-addr u )
argc @ 1 > if
1 arg
else
." No argument provided" cr
1 (bye)
then ;
\ \ \
\ business stuff
s" $ cd " 2Constant CD-CMD
s" .." 2Constant BACK-CMD
100000 Constant MAX-DIR-SIZE
\ line parsing utilities
: cd? ( c-addr u -- flag )
CD-CMD string-prefix? ; \ non-standard
: ..? ( c-addr u -- flag )
BACK-CMD str= ; \ non-standard
: dir? ( c-addr u -- flag )
..? 0= ;
: cd-arg ( c-addr1 u1 -- c-addr2 u2 )
CD-CMD len /string ;
\ \ \
Variable accumulator
: ?accumulate ( u -- )
dup MAX-DIR-SIZE <= if
accumulator +!
else
drop
then ;
: .result ( -- )
accumulator @ . cr ;
: parse-file ( -- )
begin
next-buffer-line
while \ line exists
line-str
2dup \ used in both branches
cd? if \ cd line
cd-arg dir? if \ cd <dir>
0
else \ cd ..
dup
?accumulate
+
then
else \ not a cd line, accumulate value
str>num +
then
repeat
drop \ drop the unused flag for the while loop
\ last cd .. (loop residual)
dup
?accumulate
+
\ parent directory
?accumulate ;
\ \ \
\ main
parse-args
open-input
parse-file
close-input
.result
bye
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment