Skip to content

Instantly share code, notes, and snippets.

@plasma-effect
Created August 26, 2014 04:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plasma-effect/285f7c03d2b585ceff23 to your computer and use it in GitHub Desktop.
Save plasma-effect/285f7c03d2b585ceff23 to your computer and use it in GitHub Desktop.
// Copyright plasma_effect 2014.
// Distributed under the Boost Software License, Version 1.0.
//(See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include<stdexcept>
#include<stack>
namespace plasma_brain
{
template<class InputIterator,class BidirectionalIterator,class InputStream,class OutputStream>
void brein_f(
InputIterator code_begin,
InputIterator code_end,
BidirectionalIterator memory_begin,
BidirectionalIterator memory_end,
InputStream& input_stream,
OutputStream& output_stream)
{
auto memory_ite = memory_begin;
std::stack<InputIterator> loop_stack;
for (auto code_ite = code_begin; code_ite != code_end; ++code_ite)
{
if (*code_ite == '>')
{
++memory_ite;
if (memory_ite == memory_end)
throw std::out_of_range(R"(brainf**k exception: ">" memory iterator cant point to end of memories)");
}
else if (*code_ite == '<')
{
if (memory_ite == memory_begin)
throw std::out_of_range(R"(brainf**k exception: "<" memory iterator cant point to back of begin of memories)");
--memory_ite;
}
else if (*code_ite == '+')
{
++(*memory_ite);
}
else if (*code_ite == '-')
{
--(*memory_ite);
}
else if (*code_ite == '.')
{
output_stream << (*memory_ite);
}
else if (*code_ite == ',')
{
input_stream >> (*memory_ite);
}
else if (*code_ite == '[')
{
if (*code_ite == '\0')
{
int N = 1;
while (N != 0)
{
++code_ite;
if (code_ite == code_end)
throw std::out_of_range(R"(brainf**k exception: "[" dont find "]")");
if (*code_ite == '[')
{
++N;
}
else if (*code_ite == ']')
{
--N;
}
}
}
else
{
loop_stack.push(code_ite);
}
}
else if (*code_ite == ']')
{
if (loop_stack.empty())
throw std::out_of_range(R"(brainf**k exception: "]" dont find "[")");
auto next_iterator = loop_stack.top();
loop_stack.pop();
if (*memory_ite != '\0')
{
code_ite = next_iterator;
loop_stack.push(next_iterator);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment