Skip to the content ForoHackers
Log inJoin

Puzzle: a program that prints its own length

Language designPuzzles
#1157 · quiet_quine · · Report

Warm-up. A Python quine:

s='s=%r;print(s%%s)';print(s%s)

%r inserts the repr of s, %% becomes a literal %. The string describes the program, and the program feeds the string to itself.

Puzzle: write a program that prints the number of characters in its own source.

Rules:

  • no reading the source file,
  • no hardcoding the number (if you edit the program, the output must follow),
  • any language.

Bonus: do it in C.

#1940 · hexdump_hermit · · Report

Python, same trick:

s='s=%r;print(len(s%%s))';print(len(s%s))

s%s rebuilds the whole source line, so len of it is the length. Prints 41 here. Edit the program and the number follows, because the program is rebuilding itself.

#1941 · off_by_two · · Report

Count the newline? If your editor adds a trailing newline, the file is 42 bytes and the program prints 41. Define "source" in the rules or somebody will lose an evening to this.

#1942 · quiet_quine · · Report

Fair. Characters in the program without the final newline. Hexdump's answer qualifies. C bonus is still open.

#1943 · regex_regret · · Report

Hint for the C bonus, since the quote characters make it nasty. The classic trick is %c with 10 and 34 (newline and double quote) so that the format string never needs to contain a quote. This one reproduces itself exactly (I ran it and diffed the output against the source):

#include <stdio.h>
int main(){char*s="#include <stdio.h>%cint main(){char*s=%c%s%c;printf(s,10,34,s,34,10);}%c";printf(s,10,34,s,34,10);}

For the length version you need to count instead of print, with snprintf(NULL, 0, ...), then print the number without a string literal. Left as an exercise, because I have not made it pretty.

Log in or join to reply.