Tuesday, March 3, 2015

Incrementing a three digit number in the range [000-998] in Brainf*ck

I was solving a programming problem on SPOJ.com (CRYPTO2). The task was this:

You are given a three digit number. You have to add 1 to it and display the result. But you have to submit the solution in brainf*ck.

If we had to do it in C way, we would have come up with a code like this:

#include <stdio.h>

int main(int argc, char **argv)
{
 int a[] = {4,9,9};
 if(a[2]==9){
  a[2] = 0;
  if(a[1]==9){
   a[1] = 0;
   a[0]++;
  }else a[1]++;
 }else a[2]++; 
 for(int i=0;i<3;++i)printf("%d",a[i]);
 return 0;
}

Translating it to BrainF*uck, it becomes:

Memory cells store these values sequentially:

flag
48 n1
48 n2 n2 n2 9 flag
48 n3 n3 n3 9 flag
48 48 48

Code:

+>
++++++++++++++++++++++++++++++++++++++++++++++++>,<[->-<]
>>
++++++++++++++++++++++++++++++++++++++++++++++++>,<[->-<]
> [->+>+<<] >>> +++++++++ <[->-<] >> +(F)
<[[-]>-<]>>
++++++++++++++++++++++++++++++++++++++++++++++++>,<[->-<]
> [->+>+<<] >>> +++++++++ <[->-<] >> +(F) 
<[[-]<<+>>>-<]>(back at flag)

[- <<<[-] <<<[- <<<[-] <<<+<<->>>>>>>>]<<<<<<<<[->>>>>+<<<<<]>>>>>>>> >>>>>>]

>
++++++++++++++++++++++++++++++++++++++++++++++++[<<<<<<<<<<<<<+>>>>>>>>>>>>>-]
<<<<<<<<<<<<<.
>>>>>>>>>>>>>>
++++++++++++++++++++++++++++++++++++++++++++++++[<<<<<<<<<<<+>>>>>>>>>>>-]
<<<<<<<<<<<.
>>>>>>>>>>>>
++++++++++++++++++++++++++++++++++++++++++++++++[<<<<<<+>>>>>>-]
<<<<<<.


No comments:

Post a Comment