Skip to content

Instantly share code, notes, and snippets.

@Earlz
Created November 15, 2017 01:43
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 Earlz/0b9e603952bbff664d40694f4a0cf6ad to your computer and use it in GitHub Desktop.
Save Earlz/0b9e603952bbff664d40694f4a0cf6ad to your computer and use it in GitHub Desktop.
//compiles to 2820 bytes unoptimized, 1524 optimized
//using remix version "soljson-v0.4.18+commit.9cf6e910.js"
pragma solidity ^0.4.15;
contract BrainFucker{
function interpret(bytes s, bytes1[128] input) public returns (bytes1[128] output) {
uint256 ptr=0;
uint256 i=0;
uint256 right = s.length;
uint256 BUFSIZE=1000;
uint256 loop;
bytes memory buf = new bytes(1000);
uint256 inpos = 0;
uint256 outpos = 0;
while(i < right){
bytes1 c = s[i];
if(c == '>'){
ptr++;
if(ptr >= BUFSIZE){
ptr = 0;
}
}else if(c == '<'){
ptr--;
if(ptr < 0){
ptr = BUFSIZE-1;
}
}else if(c == '+'){
buf[ptr] = bytes1(uint8(buf[ptr]) + 1);
}else if(c == '-'){
buf[ptr] = bytes1(uint8(buf[ptr]) - 1);
}else if(c == '['){
if(buf[ptr] == 0){
loop = 1;
while(loop > 0){
i++;
c = s[i];
if(c == '['){
loop++;
}else if(c == ']'){
loop--;
}
}
}
}else if(c == ']'){
loop = 1;
while(loop > 0){
i--;
c = s[i];
if(c == '['){
loop--;
}else if(c == ']'){
loop++;
}
}
i--;
}else if(c == '.'){
output[outpos] = buf[ptr];
outpos++;
}else if(c == ','){
buf[ptr] = input[inpos];
inpos++;
}
i++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment