Skip to content

Instantly share code, notes, and snippets.

@kausality
Created October 18, 2011 18:00
Show Gist options
  • Save kausality/1296150 to your computer and use it in GitHub Desktop.
Save kausality/1296150 to your computer and use it in GitHub Desktop.
a string to braifuck converter
/*A stupid str2bf converter!*/
#include <stdio.h>
#define MAX 100
int win=10;
char cell[MAX]={0};
int curr=0;
/*Find a number as a multiple of ten */
void divmod(int num,int *div,int *mod)
{
*div=num/10;
*mod=num%10;
}
/*Finds a cell closer then 10 cells away which has a value near to the value which you have to print*/
int find_closest(int *val,int *pos,char c)
{
int i,flag=0;
for(i=curr-10;i<curr+10;i++){
if(cell[i]-c<=10 && cell[i]-c>=-10){
*val=cell[i]-c;
*pos=i;
flag=1;
break;
}
}
if(!flag)
return 0;
return 1;
}
/*Moves to an empty cell*/
void on_empty_cell()
{
while(cell[curr]){
putchar('>');
curr++;
}
}
void bf_gen(char c)
{
int div,mod;
int s,i,tmp;
int seek,seek_ptr,pos,val;
int win_cell;
char t,mutate;
divmod(c,&div,&mod);
/*Suppose you have to print 'b' and the value of just the previous cell is 'a' then you
*don't need to reduntatly generate a loop for it all you have to do is:-
*<+. and BANG!
*This is what this piece of code does
*/
if(find_closest(&val,&pos,c)){
seek=(curr<pos)?pos-curr:curr-pos;
seek_ptr=(curr<pos)?'>':'<';
curr=pos;
for(i=0;i<seek;i++)
putchar(seek_ptr);
mutate=(val<0)?'+':'-';
val=(val<0)?-val:val;
for(i=0;i<val;i++){
putchar(mutate);
if(mutate=='-')cell[curr]--;
else cell[curr]++;
}
}
/*This block generate a loop,if the character has value 65,then it will div mod by 10 to get 6 & 5
* now simply we can generate a loop like
* ++++++++++[>++++++<-]>. BANG!
* Now that is what this long block do!
*/
else{
on_empty_cell();
win_cell=curr;
for(i=0;i<win;i++){
putchar('+');cell[curr]++;
}
s=tmp=curr;
putchar('[');
on_empty_cell();
for(i=0;i<div;i++)
putchar('+');
for(i=0;i<win*div+mod;i++)
cell[curr]++;
tmp=s;
for(;tmp<curr;tmp++)
putchar('<');
putchar('-');cell[win_cell]--;
putchar(']');
tmp=s;
for(;tmp<curr;tmp++)
putchar('>');
for(i=0;i<mod;i++)
putchar('+');
}
putchar('.');
}
int main()
{
char str[50];
char *p=str;
fgets(str,sizeof(str),stdin);
while(*p){
bf_gen(*p);
p++;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment