Skip to content

Instantly share code, notes, and snippets.

@mattboehm
Created December 5, 2017 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattboehm/5ccd490b9255000ec9a654f325d307d6 to your computer and use it in GitHub Desktop.
Save mattboehm/5ccd490b9255000ec9a654f325d307d6 to your computer and use it in GitHub Desktop.
Advent of code 2017 day 1 part 1 in Brainfuck
must be run on cell size of 16 bits or more with wrapping on inc and dec operations
>>
,[------------------------------------------------>,] read input and convert ascii digits to data
copy the first digit to the end (to handle wrapping)
+ add 1 to the end space to mark it
[<]> goto first digit
[<+[>]<+[<]>>-] move to marked space and the space before first digit <[>+<-] >[>]<
- subtract the 1 we added
we are now on the rightmost digit (the one we just copied)
we want to loop through each digit and if it is equal one to its left, add it to the total
the memory looks like this
result 0 first second third _______ last firstcopy
(by the way I use * as a plus sign and ~ as a minus sign)
[ while digit is nonzero (we rely on the fact that none of the digits in the input are 0)
<
r 0 ___(a) b t1 t2
[->>+>+<<<] >> [-<<+>>] copy a to t2
t1
<
r 0 ___a (b) 0 a
instead of adding b if the numbers are equal we always add b and then subtract when they are not equal
[>>>+<<< [<]<+ >>[>]>-<<-]
r*b 0 ___a (0) 0 a~b b
>>>[<<<+>>>-]
r*b 0 ___a b 0 a~b (0)
<
r*b 0 ___a b 0 (a~b) 0
if a~b is nonzero we subtract b from the result
[
<<
r*b 0 ___a (b) 0 a~b 0
[
[<]
r*b (0) ___a b 0 a~b 0
<-
(r*b~) 0 ___a b 0 a~b 0
>>[>]
r*b~ 0 ___a b (0) a~b 0
<-
r*b~ 0 ___a b~ 0 a~b 0
]
r 0 ___a (0) 0 a~b 0
>>[-]
r 0 ___a 0 0 (0) 0
]
r*?b 0 ___a b? 0 (0) 0
b will be added to r iff a was equal to b
if it was equal and we skipped that if block then we never deleted b and should zero it out now
<<[-]
r*?b 0 ___a (0) 0 0 0
move to the next digit in line
<
]
r (0)
<
(r)
print result as ascii
[>>+>+<<<-]>>>[<<<+>>>-]<<+>[<->[>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]
++++++++[<++++++>-]>[<<+>>-]>[<<+>>-]<<]>]<[->>++++++++[<++++++>-]]<[.[-]<]<
@mattboehm
Copy link
Author

You can run it here but first must change "Cell size" to 16 and "Memory overflow behaviour" to "wrap".

@jesseflorig
Copy link

You monster.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment