最近,我在头脑科学中做了很多练习问题,以便更好地学习如何使用它(并获得更多的能力)。今天,我编写了一个程序来操作输入,使每个单词(用逗号,
分隔)被反向打印,而逗号则保持在适当的位置,我对此感到非常自豪。在语句中提供的示例: Input:Hello,world\0
Output:olleH,dlrow
请随意撕毁我的代码(以及注释),并就如何改进我的代码给出一些提示!
>, 1:read
[ ~a:varchar a:in
[>+>+<<-] a:0 b:c:in
>>>>++++[<+++++ +++++ +>-]<[<->-] a:0 b:in [c:in-44]
<[[-]<[<+>-]>>] if c then a:in else
<[<<[.<]>[>]>.>]< print reverse then comma
, redo a':read ]
<[.<] print reverse
发布于 2018-02-17 12:46:20
在学习更多的脑功能之后,我了解到我的循环减去44可以改进:
>> tmp2=0 ++++[< tmp1=0 +++++ +++++ + >-] tmp1 is 44
<[<->-] subtract tmp1 from ptr
> tmp1=0 ++++[< ptr ----- ----- - >-]
这样可以防止实际创建值44并执行额外的~44操作。
发布于 2018-02-19 19:45:24
c-44
中的额外内存是不必要的,因为您可以直接从c
中减去4乘11。
除了最低限度的优化之外,您的代码也很好。老实说,你的评论不是。
据我所知,目前还没有一个最佳实践或风格指南,但问题的根源在于不一致。在第一行中,它以1:read
开头。还不完全清楚这意味着什么,所以我将用“读入单元格1”。1
立即被重命名为a
:
[ ~a:varchar a:in
squiggly行(~
)和varchar
不是自我解释,而是a:in
。因此,我们得到了<var>:<value>
将是一个模式的期望。
该模式在下一行中分解,其中a:0
(遵循模式),但b:c:in
:
[>+>+<<-] a:0 b:c:in
后面的一行引入了括号,这些括号是有效的brainfuck指令:
>>>>++++[<+++++ +++++ +>-]<[<->-] a:0 b:in [c:in-44]
我们现在混合了注释和代码。在这种情况下,这是错误的,因为我们在d:0
上,但这是一个等待发生的错误。
然而,真正的刺激是下一行。
<[[-]<[<+>-]>>] if c then a:in else
它缺少了b:(in or 0) c:0 d:0
,这对于后面的行非常重要,因为我们在这行之后处于c
或d
位置。如果你真的想管理这种风格,我建议你
[-][
Used names:
a : current cell at beginning of loop
b : cell after a to contain a copy of a
c : cell after b to subtract 44 from a
d : cell after c as helper to subtract 44 from c
in: current loop input
*<cell>: current cell
*?<cell>: cell position depends on values
]
>, *a:in
[ *a:in
[>+>+<<-] *a:0 b:in c:in
>>>++++[<----- ----- ->-] a:0 b:in c:(in minus 44) *d:0
<[[-]<[<+>-]>>] a:(c?in:0) b:(c?0:44) *?c:0 *?d:0
.....
老实说,我不建议你这么做,因为过了一段时间,事情就很难处理了。然而,这是一致的。
但是,我们可以像在常规编程语言中那样对代码进行注释:
[-]
[
This program reverses the words in a list of comma separated words.
It's memory usage is bound by the input string.
]
We leave the initial cell empty so that every word is 0 limited:
>,
[
Our initial loop cell A contains the input which we immediately
shove into the next two cells B and C:
[>+>+<<-]
A : 0 (current position)
B : input
C : input
D : temporarily 4 to subtract 44 from C
We now subtract 44 from C:
>>>++++[<----- ----- ->-]
If our input was NOT a comma (44) C won't be zero and we move
B back into A and set B and C to zero:
<[[-]<[<+>-]>>]
We're now either at position C (if C was zero) or position D
(if C wasn't zero); if C was zero then B will contain a comma
and A is zero; the next loop will therefore get executed
Otherwise we're at position D and simply move back to position
B to write the next letter of the word
<[<<[.<]>[>]>.>]<
,]
The last word is limited by zero so we just print the letters backwards:
<[.<]
这是夸大其词,但你可以像你喜欢的那样冗长。然而,这种注释有一个很大的缺点:很容易错误地输入逗号或句号,最终导致代码中断。
总之,干得好。如果-否则-逻辑是一个很好的大脑挑逗,老实说,这使一个正确的评论要重要得多。
https://codereview.stackexchange.com/questions/187751
复制相似问题