47
\$\begingroup\$

Your task is to write a full program that will continue to count down from 10 every time it is run.

  • The first time you run the program, it should print 10.
  • The next time, it should output 9.
  • The next time, it should output 8, and so on.
  • Instead of printing 0, the program should crash. You do not have to handle the program running any more times after that.
  • Any facilities used for storage may be assumed to be empty before the first execution of the program.

Here's an example implementation in Python 3:

try:f=open("a","r+");v=int(f.read())
except:f=open("a","w");v=10
1/v
print(v)
f.seek(0)
f.write(str(v-1))

This is , so the shortest answer (measured in bytes) wins.

\$\endgroup\$
7
  • 12
    \$\begingroup\$ What does crashing entail? \$\endgroup\$ Commented Dec 16, 2016 at 3:04
  • 2
    \$\begingroup\$ @ConorO'Brien Hmm... this hasn't been discussed in meta? \$\endgroup\$ Commented Dec 16, 2016 at 3:05
  • 2
    \$\begingroup\$ @Challenger5 Not that I know of. Would throwing an error be sufficient? \$\endgroup\$ Commented Dec 16, 2016 at 3:11
  • 1
    \$\begingroup\$ @ConorO'Brien Yes. \$\endgroup\$ Commented Dec 16, 2016 at 3:12
  • \$\begingroup\$ Related. \$\endgroup\$ Commented Dec 18, 2016 at 19:42

30 Answers 30

35
\$\begingroup\$

Perl on Linux, 17 bytes

I thought it might be interesting to create a program that doesn't maintain any state itself, and doesn't modify its own source code; in other words, it actually checks how often it's been run by asking the OS. The question says "Any facilities used for storage may be assumed to be empty before the first execution of the program.", and thus we'd want to start from a completely blank OS. As such, I'd better explain just how you go about doing that, as otherwise testing the program is difficult.

There are actually two ways to set up for running the program. Either way, the minimal OS for the purpose would be running nothing but a shell (to enable us to run Perl in turn), and the simplest possible shell at that (so that it doesn't do anything fancy that makes the OS non-blank). /bin/dash is a good choice here, as it was intended as a minimal shell for system recovery. Then, we need to start Linux in such a way that it's running nothing but dash. We can either do this by rebooting the computer with init=/bin/dash on the Linux command line so that it starts nothing besides dash, or (much more conveniently) creating a Linux container using unshare -Urfp /bin/dash in a terminal (unshare doesn't actually create a blank OS, but it does simulate one; notably, the inside of the container thinks it's root, dash thinks it's init, etc., just as would happen on an actual blank OS). Disclaimer: I haven't actually tested this on bare metal yet, only inside unshare, but it should work both ways in theory.

Finally, once we've got that set up, we simply have to look at the PID; as we're on a blank system, the init system (here, the shell) will have PID 1, so the executions of Perl will have PIDs from 2 up to 12 inclusive. So our program looks like this:

say 12-$$||die

Here's a sample run:

$ unshare -Urfp /bin/dash
# perl -E 'say 12-$$||die'
10
# perl -E 'say 12-$$||die'
9
# perl -E 'say 12-$$||die'
8
# perl -E 'say 12-$$||die'
7
# perl -E 'say 12-$$||die'
6
# perl -E 'say 12-$$||die'
5
# perl -E 'say 12-$$||die'
4
# perl -E 'say 12-$$||die'
3
# perl -E 'say 12-$$||die'
2
# perl -E 'say 12-$$||die'
1
# perl -E 'say 12-$$||die'
Died at -e line 1.
#
\$\endgroup\$
2
  • \$\begingroup\$ What OS are you running this on? I'm on Ubuntu Linux 14.04, and unshare doesn't support any of the flags -Urfp. \$\endgroup\$
    – isaacg
    Commented Dec 19, 2016 at 10:29
  • \$\begingroup\$ @isaacg: Ubuntu 16.04. unshare is pretty new (it's an interface to an OS feature that's also pretty new) and the bugs only really got ironed out over the last year or so. If you're using a 2½-year-old version, it's unsurprising that it's very limited in functionality. \$\endgroup\$
    – user62131
    Commented Dec 19, 2016 at 15:01
18
\$\begingroup\$

6502 machine language + Apple ][+ ROM, 12 (11? 10? 9?) bytes

CE 06 80 F0 01 A2 0B A9 00 4C 24 ED

Should start at $8000. Crashes to the system monitor when the count reaches 0.


C6 B6 F0 01 A2 0B A9 00 4C 24 ED

Should start at $B1. This saves a byte since I can use the (two-byte) zero-page version of DEC, but overwrites the critical Applesoft routine CHRGET; you'll need to load it and call it from the monitor, and use CTRL+BReturn to re-initialize BASIC once you're done. Not sure if this invalidates it or not.


CE 06 80 F0 01 A2 0B 4C 26 ED

Should start at $8000. This doesn't initialize $9E, saving two bytes. However, this means you must not call it with a negative address (or, if you call it from the monitor, you have to call the monitor with a positive address). If you do, Applesoft's CALL routine will store FF in $9E, causing it to add 65280 to the number when printing it. Again, not sure if this invalidates the solution or not.


C6 B6 F0 01 A2 0B 4C 26 ED

Should start at $B1. This is a combination of the above two programs, saving a total of three bytes; you'll have to call the monitor with a positive address, load it and run it from there, and use Ctrl+BReturn to re-initialize BASIC once you're done.


Note that these programs only modify the program in memory; re-loading the program from disk will reset the countdown. This works because the Apple ][ (and ][+, //e, and //c) have no memory protection system whatsoever; the program (and its self-modifications) will stay in memory even after it exits, so you can keep running it from memory until you overwrite that memory with something else.


Sample run

]BLOAD COUNT THEN BRK
]CALL 32768
10
]CALL 32768
9
]CALL 32768
8
]CALL 32768
7
]CALL 32768
6
]CALL 32768
5
]CALL 32768
4
]CALL 32768
3
]CALL 32768
2
]CALL 32768
1
]CALL 32768

