This is an interesting one.
I have written a short program in objective-c to encode a string into a brainf_ck string, this is what it looks like:
NSString *input; // set this to your input string
NSMutableString *output = [[NSMutableString alloc] init];
int currentPosition = 0;
for (int i = 0; i<[input length]; i++) {
int charPos = [input characterAtIndex:i];
int amountToGo = charPos-currentPosition;
if (amountToGo > 0) {
for (int b = 0; b<amountToGo; b++) {
[output appendString:@"+"];
}
}
else {
int posVal = abs(amountToGo);
for (int b = 0; b<posVal; b++) {
[output appendString:@"-"];
}
}
currentPosition += amountToGo;
[output appendString:@"."];
}
NSLog(@"%@", output);
[output release];
Now I could ask you to optimize that code.
Or, I could ask you to optimize the bf code it produces?
EXAMPLE: Output of 'Hello World!' from my code (365 chars)
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.-------------------------------------------------------------------------------.+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++.+++.------.--------.-------------------------------------------------------------------.
EXAMPLE 2: Now, looking at that code, I could probably shorten it by putting reset to zeros in, for a start... (290 chars - 75 improvement)
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.[-]++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++.+++.------.--------.[-]+++++++++++++++++++++++++++++++++.
But this takes it a step further... output of 'Hello World!' from some sample code I found on the internet: (111 chars, 179 on last, 254 on original!)
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.
Now, I don't know how that loop works, but it does. My question is this:
- Explain how the loop in the last example works.
- Write some code that can turn any string into highly optimized brainf_ck, like the last example.