문제

The following code snippet is from Wikipedia, and is the preamble to what seems to be the standard Hello World! program in Brainfuck...

1. +++++ +++++             initialize counter (cell #0) to 10
2. [                       use loop to set the next four cells to 70/100/30/10
3.    > +++++ ++              add  7 to cell #1
4.    > +++++ +++++           add 10 to cell #2 
5.    > +++                   add  3 to cell #3
6.    > +                     add  1 to cell #4
7.    <<<< -                  decrement counter (cell #0)
8. ]

I understand the gist of what's going on here, but what I don't understand is the mechanics of what's happening on lines 3 through 6. If +++++ +++++ adds 10 to the value in a[0], why does incrementing the pointer by one and executing ++*ptr seven times result in a[1] equalling 70? Shouldn't a[1] = 7? It seems like a[1] through a[4] are magically being increased by a factor of ten, and I don't understand why.

도움이 되었습니까?

해결책

The [] characters indicate a loop. The 10 +s before it indicate how many times the loop will run. This becomes clear when you understand what the various commands mean, and the <<<< - sequence of commands.

Each time the loop runs, it executes the following steps:

> move the pointer 1 space to the right
+++++ ++ add 7 to the current pointer
etc 3 more times > > >
<<<< - move back to the counter and decrement

This has the effect of adding "7, 10, 3, 1" 10 times. To put it another way, if you write the values at the first 5 pointer locations as you run the loop like they're in an array:

[10, 0, 0, 0, 0]     at first
[9, 7, 10, 3, 1]     after first run
[8, 14, 20, 6, 2]    after second
...
[0, 70, 100, 30, 10] up to this, the loop ends since the counter is 0,
                     and control continues

다른 팁

There is a nice brainfuck visualizer on this site: http://fatiherikli.github.io/brainfuck-visualizer/ it makes the brainfuck language easier to understand

The ++++++++++ makes cell0 equal to 10. Then, the [ starts a loop. In the loop, each iteration adds a set number to the other cells. For example, it adds 7 to cell one each time. The last line of the loop, <<<< - puts the pointer back to cell0 and decrements it. This way, each iteration makes cell0 count down. When it reaches 0, the loop stops and the program carries on. Therefore, it adds 7 to cell1 ten times, and this loop makes cell1 = 10*7.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top