8008-    A=80 X=9D Y=00 P=36 S=EE
*

Explanation

     DEC NUM+1  ; Decrement the LDX instruction's operand
     BEQ NUM+1  ; If it is now zero, branch to it; 00 is the opcode for the BRK instruction, which causes the program to crash to the monitor
NUM  LDX #$0B   ; Load the X register with 0x0A; the operand has already been decremented once
     LDA #$00   ; Load the accumulator with 0
     JMP $ED24  ; Jump to $ED24, an Applesoft ROM routine which prints A (high byte),X (low byte) in decimal

Explanation of 10 byte version

     DEC NUM+1  ; Decrement the LDX instruction's operand
     BEQ NUM+1  ; If it is now zero, branch to it; 00 is the opcode for the BRK instruction, which causes the program to crash to the monitor
NUM  LDX #$0B   ; Load the X register with 0x0A; the operand has already been decremented once
     JMP $ED26  ; Jump to $ED26, which is two bytes into the Applesoft routine at $ED24. The two skipped bytes would store the accumulator in $9E

Variants

Prints ERR and beeps when count reaches 0

Normal - 15 bytes

CE 06 80 F0 07 A2 0B A9 00 4C 24 ED 4C 2D FF

Overwrites CHRGET - 14 bytes

C6 B6 F0 07 A2 0B A9 00 4C 24 ED 4C 2D FF

Doesn't initialize $9E - 13 bytes

CE 06 80 F0 05 A2 0B 4C 26 ED 4C 2D FF

Overwrites CHRGET and doesn't initialize $9E - 12 bytes

C6 B6 F0 05 A2 0B 4C 26 ED 4C 2D FF

Freezes when count reaches 0

Normal - 12 bytes

CE 06 80 F0 FE A2 0B A9 00 4C 24 ED

Overwrites CHRGET - 11 bytes

C6 B6 F0 FE A2 0B A9 00 4C 24 ED

Doesn't initialize $9E - 10 bytes

CE 06 80 F0 FE A2 0B 4C 26 ED

Overwrites CHRGET and doesn't initialize $9E - 9 bytes

C6 B6 F0 FE A2 0B 4C 26 ED
\$\endgroup\$
6
  • \$\begingroup\$ I'm not sure I understand this .. Wouldn't this be the same as having a function in Python that decrements a global variable and only works if executed in the shell? Is that allowed? What I mean is, isn't it normally expected for a program to leave the memory at some point, to be reloaded again later? \$\endgroup\$ Commented Dec 16, 2016 at 13:52
  • 3
    \$\begingroup\$ @redstarcoder No - the Apple II has literally no memory allocation system; you can store anything anywhere in RAM and it will stay accessible by any program until it's overwritten with another value. \$\endgroup\$ Commented Dec 16, 2016 at 14:19
  • \$\begingroup\$ @inset_name_here, I'm not sure how it being accessible anywhere in RAM changes anything. Could you run other programs reliably and still run this program later? Maybe I'm not familiar enough with the rules around here to fully understand, so I'll just drop it. I just expect a full program to persist through reboots and be able to run fine usually if other programs are run in between its executions, but I don't know what the community rules a full program to be. \$\endgroup\$ Commented Dec 16, 2016 at 14:41
  • 1
    \$\begingroup\$ @redstarcoder the general consensus is that the program is run on a development computer with nothing but the required software and not doing anything else in the mean time. \$\endgroup\$ Commented Dec 16, 2016 at 16:15
  • 1
    \$\begingroup\$ 8 bytes if you run from $6E instead: C6 75 F0 03 4C 22 ED 0B \$\endgroup\$ Commented Mar 16, 2018 at 21:00
