Write a program that translates an arithmetic expression to a Brainfuck program which evaluates the expression and prints the result in decimal numbers. For example, this arithmetic expression,
2 * (3 + 4)
can be translated to Brainfuck as,
++ 2 >+++ 3 >++++ 4 [-<+>]< add <[>[->+>+<<]>[-<+>]<<-]>[-]>>[-<<<+>>>]<<< mul [->+<]>[>>>>++++++++++<<<<[->+>>+>-[<-]<[<<[->>>+<<<]>>>>+<<-<]<<] ++++++++[->++++++<]>[-<+>]>>>>[-<<<<+>>>>]<[-]<<<]<[.<] print decimal
The Brainfuck program doesn't take input. However, each integer constant or operator in the original expression must have a distinct translated form contained in the resulting Brainfuck program.
This is the definition of an arithmetic expression.
primary-expression integer-constant (arithmetic-expression) multiplicative-expression primary-expression multiplicative-expression multiplicative-operator primary-expression additive-expression multiplicative-expression additive-expression additive-operator multiplicative-expression arithmetic-expression additive-expression additive-operator + | - multiplicative-operator * | / integer-constant a decimal constant in the range [0-255], which cannot start with '0' unless the number is 0
In other words, a
multiplicative-expression is evaluated before an
arithmetic-expression enclosed in parentheses is evaluated prior to the outer expressions. Otherwise, a chain of expressions is evaluated from left to right.
All whitespaces are ignored.
The Brainfuck machine to run the output will have 8-bit cells, each holding an unsigned integer. It is guaranteed that
255 + 1 == 0 and
0 - 1 == 255, so you can use this fact to implement your Brainfuck operations. At the same time, you may safely assume that the initial input of an arithmetic expression does not overflow or underflow during its evaluation.
This is a
The print function in the example BF code won't print anything if it reads 0. However, your program's BF output should print 0 if the result of the expression is 0. This BF function for example will print 0 for 0, but it's longer.
>>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>] >[+[-<+>]>+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<] ++++++[->++++++++<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]<
You are free to find or make a shorter version for any BF operation. Here is a list of common operations implemented in BF. This is a webpage where you can test BF code and also look at the memory dump.