get fucked

main
Brett 2023-11-13 14:20:43 -05:00
parent e0e5f3d2ac
commit 702d5c3b57
1 changed files with 27 additions and 16 deletions

View File

@ -10,22 +10,22 @@ class brainfuck
size_t _dp; size_t _dp;
char* _data; char* _data;
void check_size(){ void check_size()
{
if (_dp >= _size) if (_dp >= _size)
{ {
char* tmp = new char[_size * 2]; char* tmp = new char[_size * 2];
std::memset(tmp, 0, _size * 2); std::memset(&tmp[_size], 0, _size);
std::memcpy(tmp, _data, _size); std::memcpy(tmp, _data, _size);
_size = _size * 2; _size = _size * 2;
delete[] _data; delete[] _data;
_data = tmp; _data = tmp;
} }
} }
public: public:
brainfuck(): _size(30000), _dp(0), _data(new char[_size]) brainfuck(): _size(2), _dp(0), _data(new char[_size])
{ {std::memset(_data, 0, _size);}
std::memset(_data, 0, _size);
}
void increment_dp() void increment_dp()
{ {
@ -44,28 +44,37 @@ class brainfuck
_data[_dp]++; _data[_dp]++;
} }
void decrement(){ void decrement()
{
check_size(); check_size();
_data[_dp]--; _data[_dp]--;
} }
void print(){ void print()
{
std::cout << _data[_dp]; std::cout << _data[_dp];
} }
void read(){ void read()
{
std::cin >> _data[_dp]; std::cin >> _data[_dp];
} }
char is(){ char is()
{
return _data[_dp]; return _data[_dp];
} }
~brainfuck()
{ delete[] _data; }
}; };
template<typename functor> template<typename functor>
void match(functor f, int sp, size_t& index, const std::string& program){ void match(functor f, int sp, size_t& index, const std::string& program)
{
while (f(index) < program.size()){ while (f(index) < program.size())
{
if (program[index] == '[') if (program[index] == '[')
sp++; sp++;
if (program[index] == ']') if (program[index] == ']')
@ -85,9 +94,11 @@ int main()
brainfuck fuck; brainfuck fuck;
size_t index = 0; size_t index = 0;
while (index < program.size()){ while (index < program.size())
{
auto c = program[index]; auto c = program[index];
switch (c){ switch (c)
{
case '>': case '>':
fuck.increment_dp(); fuck.increment_dp();
break; break;
@ -108,11 +119,11 @@ int main()
break; break;
case '[': case '[':
if (fuck.is() == 0) if (fuck.is() == 0)
match([](size_t& idx){return ++idx;}, 1, index, program); match([](size_t& idx) { return ++idx; }, 1, index, program);
break; break;
case ']': case ']':
if (fuck.is() != 0) if (fuck.is() != 0)
match([](size_t& idx){return --idx;}, -1, index, program); match([](size_t& idx) { return --idx; }, -1, index, program);
break; break;
default: default:
break; break;