14
\$\begingroup\$

Bash + sed, 41 40 38 bytes

echo $[n=10/1]
sed -i s/$n/$[n-1]/g $0

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ The TIO link has a header and footer, don't those add to byte count? \$\endgroup\$
    – Pavel
    Commented Dec 16, 2016 at 3:50
  • 2
    \$\begingroup\$ No, those are just to run the program 11 times. \$\endgroup\$
    – Dennis
    Commented Dec 16, 2016 at 3:52
  • \$\begingroup\$ I get sed: invalid option -- '/'. sed (GNU sed) 4.2.2 \$\endgroup\$
    – shrx
    Commented Dec 16, 2016 at 8:36
  • \$\begingroup\$ @shrx Huh. I have the same version of sed locally and on TIO, and they don't show that error. \$\endgroup\$
    – Dennis
    Commented Dec 16, 2016 at 14:01
9
\$\begingroup\$

Javascript, 42 bytes

y=localStorage;y.a=y.a||10;alert(y.a--||a)

Test it out with this fiddle - be sure to clear your local storage to reset the countdown.

Thanks to steenbergh, Lmis, and obarakon for lots of bytes!

\$\endgroup\$
9
  • \$\begingroup\$ y=localStorage;y.a=y.a||10;alert(y.a>0?y.a--:a) can save you a byte. \$\endgroup\$
    – Oliver
    Commented Dec 16, 2016 at 17:01
  • \$\begingroup\$ You can use sessionStorage to test with an easier reset (just use a fresh tab) but of course +2 bytes. \$\endgroup\$
    – Kevin Reid
    Commented Dec 17, 2016 at 15:22
  • \$\begingroup\$ Ouch, sorry, i just saw your answer, i ended up doing almost the same. If you want to, you can use l=localStorage;l.l=-~l.l;alert(10-l.l||l) to save a byte, i'd delete mine \$\endgroup\$
    – C5H8NNaO4
    Commented Dec 18, 2016 at 1:30
  • \$\begingroup\$ @Mego Of course :) I don't see a console.log here, but i'd prefer that either \$\endgroup\$
    – C5H8NNaO4
    Commented Dec 18, 2016 at 17:09
  • 1
    \$\begingroup\$ @obarakon Yep, and Boolean short-circuiting prevents the a from evaluating when the value in localstorage isn't 0. \$\endgroup\$
    – user45941
    Commented Dec 19, 2016 at 18:40
9
\$\begingroup\$

Dyalog APL, 33 28 22/20? bytes

I am not sure if this is valid, as it consists of a function (which must be called with a dummy argument). However, all APL programs (purely functional or not) have the same status, and indeed some APL versions do not have traditional programs, only functions. In compensation, I have added two bytes to name it, although that is not necessary for the desired effect.

f←{6::⊢c∘←10⋄÷÷c∘←c-1}

Note that this relies on an unofficial quirk, that ∘← assigns globally.

6:: upon any value error

⊢c return c

∘←10 which is globally set to 10

now

÷÷c return the twice inverted (errors on zero) c

∘← which is globally set to

c-1 one less than c

TryAPL online!


Certainly valid 28 byte version:

f
⍎'c←11'/⍨0=⎕NC'c'
⊢c←÷÷c-1

Works by setting c to 11 if missing, then subtracting 1 from c, inverting twice (which gives div-by-zero error if c-1 is 0), assigning to c, and outputting the new value.


Old 33 byte version:

f
÷÷≢2↓r⊣⎕FX¯1↓r←⎕NR'f'
    
    
    
    
    
    
    
    
    

