c – 有人可以解释脑力吗?
我正在尝试编写一个brainfuck解释器,但我缺少一些上下文或其他东西.应该调用以处理“><>”转换的函数应该是:
std::vector<int> Interpreter::interpret(const std::string &src_,const std::vector<int> & input_) 该计划的测试如下: int main() { std::vector<int> res; // output: 1 res = interpret("+."); for (auto i : res) std::cout << i << " "; 2 // output: 2 res = interpret(",.",{2}); for (auto i : res) std::cout << i << " "; return 0; } http://www.muppetlabs.com/~breadbox/bf/ 我真的不明白这是做什么的.我见过其他视频,但它没有意义.有人可以解释目标吗? 如果为函数提供要翻译的数组,30000字节数组有什么意义? 编辑: 编辑:提供说明
编辑:到目前为止我所拥有的: BFK.h #pragma once #include <vector> #include <iostream> using namespace std; char arr[30000]; char* p = arr; void incPtr(); void decPtr(); void incByte(); void decByte(); void printByte(); void setByte(); void jumpF(); void jumpB(); std::vector<int> interpret(const std::string &src,const std::vector<int> & input = {}); BFK.cpp #include "BFK.h" void incPtr() { p++; } void decPtr() { p--; } void incByte() { (*p)++; } void decByte() { (*p)--; } void printByte() { std::cout << *p; } void setByte() { std::cin >> *p; } void jumpF() { if (*p == 0) { } } void jumpB() { } std::vector<int> interpret(const std::string &src_,const std::vector<int> & input_){ int i = 0; int max = src_.size(); while (i < max) { switch (src_[i]) { case '>': incPtr(); break; case '<': decPtr(); break; case '+': incByte(); break; case '-': decByte(); break; case '.': printByte(); break; case ',': setByte(); break; case '[': jumpF(); break; case ']': jumpB(); break; } } return input_; } 你应该能够在没有实例化任何东西的情况下调用解释,所以我不知道将其组合在一起的另一种方法.我还没有实现跳转功能. 解决方法
想象一下,你得到两个数字–2和5 – 并希望你的Brainfuck程序打印他们的总和. 你怎么做,当你所能做的就是操纵当前单元格中的值并“选择”哪个单元格是当前的?当然,在某些时候你需要一些临时记忆. 为了在两个单独的单元格中有两个值,为了准备添加,这是你可以做的: ,>, 如果用户输入2和3(十进制,而不是ascii),那么Brainfuck程序存储器或磁带的前两个字节将如下所示: [2,3,...] // ^ This is where our tape pointer is now. We incremented it with `>` 够了,现在增加怎么样?解决方案是使用Brainfuck循环. 让我们添加两个自然整数而不做任何事情,只是递增和递减值: int a = 2,b = 3 while (a != 0) { b += 1 a -= 1 } 基本上,我们递减第一个值直到它达到零,并且随着这个减少,我们正在递增第二个值.随着时间的推移,这将显示: a = 2,b = 3 a = 1,b = 4 a = 0,b = 5 a == 0,break 因此,我们确实得到2 3 = 5.这很容易在brainfuck中实现. ,Get value for first cell (a) >,Get value for second cell (b) < Move back to a [ Loop until a == 0 >+ Decrement b <- Increment a We are still at a at this point,so everything is alright ] Loop again if a != 0 >. Print the final result (sum of a plus b) ……这一切都是为了演示如何使用Brainfuck的磁带存储器来做实际的事情. 我相信很多Brainfuck程序都会将磁带作为堆栈进行操作.有趣的是,您实际上并不需要了解Brainfuck程序用于以可用方式临时存储值的技术. 让我们看看Brainfuck解释器如何粗略地使用上述程序,逐条指令. *在堆栈中的值之后意味着它现在是堆栈指针的目标. 我会把它们中的一些归为不要太长时间. >,– tape [index] = input(),堆栈现在为[2 *,…] 毋庸置疑,我没有意识到这个问题是从2015年开始的! (耶!)至少有人可能会发现这在将来很有用……:^) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |