Home » FizzBuzz in Brainfuck

# Simplifications

Thanks to implementing some analysis of while loops in my Brainduck project (which I worked on thanks to reviewing “Hello, Brainfuck”), I managed to find a bunch of loops that were always performed x times. By expanding these loops (copy-paste their content x times and remove the loop) several simplifications are possible.

### Boolean peek-a-boo. Wheeeere’s the boolean?

``````+[-<+]->>    Locate the 255 marker and goto the boolean
``````

This loop is always being performed exactly twice, which means that the loop can be expanded to `+-<+-<+->>` which in turn can be simplified to `<<>>` which of course can be totally removed. So it can be replaced with a comment:

``````cursor is now located on the boolean
``````

### Boolean is always one, no shit Sherlock!

``````]+

Boolean is always one here so print new line
[-]<<<.>>>     Print new line
``````

No wonder that the boolean is always one when you did `+` right after the `]`. As the value is always 1, the loop is always performed once, which can simplify this code to:

``````]
Boolean is now zero so just print the new line
<<<.>>>     Print new line
``````

### Boolean, marker, boolean, Dumbledore!

``````-[          If boolean is zero then print the number
+>>>
+[-<+]-    Go back to the 255 marker
>>          We are positioned after the counter
``````

“We are positioned after the counter” is the same as “we are positioned at the boolean” (which now has the value zero). This code starts at the boolean, which is positioned two steps to the right of the 255 marker, and then you move three steps more to the right only to go back to the 255 marker… as this loop to go backwards is always performed five times, this can be simplified. First, expand the loop:

``````     +>>>
+-<+-<+-<+-<+-<+-    Go back to the 255 marker
>>          We are positioned after the counter
``````

Then remove the `+-` that cancel each other out:

``````     +>>>
<<<<<       Go back to the 255 marker
>>          We are positioned after the counter
``````

Then remove `><` that cancel each other out and here is what remains:

``````+
``````

### Finding 252 and changing to 254

``````++++[----<++++]--   Find value 252 and change to 254
``````

This loop is done exactly twice, which can be simplified to:

``````<<++                Go left to value 252 and change to 254
``````

### Finding 254 when we’re almost there already

``````+++[---         Make sure that we are not at 253 (end)
++[--<++]--  Find last value 254

--           Change marker to 252 to indicate that we're processing it
``````

Guess what!? Your 253 is located exactly one step after the 254 value, which means that the “Find last value 254” loop is only done once, which means it is simplification time:

`````` +++[---         Make sure that we are not at 253 (end)
<--         Go to 254 marker and change to 252 to indicate that we are processing it
``````

### Go directly to countdown, do not change it, do not collect \$200

``````>>             Go to the countdown
-<             Decrease fizzbuzz countdown
+>             Increase fizzbuzz counter
``````

The BF code `>>-<+>` is the same thing as `>+>-` so change this to:

``````>+             Increase fizzbuzz counter
>-             Decrease fizzbuzz countdown
``````

### Resetting the boolean

``````>+              Increase counter
>[-]            Reset boolean for if we have found a match or not
``````

The boolean is reset at the end of every loop, no need to reset it at the beginning as well, change to:

``````>+>             Increase counter
``````

### Finding the 255 marker and the countdown

``````ALGORITHM START

+[-<+]-         Go backwards to the 255 mark
<

[
+[->+]-     Go forward to the start position 255 marker
``````

My analysis found something interesting here, the first time “Go forward to the start position 255 marker” loop was done, it was only performed once, but all other times it was performed exactly twice. This gave me a clue that there was a possibility of refactoring here, starting with simply replacing the single `<` with `<<` to make the loop always be performed exactly twice.

``````+[-<+]-         Go backwards to the 255 mark
<<              Go to the countdown

[
+[->+]-     Go forward to the start position 255 marker
``````

Then it occurred to me that at the end of the loop, at this code:

``````<<<.>>>     Print new line

+[-<+]-    Go back to the 255 marker
<<         Go to the countdown to find out if we should go another round
``````

This “Go back to the 255 marker” was always performed twice, which means that we once again expand and simplify:

``````<<<.>>>     Print new line

+-<+-<+-   Go back to the 255 marker
<<         Go to the countdown to find out if we should go another round
``````

and then:

``````<<<.      Print new line
<         Go to the countdown to find out if we should go another round
``````

Now, going back to the start of the big loop, let’s take a look at:

``````[
+[->+]-        Go forward to the start position 255 marker
<<->>          Decrease countdown
``````

Considering the first `[` is always at the countdown, we can just do `->>`, i.e. we don’t need to first fine the 255 marker just to go to the countdown when we are already at the countdown. So replace that with:

``````[
->>            Decrease countdown
``````

``````[>]                 Position to a place that is zero to avoid repeat
++[-->++]-- <       Find NEXT 254 marker and stop right before it
``````

The ‘avoid repeat’ comment is not very good, because of the loop afterwards, it is enough to only do the `>` once. However, if the string itself would contain the magical 254 value, then we would have a problem. So clarify this comment:

``````[>]                 Go to a zero to avoid repeat in case there is a 254 value in the string
``````

### Memory utilization

The memory utilization seems to be quite good, only 39 memory cells are being used overall. However, this:

``````>>>>>>>>>>>>>>>>              Empty space for counter to string conversion
``````

Is unnecessary extra space. That can be reduced to:

``````>>>>> >>>>> >
``````

Also note how spaces every 5 instructions makes it more readable.

### Additional simplifications, that reduces the flexibility

This simplification can only be done thanks to the fact that the FizzBuzz ends at 100. If you want to FizzBuzz more, you cannot simplify this part.

The SO code for printing a number can be simplified to:

``````     Code taken from StackOverflow below for printing a number
>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<
[->->+<<]>[-]>[<++++++[->++++++++<]
>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]
End of StackOverflow code
``````

With this simplification, one extra memory cell can be freed by changing to:

``````>>>>> >>>>>                   Empty space for counter to string conversion
``````

### 2 become 1 (two zeros become one)

Currently there are always two zeros after a Fizz or Buzz string. This can easily be changed to only one zero, which would allow a bit of simplification in this code:

`````` If current marker is NOT zero
[
<<++                Go left to value 252 and change to 254
[>]                 Go to a zero to avoid repeat in case there is a 254 value in the string
]
``````

This also allows a simplification at the end of the “We have a match” case:

``````>++                 Go to next 254 change to 256 to break loop
``````

It allows more flexibility though to have it as it used to be, to scan for the next 254 value.

### Resulting code

Non-minimized version of the resulting code, without the additional flexibility-reducing simplifications, 631 Brainfuck instructions in the source code, 152267 being performed at run-time:

``````TAPE MEANINGS
255 Start
254 A Fizz or Buzz text to print
253 End of Fizzes and Buzzes
252 Currently processed FizzBuzz calculation

TAPE OVERVIEW
Remaining Iterations
10 for Line Break
255 Start Marker
Counter
Boolean 1 or 0 for whether or not a fizzbuzz matches current counter
Some empty space for converting counter to string
Any Number of Sequences of the following
254 Indicator for FizzBuzz sequence
Counter
Countdown until next text output
Text any number of characters
Zero
Zero
254 and 253 marker to indicate the end of sequences

++++++++++[>++++++++++<-]> Initialize 100 (number of times to perform FizzBuzz)

>++++++++++                   Line break
>-                            Start marker
>>>>> >>>>> >                 Empty space for counter to string conversion

SETUP Create the Fizz and Buzz sequences on the tape
without having to write plus more than 65 times for every character

FIZZ
-->                               Create indicator
+++++++[->++++++++++<]>           Create F
[->+>+>+>+<<<<]                   Copy 4x F
+++                               Set modulo operator to 3
>>+++>>>                          Adjust second letter to I
++++++++[-<++++<++++<++++>>>]     Make the last three lowercase to Fiff
+++++[-<++++<++++>>]              Modify the last two F to Z by adding 20
>>                                Leave two zeros at the end

BUZZ
-->                               Create indicator
++++++[->+++++++++++<]>           Create B
[->+>+>+>+<<<<]                   Copy 4x B
+++++                             Set modulo operator to 5
++++++++[-<++++<++++<++++>>>]     Make lower case
>>                                Leave two zeros at the end

-->---          Mark the ending with 254 and 253

END OF SETUP

ALGORITHM START

+[-<+]-         Go backwards to the 255 mark
<<              Go to the countdown

[
->>            Decrease countdown
>+>            Increase counter

++[-->++]-->   Find next 254 and go one step beyond it

Loop through all 254s
+++[---         Make sure that we are not at 253 (end)
<--            Go to 254 marker and change to 252 to indicate that we are processing it
>+             Increase fizzbuzz counter
>-             Decrease fizzbuzz countdown

If current marker is NOT zero
[
<<++                Go left to value 252 and change to 254
[>]                 Go to a zero to avoid repeat in case there is a 254 value in the string
++[-->++]-- <       Find NEXT 254 marker and stop right before it
]

>++
Check if we are positioned on a 254 already then if skip this
[--

We have a match so find start position and mark match

+[-<+]-  >>         Find 255 marker and go to the boolean
[-]+                Set boolean to 1 whatever the previous value is
++++[---->++++]--   Find value 252 and change to 254
>[->+<]             Reset the current FizzBuzz countdown
>>[.>]              Print the text
++[-->++]           Go to next 254 change to 256 to break loop
]
-->

+++ Detect if we are at the 253 end
]
---

ALL FIZZBUZZES PROCESSED
Use the boolean to check whether or not to print the number

+[-<+]-     Go back to the 255 marker
>>          Go to boolean
-[+         If boolean is zero then print the number

Code taken from StackOverflow below for printing a number
>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[-
<+>]>+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->++++++++
<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]
End of StackOverflow code

cursor is now located on the boolean
]

Boolean is now zero so just print the new line
<<<.      Print new line
<         Go to the countdown to find out if we should go another round
]
``````

The minimized version of the resulting code with the additional flexibility-reducing simplifications, 548 characters: (run-time instructions being performed is 143808)

``````++++++++++[>++++++++++<-]>>++++++++++>->>>>>>>>>>-->+++++++[->++++++++
++<]>[->+>+>+>+<<<<]+++>>+++>>>++++++++[-<++++<++++<++++>>>]+++++[-<++
++<++++>>]>-->++++++[->+++++++++++<]>[->+>+>+>+<<<<]+++++>>+>++++++>++
++++>++++++++[-<++++<++++<++++>>>]++++++[-<+++<+++<+++>>>]>-->---+[-<+
]-<<[->>>+>++[-->++]-->+++[---<-->+>-[<<++[>]]>++[--+[-<+]->>[-]+++++[
---->++++]-->[->+<]>>[.>]>++]-->+++]---+[-<+]->>-[+>++++++++++<<[->+>-
[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->->+<<]>[-]>[<++++++[-
>++++++++<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]]<<<.<]
``````

• You should “initialize 100” after the “Tape meanings”. I consider it to be part of the actual code and the explanation to be a kind of “header” explaining the code.

• I agree that commenting “what” becomes more important in bf, but you should still explain “why” every now and then. The reasoning behind why you build the “Fizz” and “Buzz” strings the way you do is not obvious. A simple “This is more efficient than directly creating the letters.” comment would go a long way. There’s also no indication as to why you leave two zeros at the end of each string.

• I can’t figure out what this hash mark is doing here. It’s a little confusing. Anything in bf that’s not a valid operator is a comment. You don’t use hashes for comments elsewhere, don’t do it here either.

``````+++ # Detect if we are at the 253 end
``````

All in all it’s the most readable bf I’ve laid my eyes on though. However, don’t take my omission of commenting on the actual code as an indication that it was done right. Truthfully, I’ve no idea. I’d have to brush up on Turing machines and spend some time writing something simple just to get into the right mindset to decipher this. I mostly wanted to post an answer so that maybe it would prod someone else into taking a serious look at it.

## Spring + Hibernate manually creating transactions, PROPAGATION_REQUIRED fails. BUG?

You basically don't use the transaction API as its intended to. The reference documentation is pretty precise about how to use programatic transactions: PlatformTransactionManager manager = … // obtain a transaction manager (DI) TransactionTemplate template =...

## With Numpy, what’s the best way to compute the inner product of a vector of size 10 with each row in a matrix of size (5, 10)? [closed]

For a start we can ask which ones work! In : vector1 = np.arange(10) In : matrix1 = np.arange(50).reshape(5,10) First the wrong way to use dot: In : np.dot(vector1*matrix1) ---------------------------------------------------------------------------...

## How do I store a custom user selected CSS template style (like wordpress visual editor)? [closed]

If you want to give users the ability to style a few HTML elements on different sections of your website, the simplest implementation is the following: 1) Create table users_styles with fields: id (INT), user_id (INT), section_id (INT), value (VARCHAR 1000)....

## Calculate the sum with minimum usage of numbers

Here's a hint: 23 : 11 + 11+ 1 ( 3 magic numbers) 120: 110+ 10 (2 magic numbers) The highest digit in the target number is the answer, since you need exactly k magic numbers (all having 1 in the relevant position) in order for the sum to contain the digit k. So...

## Why not drop the “auto” keyword? [duplicate]

Your proposal would be rejected on the basis of backward compatibility alone. But let's say for the sake of argument that the standards committee like your idea. You don't take into account the numerous ways you can initialize a variable widget w; // (a) widget...

## Recursive to iterative using a systematic method [closed]

So, to restate the question. We have a function f, in our case fac. def fac(n): if n==0: return 1 else: return n*fac(n-1) It is implemented recursively. We want to implement a function facOpt that does the same thing but iteratively. fac is written almost in...

## How can I match values in one file to ranges from another?

if the data file sizes are not huge, there is a simpler way \$ join input1 input2 | awk '\$5<\$4 && \$3<\$5 {print \$2, \$5-\$3+1}' B100002 32 B100043 15 B123465 3 This Perl code seems to solve your problem It is a common idiom: to load the entire...

## Javascript difference between “=” and “===” [duplicate]

You need to use == or === for equality checking. = is the assignment operator. You can read about assignment operators here on MDN. As a quick reference as you are learning JS: = assignment operator == equal to === equal value and equal type != not equal !==...

## Why does the || (or) and && (and) operator in JavaScript behave differently than in C (returning non boolean value)?

The logical operators in C always evaluate to boolean values. In C, the int 1 represents true and the int 0 represents false. That's the reason why both the expressions, "All" && 1 and "All" || 1, evaluate to 1. Both of them are logically true. For...

## Compiler complains about misplaced else [closed]

Your compiler complains about an misplaced else because, well, there is an else without a preceding if: // ... for (j=1; j<n-i; j++) { if(a[j]<=a[j+1]) { // ... } // END OF IF } // END OF FOR else { continue; } // ... The else in your code does not follow...

## Bootstrap – custom alerts with progress bar

/* !important are just used to overide the bootstrap css in the snippet */ .alertContainer { border-radius: 0 !important; border-width: 0 !important; padding: 0 !important; height: auto !important; position: absolute !important; bottom: 15px !important; left:...

## How to Garbage Collect an external Javascript load?

Yes, s.onload = null is useful and will garbage collect! As of 2019, it is not possible to explicitly or programmatically trigger garbage collection in JavaScript. That means it collects when it wants. Although there is cases where setting to null may do a GC...

## Math programming with python

At first, what you are looking for is the modulo operator and the function math.floor() Modulo from wikipedia: In computing, the modulo operation finds the remainder after division of one number by another (sometimes called modulus). for example: 12%12=0...

## How to create posts-by-month-and-year table in Jekyll without plugins? [closed]

This is the code for the archive.html page. You can see it live here. Tested with 400 posts, no performance issues on build/serve. --- layout: page title: archive --- {%comment%} ++++++++++ We first find start and end years ++++++++++ {%endcomment%} {% assign...

## Android slide over letters to create a word [closed]

Here some advice you can use: First for each cell you can create an object that represents the state of that cell: class Cell { char mChar; int row,column; boolean isSelected; } then you can create a 2D array of your cells Cell[][] mTable = ... For views you...

## Sum two integers in Java

You reused the x and y variable names (hence the variable x is already defined in method main error), and forgot to assign the ints read from the Scanner to the x and y variables. Besides, there's no need to create two Scanner objects. public static void...

## How does one force a C++ move operator without std:whatever [closed]

I cannot use std:move, because I don't use the standard libraries at all... Hopefully it doesn't do anything magical that I can't do? From How does std::move() transfer values into RValues?: template <typename T> typename...

## How to implement and fire an event when a change occurs in a property of `T` in `List` within the owning class in Java

I just ported ItemPropertyChangedNotifyingList to ItemChangeList. In code, I changed this part. Used 'ArrayList' to hold elements instead of 'List` in C# In copyTo, I used Java 8 Stream. Since you tag 'android', I used Lightweight-Stream-API to achieve same...

## Extend three classes that implements an interface in Java

Using this simplified implementation of the library, using method() instead of M(): interface IFC { void method(); } class A implements IFC { public void method() { System.out.println("method in A"); }; } As akuzminykh mentions in their comment You'd write a...

## How to set the stream content in PHPExcel? [closed]

Okey, First thing first PHPExcel_Worksheet_MemoryDrawing() can't solve your problem if you insist to use stream content and pass that to your worksheet your PDF will not render your image. But you can use `PHPExcel_Worksheet_Drawing()' if you want to render...