This question already has an answer here:
- Incrementing Numbers, Over Multiple Sessions 23 answers
In a programming language of your choice, write a full program that, when run, prints a positive integer N and then modifies its own source file such that the next time it is run it will print N+1.
For example, this (ungolfed) Python 3 program satisfies this behavior:
N = 1 print(N) with open(__file__, 'r+') as f: N = int(f.readline()[4:]) + 1 code = 'N = ' + str(N) + '\n' + f.read() f.seek(0) f.write(code)
Right away it declares and prints N, then it opens itself and rewrites its first line so the declared value of N is incremented. Then it copies the rest of its code verbatim and writes the new code to the same file, resulting in a program that will print N+1 when run again.
If the file were named
incr.py, running it on the command line would look something like this:
C:\somepath> python incr.py 1 C:\somepath> python incr.py 2 C:\somepath> python incr.py 3 C:\somepath> python incr.py 4
At this point,
incr.py would read:
N = 5 print(N) with open(__file__, 'r+') as f: N = int(f.readline()[4:]) + 1 code = 'N = ' + str(N) + '\n' + f.read() f.seek(0) f.write(code)
Your program should behave essentially the same as this Python example, though of course your program structure may be very different, even changing as N increases. (You don't need to define N as a plain integer on the first line, for example.)
Give the program that prints
1 in your answer. Programs for all higher N can then be inferred. The shortest
1-printing program in bytes wins.
The output should be the sole number N in decimal (or your language's most natural base), followed optionally by a trailing newline.
Your program must actually rewrite its own source code file, not simply output its modified source like a quine.
The file name and/or path of the source file may be hardcoded into your program (e.g.
'incr.py'could have replaced
__file__in the Python example) but the program's behavior should not depend on them. If the file is moved or renamed it should be easy enough to rewrite the program accordingly.
The source file's name and path should not change during execution.
Temporary files may be made (to copy code to or whatever) but they should be removed before the main program ends. Specifically, the only side effects of running your program should be:
Printing N to stdout.
Changing the source file so it will print N+1 when next run.