4

如何使用 Brainfuck 中的循环打印从 1 到 10 的数字?甚至可能吗?
我正在寻找解决此问题的方法。

4

4 回答 4

5
+++++++++++++++++++++++++++++++++++++++++++++++++  Cell 0 to '1'
>++++++++++  cell 1 to '\n'
>+++++++++  cell 2 to 9 as counter
[  Print numbers 1 to 9
<<  Data pointer to cell 0
.+  Print and increment cell 0
>.  Data pointer to cell 1 and print the newline
>-  Data pointer to cell 2 and decrement counter
]  Loop till counter is 0
+++++++++  Set cell 2 to 9
[  Set cell 0 to '1'
<<-  Data pointer to cell 0 and decrement
>>-  Data pointer to cell 2 and decrement counter
]  Loop till counter is 0
<<.  Data pointer to cell 0 and print '1'
-.   Decrement cell 0 and print '0'
>.   Data pointer to cell 1 and print newline

可读版本:

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

输出:

1
2
3
4
5
6
7
8
9
10

现场演示:

Brainf**k 打印 1 到 10
Brainf**k 展示台

于 2018-11-28T21:51:26.057 回答
3

TL;博士

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

在线尝试!

结束 TL;DR

为了在 BrainF**k 中编程,假设每个程序(即使是简单的程序)都需要从布局开始。

伪代码类似于:

Generate the character '0'
Move left and generate '\n'
Move left and generate the counter (10 numbers in this case)
Loop: Get back to the character '0', print it, increment it to '1', go to the newline, print it, go to the counter, and decrement it. End it when the counter is 0
Generate '1' and print it
Generate '0' and print it

但是,最后两个步骤可以简化为:

Go back to the digit '9'
Decrement it until '1' and print
Decrement it until '0' and print

这节省了大量时间和字节字符。

要生成字符“0”,您需要生成整数 48(因为那是 ASCII 值)。为此,您可以访问Esolangs 的 BF 常量。查找数字 48,我们发现-[>+<-----]>---

到目前为止,我们的程序是-[>+<-----]>---生成0

接下来,向左移动并生成\n(换行符)。我们可以使用<++++++++++. 注意它是如何完全加号的。这是因为在数字 10 处减少字符数的空间不大。

到目前为止,我们的计划是-[>+<-----]>---<++++++++++

然后,向左移动并生成计数器。我们希望计数器为 10 以打印从 0 到 9 的数字<++++++++++。。

到目前为止,我们的计划是-[>+<-----]>---<++++++++++<++++++++++

之后,开始循环[。转到'0' >>,打印它.,递增它+,转到换行符并打印<.,转到计数器并递减它,当它为零时结束循环<-][>>.+<.<-]

到目前为止,我们的计划是-[>+<-----]>---<++++++++++<++++++++++[>>.+<.<-]

最后,转到 '9' >>,将其递减至 1 并打印---------.,然后将其递减至 0 并打印-.---------.-.

程序结束。

于 2019-06-24T18:12:23.990 回答
0

这个有可能。这是代码:++++++++++>++++++++++[>+++++<-]>-.<<.>>+.<<.>>+.<<.>>+.<<.>>+.<<.>>+.<<.>>+.<<.>>+.<<.>>+.<<.>>--------.-.它可能更短,但是,它仍然完成相同的任务。Brainf***理论上可以执行任何计算,因为它是图灵完备的。这只是这些计算之一。

于 2019-07-11T16:56:17.217 回答
0
++++++++++++++++++++++++++++++++++++++++++++++++ Let address 0 be the digit we want to print, starting with '0'
>++++++++++ Let address 1 be our newline character
>+++++++++ Let address 2 be our counter, starting at 9 
[
  - Decrement the counter
  <<+. Increment the digit we want to print and print it
  >. Print the newline
  > Make sure we're at the counter again before we loop back
]

<< Move back to address 0
--------. Make address 0 '1'
-. Make address 0 '0'

现场演示

于 2018-12-23T16:44:35.057 回答