Monday, 28 September 2015

computer puzzle - ‘‘Loopy’’ C loop


What is the smallest number of non-space characters that can be added in order to change the following code into a complete C program that prints  LoopyLoopyLoopyLoopy?


#include
main(){
<-- ^
| @ |
v --> printf("Loopy");}


Starts as: 5 lines with no leading spaces, totaling 52 non-space characters and 5 within-line spaces.


Possible edits (additions that don't move the original characters):
•   Single non-space characters may replace any of the 5 original spaces.
•   Spaces and non-space characters may be added to the ends of lines.


No-nos and pedantry:
•   No commenting.
•   No additional " quotation marks.
•   No new lines. (Intended, but not made explicit, in the original puzzle statement.)
•   All syntax should abide by The C Programming Language, 2nd Edition, Kernighan & Ritchie.
•   If any variables are used before they are initialized, the program should be successful with any initial values for those variables.



Notes about the original puzzle statement: The word visible was used instead of instead of non-space. Adding lines was unintentionally allowed as a newline would count as a character added to the end of an existing line. The line #include could have been left out for a more streamlined version of essentially the same puzzle, as mentioned by Arkku.



Answer




In accordance with the updated rules:



#include
main(){int v=4;for('\
<-- ^\
| @ |';v;)
v --> printf("Loopy");}



The original rules (in effect at the time of posting this) unintentionally permitted adding a newline character to the end of a line, which enabled:



#include
v;
main(){for(;-8
<--v^0;'\
| @ |')
v --> printf("Loopy");}

(16 if adding a newline character to end of line counts as space, 17 if it counts as a non-space.)




Note: The type of the global v defaults to int and is implicitly initialized to zero in ANSI C (the standard at the time of K&R 2nd edition) due to static duration.




If it were permitted to insert a single non-space character between two non-space characters:



#include
main(v){for(;-8
<--v^0;'\
| @ |')

v --> printf("Loopy");}

This with the caveat:



The program must be run without arguments in an environment that passes 1 as the initial argument of main in that case. (As discussed in comments, this is permitted.)



No comments:

Post a Comment

Understanding Stagnation point in pitot fluid

What is stagnation point in fluid mechanics. At the open end of the pitot tube the velocity of the fluid becomes zero.But that should result...