Works by redefining itself on each run, but with one less trailing newline. Outputs the twice inverted number of remaining lines (less two), thus giving a div-by-zero error when only two lines are left (the header and the actual code).

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Er... why are there so many newlines? \$\endgroup\$
    – user41805
    Commented Dec 16, 2016 at 9:50
  • 4
    \$\begingroup\$ @KritixiLithos The program redefines itself with one less line for each run. \$\endgroup\$
    – Adám
    Commented Dec 16, 2016 at 10:21
8
\$\begingroup\$

C#, 197 160 159 125 bytes

namespace System.IO{class P{static void Main(){int n=11;for(;File.Exists(""+--n););File.Create(""+n);Console.Wr‌​ite(n*n/n);}}}

Saved 34 bytes thanks to milk

And a formatted version (With ReadKey added so you can view the output):

namespace System.IO
{
    class P
    {
        static void Main()
        {
            int n=11;
            for(;File.Exists(""+--n););
            File.Create(""+n);
            Console.Wr‌​ite(n*n/n);
        }
    }
}

It is longer than I thought it would be so there's probably room for golfing.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ File.Exists and File.Create instead of ReadAllText and WriteAllText. Just check if a filename exists, don't both with the file contents. Also, namespace System.IO and you can remove the namespace from System.Console.Write. 125 bytes: namespace System.IO{class P{static void Main(){var n=11;for(;File.Exists(""+--n););File.Create(""+n);Console.Write(n*n/n);}}} \$\endgroup\$
    – milk
    Commented Dec 16, 2016 at 19:57
  • \$\begingroup\$ @milk Thanks a lot! Can't believe I didn't think of using the filename only though! And I didn't know about that namespace trick, awesome. \$\endgroup\$ Commented Dec 17, 2016 at 9:25
7
\$\begingroup\$

Perl, 37 36 bytes

9=~//;print$'-sysopen$~,$0,print$'+1

Crashes when the initial value reaches -1 (which would have printed 0), as it writes over the =~ operator.

Saved a byte using sysopen rather than open. This allows me to print to STDOUT first, using the return value as the file mode (1, a.k.a. O_WRONLY), before $~ is reassigned.

Sample Usage

$ perl crash-off.pl
10
$ perl crash-off.pl
9
$ perl crash-off.pl
8

...

$ perl crash-off.pl
2
$ perl crash-off.pl
1
$ perl crash-off.pl
syntax error at crash-off.pl line 1, near "1~"
Execution of crash-off.pl aborted due to compilation errors.
\$\endgroup\$
6
\$\begingroup\$

Perl 6,  60  58 bytes

put 10-$=finish.lines||die;
$*PROGRAM.open(:a).put;
=finish
 
open($*PROGRAM,a=>put 10-$=finish.lines||die).put
=finish
 

Needs newline character after =finish.

die can be replaced with 1/0.

Explanation:

It gets a list of lines after =finish ($=finish.lines) subtracts that from 10, and if the result isn't 0 it prints it, otherwise it dies.

The last thing it does is open itself in append mode, and add another line to the end.

\$\endgroup\$
4
  • \$\begingroup\$ Permalink for those who don't have Perl 6. \$\endgroup\$
    – Dennis
    Commented Dec 16, 2016 at 3:26
  • \$\begingroup\$ @Dennis At least that one isn't as far out of date as what Ideone has ( run say $*PERL.compiler.version ) \$\endgroup\$ Commented Dec 16, 2016 at 4:54
  • 1
    \$\begingroup\$ 2014.7... wow! Is 2016.11 very different from 2016.7? If so, I can build it from source. \$\endgroup\$
    – Dennis
    Commented Dec 16, 2016 at 5:29
  • \$\begingroup\$ @Dennis The official release of Perl 6 was 2015-12-25. There was a big change in late 2015 called The Great List Refactor (GLR), so getting code to also work on 2014.7 is almost impossible. Most of what's been happening in 2016 is performance related, though there have been plenty of edge condition fixes. Most of the golfed code here should work on anything after the 2015.12 release of Rakudo. So I think v2016.07 is fine. \$\endgroup\$ Commented Dec 16, 2016 at 14:23
6
\$\begingroup\$

Python 2, 65 bytes

f=open(__file__,"r+")
x=75-len(f.read())
x/x
print x
f.write('#')

Inspired by L3viathan's answer.

Can be reduced to 60 bytes if you can choose to name the file a single character like x and then replace __file__ with 'x'. In that case, replace 75 with 70.

\$\endgroup\$
2
  • \$\begingroup\$ @Flp.Tkc yes, but isn't that the same number of bytes? \$\endgroup\$
    – Alex Hall
    Commented Dec 17, 2016 at 11:20
  • \$\begingroup\$ oh, that's true :P \$\endgroup\$
    – FlipTack
    Commented Dec 17, 2016 at 11:28
