B2C
Jump to navigation
Jump to search
It's Brainfuck, with 2 cells, invented by User:None1.
Introduction
B2C is a Brainfuck derivative (or a Brainfuck equivalent, depends on how you think) with only 2 cells.
Since there are only 2 cells, B2C doesn't need 2 commands to move the pointer, it just need one command, which is the | command. The | command moves the pointer from one cell to the other.
Example Programs
Cat Program
+[,.] [The same as the one in Brainfuck]
Non-terminating version
+[|,.|]
Nope. Interpreter
++++++[|+++++++++++++|-]|.[-]|++++++++++[|+++++++++++|-]|+.+. -----------.[-]|+++++[|+++++++++|-]|+.
Hello World (last because it's the hardest one)
+++++++++[|++++++++|-]|.[-]|++++++++++[|++++++++++|-]|+. +++++++..+++.[-]|++++++++[|++++|-]|.[-]| ++++++++++[|++++++++|-]|+++++++.[-]|+++++++++++[|++++++++++|-]| +.+++.------.--------.[-]+++++++++++[|+++|-]|.
Interpreter
The following is an interpreter in JavaScript:
function b2c(program,input){ var stack=[]; var matches={}; var ip=0; var tape=[0,0]; var p=0; var output=''; for(var i=0;i<program.length;i++){ if(program[i]=='['){ stack.push(i); } if(program[i]==']'){ if(stack.length==0){ throw new Error('Right bracket does not match left bracket'); } var mt=stack.pop(); matches[mt]=i; matches[i]=mt; } } if(stack.length!=0){ throw new Error('Left bracket does not match right bracket'); } while(ip<program.length){ if(program[ip]=='+'){ tape[p]=tape[p]+1; if(tape[p]==256) tape[p]=0; ip=ip+1; } if(program[ip]=='-'){ tape[p]=tape[p]-1; if(tape[p]==-1) tape[p]=255; ip=ip+1; } if(program[ip]=='|'){ p=1-p; ip=ip+1; } if(program[ip]==','){ if(input==''){ tape[p]=0; }else{ tape[p]=input.charCodeAt(0)%256; input=input.slice(1); } ip=ip+1; } if(program[ip]=='.'){ output+=String.fromCharCode(tape[p]); ip=ip+1; } if(program[ip]=='['){ if(tape[p]==0){ ip=matches[ip]; }else{ ip=ip+1; } } if(program[ip]==']'){ if(tape[p]!=0){ ip=matches[ip]; }else{ ip=ip+1; } } if(!('+-,.[]|'.includes(program[ip]))){ ip=ip+1; } } return output; }
The minimized version is like this:
function b2c(r,t){for(var e=[],o={},h=0,n=[0,0],c=0,a="",f=0;f<r.length;f++)if("["==r[f]&&e.push(f),"]"==r[f]){if(0==e.length)throw new Error("Right bracket does not match left bracket");var i=e.pop();o[i]=f,o[f]=i}if(0!=e.length)throw new Error("Left bracket does not match right bracket");for(;h<r.length;)"+"==r[h]&&(n[c]=n[c]+1,256==n[c]&&(n[c]=0),h+=1),"-"==r[h]&&(n[c]=n[c]-1,-1==n[c]&&(n[c]=255),h+=1),"|"==r[h]&&(c=1-c,h+=1),","==r[h]&&(""==t?n[c]=0:(n[c]=t.charCodeAt(0)%256,t=t.slice(1)),h+=1),"."==r[h]&&(a+=String.fromCharCode(n[c]),h+=1),"["==r[h]&&(0==n[c]?h=o[h]:h+=1),"]"==r[h]&&(0!=n[c]?h=o[h]:h+=1),"+-,.[]|".includes(r[h])||(h+=1);return a}