4
\$\begingroup\$

Jolf, 20 bytes

γ-@▲lqΈ?␡γ?γaγ0₯I₯C1

Try it here! Errors when 0 is printed. Modifies the code. Explanation to come.

\$\endgroup\$
2
  • \$\begingroup\$ I'm not very familiar with Jolf, but it does not immediately seem to work in the online interpreter. \$\endgroup\$ Commented Dec 16, 2016 at 3:17
  • 1
    \$\begingroup\$ @Challenger5 The language usually only works on firefox. \$\endgroup\$ Commented Dec 16, 2016 at 3:21
4
\$\begingroup\$

Applesoft BASIC, 21 bytes (tokenized)

0  PRINT 9 + 1: CALL 2066: END : OR <CTRL-F><CTRL-H>`

Replace <CTRL-F> and <CTRL-H> with their literal versions. Note that this only modifies the program in memory; re-loading it from the disk will reset the countdown.


Sample run

]RUN
10

]RUN
9

]RUN
8

]RUN
7

]RUN
6

]RUN
5

]RUN
4

]RUN
3

]RUN
2

]RUN
1

]RUN

?SYNTAX ERROR IN 0

Explanation

PRINT 9 + 1 does what you'd expect. CALL 2066 calls the 6502 machine-language routine at memory location 2066, which is after END :. END halts the program so that the machine-language routine (which, to the Applesoft interpreter, is garbage) isn't executed.

The machine-language routine simply decrements the 9 in PRINT 9 + 1. Disassembly:

0812-   CE 06 08    DEC $0806
0815-   60          RTS

After the counter reaches 0, it is "decremented" to /; attempting to run the program will then cause a syntax error.

\$\endgroup\$
4
\$\begingroup\$

*><>, 20 18 bytes

a1Fi:0(?b1-:?:1Fn;

This actually works on Linux (and whatever supports files named \n I guess). It creates a file named \n on first run and outputs 10. It proceeds to output one less number on each subsquent run, except 0 where it crashes instead.

Explanation

a1F                   open file named "\n"
   i:                 recieve input and duplicate it (-1 if empty)
     0(?b             if the file is empty, push 11 to the stack
         1-           subtract one
           :          duplicate the number
            ?:        if the number isn't 0, duplicate it again
              1F      save the number to the file
                n     output the number (crash if non-existant)
                 ;    exit
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Convenient that *><> adds IO \$\endgroup\$ Commented Dec 16, 2016 at 14:08
4
\$\begingroup\$

PHP 57 bytes

echo$n=($f=file(f))?$f[0]:10?:die;fputs(fopen(f,w),--$n);

doesn´t really crash but exit (without counting down) when it hits 0. Is that sufficient?

Run with -r.

\$\endgroup\$
4
\$\begingroup\$

C#, 156 bytes

I golfed @TheLethalCoder's answer for a bit, and was able to save 3 bytes by reordering the statements and eliminating the int.parse(). Still room for improvement, I'm sure.

using System.IO;class P{static void Main(){int n;try{n=File.ReadAllText("f")[0]-48;}catch{n=10;}System.Console.Write(n/n*n);File.WriteAllText("f",""+--n);}}

Ungolfed:

using System.IO;
class P
{
    static void Main()
    {
        int n;
        try
        {
            n = File.ReadAllText("f")[0] - 48;
        }
        catch {
            n = 10;
        }
        System.Console.Write(n / n * n);
        File.WriteAllText("f", "" + --n);
    }
}

Meta-question: It may be hack-y to take TheLethalCoder's work as a starting point for my answer. Would it be better (once I have the rep) to add this as a comment on their answer? I'm not trying to compete with them, I just want to show off my golf, for mutual edification.

\$\endgroup\$
2
  • \$\begingroup\$ People usually leave comments underneath the other persons answer suggesting improvements, however because of the improvements on mine suggested by milk mine is now much different so yours is fine on its own \$\endgroup\$ Commented Dec 17, 2016 at 16:32
  • \$\begingroup\$ I usually go by if they are improvements to someone else's answer comment but if it is different enough to theirs then post your own answer \$\endgroup\$ Commented Dec 17, 2016 at 16:33
3
\$\begingroup\$

Powershell V2.0, 49 bytes

(First ever code golf, couldn't find the rules on how to calculate bytes. I used a String to bytes calculator online)

if(!$n){$n=10;$n}else{$n-=1;if($n-eq0){throw};$n}

Running:

PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
10

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
9

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
8

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
7

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
6

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
5

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
4

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
3

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
2

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
1

____________________________________________________________________________________________________________________________________________________________________
PS C:\Users\***> if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw};$n;}
ScriptHalted
At line:1 char:49
+ if(!$n){$n = 10;$n}else{$n=$n-1;if($n-eq0){throw <<<< };$n;}
    + CategoryInfo          : OperationStopped: (:) [], RuntimeException
    + FullyQualifiedErrorId : ScriptHalted
\$\endgroup\$
4
  • \$\begingroup\$ Welcome to PPCG! The rules to calculate bytes depend on the character encoding used by the language. Powershell probably uses ASCII or UTF-8 encoding, and so for a script with only ASCII codes, as is the case here, each character takes up 1 byte \$\endgroup\$
    – Luis Mendo
    Commented Dec 16, 2016 at 12:57
  • \$\begingroup\$ Welcome to PPCG! Per the challenge writer, all submissions must be a complete program, which this is not -- as is, it's essentially being run in PowerShell's equivalent of a REPL. \$\endgroup\$ Commented Dec 16, 2016 at 14:26
  • \$\begingroup\$ If I wrote this inside of a .ps1 and executed that 10 times crash-off.ps1 for example, does that count as a full program? \$\endgroup\$ Commented Dec 19, 2016 at 9:47
  • \$\begingroup\$ @KieronDavies Yes, provided that if you closed and reopened the shell in between each time, you still got the same result. Keeping items "in memory" in the shell between execution is what defines the "REPL environment" of PowerShell from a "full program" environment. \$\endgroup\$ Commented Dec 19, 2016 at 16:36
3
\$\begingroup\$

Java, 343 bytes

My first golfing attempt

import java.io.PrintWriter;class M{public static void main(String[] a) throws Exception{if(!new java.io.File("x").exists()) try(PrintWriter p=new java.io.PrintWriter("x")){p.write("10");}int b=new java.util.Scanner(new java.io.File("x")).nextInt();try(PrintWriter p=new java.io.PrintWriter("x")){p.print(b/b*b-1+"");System.out.print(b+"");}}}

ungolfed

import java.io.PrintWriter;

class M {
    public static void main(String[] a) throws Exception {
        if (!new java.io.File("x").exists()) {
            try (PrintWriter p = new java.io.PrintWriter("x")) {
                p.write("10");
            }
        }
        int b = new java.util.Scanner(new java.io.File("x")).nextInt();
        try (PrintWriter p = new java.io.PrintWriter("x")) {
            p.print(b / b * b - 1 + "");
            System.out.print(b + "");
        }
    }
}
\$\endgroup\$
4
  • \$\begingroup\$ You can get it down to 300 bytes by importing java.io.* and avoiding using fully-qualified constructor names, and you can cut another 8 by using the fact that "print" will automatically stringify its arguments: import java.io.*;class M{public static void main(String[] a) throws Exception{if(!new File("x").exists()) try(PrintWriter p=new PrintWriter("x")){p.print(10);}int b=new java.util.Scanner(new File("x")).nextInt();try(PrintWriter p=new PrintWriter("x")){p.print(b/b*b-1);System.out.print(b);}}} \$\endgroup\$
    – Glen
    Commented Dec 17, 2016 at 0:56
  • \$\begingroup\$ You can get it down to 237 bytes by not writing the "10" to file, and instead just using the ? operator based on file existence when you read b: import java.io.*;class M{public static void main(String[] a) throws Exception{int b=new File("x").exists()?new java.util.Scanner(new File("x")).nextInt():10;try(PrintWriter p=new PrintWriter("x")){p.print(b/b*b-1);System.out.print(b);}}} \$\endgroup\$
    – Glen
    Commented Dec 17, 2016 at 1:00
  • \$\begingroup\$ Most optimized I could make: 220 bytes. Here's the beast: import java.io.*;class A{public static void main(String[]a)throws Exception{File f=new File("f");int b=f.exists()?new FileInputStream(f).read()-48:10;new PrintWriter(f).printf("%d",b/b*b-1).close();System.out.print(b);}} \$\endgroup\$ Commented Dec 17, 2016 at 20:12
  • \$\begingroup\$ thx for the suggestions :) \$\endgroup\$ Commented Dec 19, 2016 at 13:26
3
\$\begingroup\$

SQLite, 142 137

This could probably be done much more cleverly. 141 136 chars for code:

create table if not exists t(n not null);insert into t select 11;update t set n=case n when 1 then null else n-1 end;select min(n)from t

Plus 1 for the filename x in sqlite3 x '…'.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Nice! Haven't seen SQLite used like this before. You can squeeze a few bytes by replacing "values(11)" with "select 11", and "select n from t limit 1" with "select min(n) from t" \$\endgroup\$ Commented Dec 17, 2016 at 1:08
3
\$\begingroup\$

JavaScript, 74 bytes

x=typeof x!=typeof 1?10:x!=1?x-=1:_

l=localStorage;l.a=typeof l.a!=typeof""?10:l.a!=1?l.a=--l.a:_;aler‌​t(l.a)

\$\endgroup\$
4
  • 5
    \$\begingroup\$ The OP has clarified (in the comments) that a full program is required. \$\endgroup\$
    – Dennis
    Commented Dec 16, 2016 at 5:39
  • 1
    \$\begingroup\$ @Dennis Does my revised submission qualify as a full program? \$\endgroup\$
    – Oliver
    Commented Dec 16, 2016 at 14:52
  • \$\begingroup\$ I don't know, but I don't think so. I'd say that without a call to alert or similar, it's just a REPL snippet. \$\endgroup\$
    – Dennis
    Commented Dec 16, 2016 at 15:11
  • 2
    \$\begingroup\$ Looks good to me. (Can't test it from my phone.) \$\endgroup\$
    – Dennis
    Commented Dec 16, 2016 at 16:29
3
\$\begingroup\$

Ruby, 94 87 84 61 59 bytes

j=File.open(?a,"a+");1/(i=j.readlines.size-14);p -i;j.puts

Please leave suggestions below.

Thanks @ConorO'Brien for the ideas (some shamelessly ripped off from his answer).

\$\endgroup\$
2
  • \$\begingroup\$ puts i => p i \$\endgroup\$ Commented Dec 16, 2016 at 3:37
  • \$\begingroup\$ Use new and size instead of open and length. \$\endgroup\$
    – Lee W
    Commented Dec 16, 2016 at 17:01
2
\$\begingroup\$

Ruby, 52 + 1 = 53 bytes

Assumes the file is named a (+1 byte).

q=File.read ?a
0/h=62-q.size
p h
File.write ?a,q+?1#

Running

C:\Users\Conor O'Brien\Documents\Programming
λ type a
q=File.read ?a
0/h=62-q.size
p h
File.write ?a,q+?1#
C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
10

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
9

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
8

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
7

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
6

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
5

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
4

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
3

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
2

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
1

C:\Users\Conor O'Brien\Documents\Programming
λ ruby a
a:2:in `/': divided by 0 (ZeroDivisionError)
        from a:2:in `<main>'
\$\endgroup\$
4
  • \$\begingroup\$ ...you can assume names? \$\endgroup\$
    – anna328p
    Commented Dec 16, 2016 at 3:42
  • \$\begingroup\$ You could use $0 instead of a and 'echo>>#$0' (with backticks) on the last line. \$\endgroup\$
    – G B
    Commented Dec 16, 2016 at 8:56
  • \$\begingroup\$ @GB It's still more bytes than assuming a (which is only +1). \$\endgroup\$
    – wizzwizz4
    Commented Dec 16, 2016 at 18:37
  • \$\begingroup\$ ?a is 2 bytes, $0 is 2 bytes, but doesn't need whitepaces. \$\endgroup\$
    – G B
    Commented Dec 16, 2016 at 20:58
2
\$\begingroup\$

Python 2, 89 bytes

x=10
x/x
print x
f=open(__file__,"r+")
s=f.read()
f.seek(0)
f.write(s.replace(`x`,`x-1`))
\$\endgroup\$
3
  • \$\begingroup\$ I liked your idea of opening __file__ so I made use of that in my answer. \$\endgroup\$
    – Alex Hall
    Commented Dec 16, 2016 at 17:55
  • \$\begingroup\$ @AlexHall Great idea with len \$\endgroup\$
    – L3viathan
    Commented Dec 16, 2016 at 18:06
  • \$\begingroup\$ @Flp.Tkc I won't save any characters with that. I still need to use the variable s, because I need to read, then seek, then write. The print x/x*x would work, but doesn't improve the byte count. \$\endgroup\$
    – L3viathan
    Commented Dec 17, 2016 at 11:29
2
\$\begingroup\$

TI-BASIC (TI-84 Plus) (15 bytes)

If not(Ans
11
Ans-1
AnsAns/Ans

Ans should equal 0 (the default value) before the first run.

Since AnsAns/Ans is the last line of the program, it will be outputted and stored to Ans unless Ans is 0, in which case a divide by 0 error occurs.

\$\endgroup\$
2
\$\begingroup\$

JavaScript, 41

l=localStorage;l.l=-~l.l;alert(11-l.l||I)

\$\endgroup\$
1
  • \$\begingroup\$ @Mego Yes obviously, I don't know how this could happen... I had an a instead of the l when i wrote it, and changed it without thinking, because i thought it looks more fun... it's been too late and herby, thanks for pointing that out. \$\endgroup\$
    – C5H8NNaO4
    Commented Dec 18, 2016 at 7:08
1
\$\begingroup\$

GNU Smalltalk, 70, 68 bytes

66 bytes code +2 bytes for the "-S" flag

EDITS

  • Removed unnecessary parentheses, -2 bytes

Golfed

X=Y ifTrue:[Smalltalk at:#X put:10]ifFalse:[X:=X-1].(X*X/X)printNl

Test

>seq 11|xargs -L1 sudo gst -S fail.st 2>/dev/null
10
9
8
7
6
5
4
3
2
1
Object: 0 error: The program attempted to divide a number by zero
ZeroDivide(Exception)>>signal (ExcHandling.st:254)
SmallInteger(Number)>>zeroDivide (SysExcept.st:1426)
SmallInteger>>/ (SmallInt.st:277)
UndefinedObject>>executeStatements (fail.st:1)

Important

You must run gst as root, for it to be able to modify the default image, or specify your own image with -I.

\$\endgroup\$
1
\$\begingroup\$

PHP, 45 bytes

Honestly not sure if this one counts.

<?session_start();echo10-$_SESSION[0]++?:die;

I'd post a link to an example, but all the online testers that I know don't allow session_start() to be used.

This will keep counting down each time you refresh the page until 0, when the die command is ran.

\$\endgroup\$
0
\$\begingroup\$

QBIC, 70 bytes

open"r",1,"a.b" $get#1,1,e|~e=0|e=z\e=e-1]?e~e=0|$error 1|]$put#1,1,e|

Opens file a.b (or creates it when not found on first run), reads record 1 into e. If that record is not found, assume 10, else sub 1. At e==0, raise an error. Write back e to a.b.

File access is not built into QBIC, this relies heavily on the underlying QBasic.

\$\endgroup\$
0
\$\begingroup\$

Batch, 72 bytes

@call:l
@if %n%==0 goto g
@echo %n%
@cmd/cset/a-1>>%0
:l
@set/an=10

Needs to be invoked using the full file name including extension. Last line must not have a trailing newline. Works by writing -1 to the end of the last line so that it evaluates to 1 less each time. goto g errors out because there's no label :g.

\$\endgroup\$
0
\$\begingroup\$

R, 52 bytes

`if`(!"x"%in%ls(),cat(x<-10),`if`(x>0,cat(x<-x-1),))

Essentially uses ls() to list the names of all globally stored objects. If we assume that the global environment is empty and "x" doesn't exist already, generate x=10, else if x!=0 subtract 1 else call a missing argument which returns an error.

\$\endgroup\$
4
  • \$\begingroup\$ You can save a byte by removing the ! and switching the order of the then and else arguments, and another two by changing x>0 to x. (Also, exists("x") is a little neater than "x"%in%ls(), although equal in byte count.) \$\endgroup\$
    – rturnbull
    Commented Dec 16, 2016 at 12:46
  • \$\begingroup\$ Ah, re-reading the comments in the specification, it looks like a full program is required, which means you can't rely on object persistence between runs. \$\endgroup\$
    – rturnbull
    Commented Dec 16, 2016 at 12:47
  • \$\begingroup\$ @rturnbull Although I cannot find where this is explicitly stated. I will delete the answer if you can point me to it. \$\endgroup\$
    – Billywob
    Commented Dec 16, 2016 at 13:33
  • \$\begingroup\$ It's mentioned here, although it hasn't been edited into the spec. \$\endgroup\$
    – rturnbull
    Commented Dec 16, 2016 at 15:19
0
\$\begingroup\$

Windows Batch, 61 bytes

@if %n%.==. set n=10
@if %n%==0 goto.
@set /a n-=1&@echo %n%
\$\endgroup\$
0
\$\begingroup\$

JavaScript, 44 bytes

function* f(n=11){for(;--n;yield n);throw''}

p=f()
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)
console.log(p.next().value)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.