title: Display a Digital Clock

text:
# Question
Title: Display a Digital Clock
## Display a Digital Clock

(I see there are many clock challenges, I have tried to read them all, I'm pretty sure this is unique)

Write some code that continuously updates a digital clock displayed in the format `h:m:s` where `h`, `m`, and `s` can occupy 1 or 2 characters each. The restrictions in simple terms as @BlueEyedBeast put it, I basically want it to replace the time shown.

* Newlines are not allowed
* Trailing spaces are allowed
* Other trailing characters are not allowed
* No seconds should be missed (57 -\> 59 is not allowed)
* Numbers beginning with "0" are allowed, as long as they don't occupy more than 2 characters
* The code must not accept any input
* If your language can't get the current time without input, you may use for input up to 8 bytes in a standardly allowed way
* Output must be to stdout
* This is codegolf so the shortest answer wins!

**Example**

~~I'm working on a language named \*\>\<\> (starfish) because programs like this aren't possible in \>\<\> (just wait for file i/o) . Here's a working digital clock program in it (ungolfed).~~ This program is written in \*\>\<\>:

```
s":"m":"hnonon"   "ooo88888888888ooooooooooo1S

```

Note: Everything is identical to \>\<\> in this except, s = second, m = minute, h = hour, S = sleep(100ms\*x)

This outputs:

```
14:44:31

```

Updating every 100ms until terminated.

**Disallowed Examples**

The following are not allowed:

1:

```
14:44:3114:44:32

```

2:

```
14:44:31 14:44:32

```

3:

```
14:44:31
14:44:32

```

The time must remain on the first line it was outputted with no visible trailing characters. Clearing the terminal though, would be allowed as that still wouldn't have any trailing characters.

# Answer
> 5 votes
## Pyke, 6 bytes

```
Ctr\ J

```

Try it here!

I think this is valid. Replace the space character with carriage return for valid output (does not work online)

# Answer
> 10 votes
# HTML + JS (ES6), 8 + 60 = 68 bytes

Tested in Chrome.

```
setInterval`a.innerHTML=new Date().toLocaleTimeString('fr')`
```

```
<a id=a>
```

-1 byte (@ETHProductions): Use French time format instead of `.toTimeString().slice(0,8)`

---

# HTML + JS (ES6), 8 + 62 = 70 bytes

This will work in FireFox.

```
setInterval('a.innerHTML=new Date().toLocaleTimeString`fr`',0)
```

```
<a id=a>
```

-3 bytes (@ETHProductions): Use French time format instead of `.toTimeString().slice(0,8)`

# Answer
> 7 votes
# Python 2, 50 bytes

(Python 2.1+ for `ctime` with no argument)

```
import time
while 1:print'\r'+time.ctime()[11:19],

```

`time.ctime()` yields a formatted string, from which the hh:mm:ss may be sliced using `[11:19]` (it remains in the same location whatever the date and time).

`print`ing the carriage return `'\r'` before the text and making the text the first item of a tuple with `,` effectively suppresses the implicit trailing `'\n'` and overwrites the previously written output.

`while 1` loops forever.

# Answer
> 6 votes
# Mathematica, ~~48~~ ~~41~~ ~~37~~ 28 bytes

```
Do[s=Now[[2]],∞]~Monitor~s

```

The output will be a `TimeObject`, refreshing continuously.

Looks like this:

**Alternative versions**

48 bytes:

```
Dynamic@Refresh[TimeObject[],UpdateInterval->.1]

```

53 bytes:

```
Dynamic@Refresh[DateString@"Time",UpdateInterval->.1]

```

# Answer
> 5 votes
I see that the requirement for a non-signal UI input to stop the program has been removed. So now we can do:

# Bash + coreutils, 28

```
yes now|date -f- +$'\e[2J'%T

```

`yes` continuously outputs the string "now", once per line, into a pipe.

`date -f-` reads interprets each "now" as the current time, then outputs in the required format. The format string includes the ANSI escape sequence to clear the screen. `date` *does* output a newline after the date - I'm not sure if this disqualifies, since the screen is cleared every time anyway.

If it disqualifies, then we can use `tr` instead:

# Bash + coreutils, 31

```
yes now|date -f- +%T|tr \\n \\r

```

---

Previous Answers:

# Bash + X, 32

```
xclock -d -update 1 -strftime %T

```

Unfortunately this can only update every second. If that disqualifies, then we can do this instead:

# Bash + coreutils, 43

```
until read -t0
do printf `date +%T`\\r
done

```

# Answer
> 4 votes
## QBIC, 6 bytes

```
{_C?_d

{      Starts a DO-loop
 _C    CLS
   ?   PRINT
    _d TIME$

```

Constantly clears the screen and prints the system time in the format `22:03:41`.

# Answer
> 4 votes
# PHP, 28 bytes

```
for(;;)echo date("\rH:i:s");

```

The `date` function prints everything literally that it doesn´t recognize.

`\r` is the carriage return, sets the cursor to the first column.

Run with `-r`.

# Answer
> 4 votes
# Bash + watch, 19 bytes

*watch* is not a part of *coreutils*, but is available out of the box on virtually every Linux distro.

**Golfed**

```
watch -tn1 date +%T

```

Try it online !

# Answer
> 3 votes
# MATL, 11 bytes

```
`XxZ'13XODT

```

Infinite loop that clears the screen and prints the time in the specified format.

You can try it at MATL Online!. This compiler is experimental; if it doesn't work refresh the page and press "Run" again.

# Answer
> 3 votes
# Clojure, ~~150~~ ~~136~~ 141 bytes

## V3: 141 bytes :(

+5 bytes to fix a bug. Since the times aren't zero padded, the clock can "shrink" and expand when the time changes. It was "smearing" when it shrunk because the last digit was no longer being cleared. Fixed it by adding some spaces at the end to ensure everything is being overwritten.

```
#(while true(flush)(print(str(apply str(repeat 9"\b"))(.format(java.text.SimpleDateFormat."H:m:s")(java.util.Date.))"   "))(Thread/sleep 99))

```

## V2: 136 bytes

```
#(while true(flush)(print(str(apply str(repeat 9"\b"))(.format(java.text.SimpleDateFormat."H:m:s")(java.util.Date.))))(Thread/sleep 99))

```

-14 bytes by switching to using `SimpleDateFormat` to format the date. Still huge.

## V1: 150 bytes

```
#(while true(let[d(java.util.Date.)](flush)(print(str(apply str(repeat 9 "\b"))(.getHours d)":"(.getMinutes d)":"(.getSeconds d)))(Thread/sleep 100)))

```

I realized I'm probably using the worst way possible to get the date. Definitely room for improvement here.

Ungolfed:

```
(defn -main []
  (while true
    (let [d (java.util.Date.)]
      (flush)
      (print
        (str
          (apply str (repeat 9 "\b"))
          (.getHours d)":"(.getMinutes d)":"(.getSeconds d)))
      (Thread/sleep 100))))

```

# Answer
> 3 votes
## C, ~~134~~ ~~116~~ ~~89~~ ~~80~~ ~~76~~ ~~75~~ 73 bytes

```
main(n){for(;time(&n);)printf("\r%02d:%02d:%02d",n/3600%24,n/60%60,n%60);}

---- Old versions:
main(n){for(;;)n=time(0),printf("\r%02d:%02d:%02d",n/3600%24,n/60%60,n%60);}

n;main(){for(;;)n=time(0),printf("\r%02d:%02d:%02d",n/3600%24,n/60%60,n%60);}

----

n;main(){for(;;)n=time(0),printf("\r%02d:%02d:%02d",n/3600%24,n/60%60,n%60);}

----

Saved 9 more bytes thanks to @nmjcman101 again:
n;main(){for(;;)n=time(0),printf("\r%02d:%02d:%02d",(n/3600)%24,(n/60)%60,n%60);}

----

Saved 27 bytes thanks to @nmjcman101
n,b[9];main(){for(;;){n=time(0);strftime(b,9,"%H:%M:%S",localtime(&n));printf("\r%s",b);}}

----

I figured out I don't need to put `#include<stdio.h>` into the file :)
#include<time.h>
main(){for(;;){time_t n=time(0);char b[9];strftime(b,9,"%H:%M:%S",localtime(&n));printf("\r%s",b);}}

----

#include<time.h>
#include<stdio.h>
main(){for(;;){time_t n=time(0);char b[9];strftime(b,9,"%H:%M:%S",localtime(&n));printf("\r%s",b);}}

```

# Answer
> 3 votes
# SmileBASIC 3.3.2, 38 bytes

```
@L?TIME$;" ";
GOTO@L

```

UTF-16 sucks :(

Anyway, this repeatedly prints the local time in HH:MM:SS with a space after it, no newline afterward. It doesn't update every second though, it just repeatedly prints forever.

# Answer
> 2 votes
# WinDbg, 73 bytes

```
.do{r$t0=0;.foreach(p {.echotime}){r$t0=@$t0+1;j8==@$t0'.printf"p \r"'}}1

```

It continually updates a line with the current time until the user presses Ctrl+Break.

How it works:

```
.do                          * Start do-while loop
{
    r$t0 = 0;                * Set $t0 = 0
    .foreach(p {.echotime})  * Foreach space-delimited word in a sentence like "Debugger (not
    {                        * debuggee) time: Mon Dec  5 14:08:10.138 2016 (UTC - 8:00)"
        r$t0 = @$t0+1;       * Increment $t0
        j 8==@$t0            * If $t0 is 8 (ie- p is the current time)
        '
            .printf"p \r"    * Print p (current time) and \r so the next print overwrites
        '
    }
} 1                          * Do-while condition: 1, loop forever

```

Sample output (well, you get the idea):

```
0:000> .do{r$t0=0;.foreach(p {.echotime}){r$t0=@$t0+1;j8==@$t0'.printf"p \r"'}}1
14:10:12.329

```

# Answer
> 2 votes
# C#, 82 bytes

```
()=>{for(;;)Console.Write(new string('\b',8)+DateTime.Now.ToString("HH:mm:ss"));};

```

Anonymous method which constantly overwrites 8 characters with new output. Can be made 1 byte shorter if modifying to accept a dummy parameter (`z=>...`).

Full program:

```
using System;

public class Program
{
    public static void Main()
    {
        Action a =
        () =>
        {
            for (;;)
                Console.Write(new string('\b', 8) + DateTime.Now.ToString("HH:mm:ss"));
        };

        a();
    }
}

```

# Answer
> 2 votes
## C#, 65 bytes

```
()=>{for(;;)Console.Write("\r"+DateTime.Now.ToLongTimeString());};

```

Works by overwriting the same line within an endless loop

# Answer
> 2 votes
# Powershell, 39 bytes

```
for(){write-host -n(date -F h:m:s`0`r)}

```

Because I dislike using cls in Powershell. From briantist's post @https://codegolf.stackexchange.com/a/102450/63383

# Answer
> 2 votes
# Pascal, 61 bytes

```
uses sysutils;begin while 1=1do write(#13,timetostr(now))end.

```

Free pascal has nice time routines in SysUtils unit. Ungolfed:

```
uses
  sysutils;
begin
  while 1=1 do
    write(#13, timetostr(now));
end.

```

# Answer
> 2 votes
# Commodore BASIC (CBM/PET, C64, C128, VIC-20, C16/+4), 64 ~62 BASIC bytes (tokens), 64 62 PETSCII characters with keyword abbreviations

```
?"{CLEAR}":FORI=0TO1:?"{HOME}"LEFT$(TI$,2)":"MID$(TI$,3,2)":"RIGHT$(TI$,2):I=0:NEXT

```

**Edit** I realised that this is what I would call a *zero liner*, or in other words, it does not require a line number to run, so I've taken this out. Once you break it though, you need to type it in again.

**Changes** Line numbers in Commodore BASIC take up I think at least two bytes (though I need to check), so by actual byte count is an estimation, however, removing the line number and using the `LEFT$` command for the first two digits, rather than the `MID$` command, has shaved off two whole characters from this.

Some notes: if you are entering this on a Commodore C64 then you will need to use keyword abbreviations (see the screen shot below). Some other Commodore 8-bits, like the C128 and VIC-20, accept more than 80 characters entered per line, but to be sure, use the keyword abbreviations anyway.

To set the time first, use `TI$="112233"` as `HHMMSS` format as 24 hours (`000000` being midnight).

## How it works

`TI$` is a system variable which fairly accurately keeps time. 8 BIT Show and Tell explores this in some depth in this YouTube video and is well worth a watch if you are interested.

An unbroken loop is set with resetting the `I` variable per iteration by setting it to `0`. We then use the `MID$` and `RIGHT$` function to print out each relevant time segment, being `HH:MM:SS`. A list of BASIC keywords can be found here.

# Answer
> 1 votes
# Vim, 26 bytes

```
qqS<C-r>=strftime("%T")<CR><esc>@qq@q

```

This creates a recursive macro (e.g. an eternal loop) that deletes all the text on the current line and replaces it with the current time.

# Answer
> 1 votes
# Pyth - 28 bytes

Kinda longish, because pyth has no strftime.

```
#p+"\r"j\:m.[`02`dP>4.d2.d.1

```

# Answer
> 1 votes
# PowerShell, ~~30~~ ~~28~~ ~~24~~ 20 bytes

Changed my computer's region to Germany based on raznagul's comment to save 4 bytes. :)

```
for(){date -F T;cls}

```

### Previous version that works in all locales.

```
for(){date -F h:m:s;cls}

```

# Answer
> 1 votes
# Groovy, 45 characters

```
for(;;)print(new Date().format("\rHH:mm:ss"))

```

# Answer
> 1 votes
# Jelly, 8 bytes

```
13Ọ7ŒTȮß

13Ọ        chr(13), carriage return
   7ŒT     time string, which extends the previous character
      Ȯ    print
       ß   call the whole link again

```

Try it online!

The carriage return doesn't work online, and I can't get the interpreter to work, so its kinda untested, but it works as expected when I use printable characters in place of the CR.

# Answer
> 1 votes
# ForceLang, 123 bytes

```
def s set
s d datetime
s z string.char 8
s z z.repeat 16
label 1
io.write z
io.write d.toTimeString d.now()
d.wait 9
goto 1

```

`datetime.toTimeString` is backed in the reference implementation by Java's `DateFormat.getTimeInstance()`, which is locale-dependent, so you can set your default system locale to one that uses 24-hour time.

# Answer
> 1 votes
# Java, 67 bytes

```
for(;;)System.out.print("\r"+java.time.LocalTime.now()+"\b\b\b\b");

```

We loop infinitely, grabbing the current time and outputting to screen. The quad backspace is for easy formatting, because otherwise we'd have to do something like this:

```
for(;;)System.out.print("\r" + java.time.LocalTime.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS));

```

# Answer
> 1 votes
# tcl, 69 bytes

```
while 1 {puts -nonewline \r[clock format [clock seconds] -format %T]}

```

Try it here!

# Answer
> 1 votes
## C 65 (prev 64) bytes

Guaranteed to work on Linux machine. :)

@Marco Thanks!

```
f(){while(1){system("date +%T");usleep(100000);system("clear");}}

```

# Answer
> 1 votes
# SmileBASIC, 14 bytes

```
CLS?TIME$EXEC.

```

`CLS` clears the screen, `? TIME$` prints the current time, and `EXEC 0` runs the code that's in slot 0. It's a bit flickery, but there's nothing in the reqirements about that, so it should be fine.

Format is `HH:MM:SS` 24 hour time :(

# Answer
> 1 votes
# x86-16 machine code, IBM PC DOS, ~~71~~ 69 bytes

Binary:

```
00000000: b81c 35cd 2153 06ba 1901 e806 00b4 08cd  ..5.!S..........
00000010: 211f 5ab8 1c25 cd21 c3b4 2ccd 218a c5e8  !.Z..%.!..,.!...
00000020: 0800 91e8 0400 8ac6 b2ff d40a 0d30 3086  .............00.
00000030: e0cd 2986 e0cd 2984 d27c 05b0 3acd 29c3  ..)...)..|..:.).
00000040: b00d cd29 cf                             ...).

```

Listing:

```
B8 351C         MOV  AX, 0351CH             ; AL = 1CH, AH = 35H
CD 21           INT  21H                    ; get interrupt vector for 1CH into ES:BX
53              PUSH BX                     ; save old vector
06              PUSH ES                     ; save old segment
BA 011D R       MOV  DX, OFFSET GET_TIME    ; DX = interrupt vector of time proc
E8 0117 R       CALL SET_VECT               ; setup new vector
B4 08           MOV  AH, 8                  ; DOS read char from stdin without echo
CD 21           INT  21H                    ; wait for user to press the "any key"
1F              POP  DS                     ; restore old segment
5A              POP  DX                     ; restore old vector
            SET_VECT:
B8 251C         MOV  AX, 0251CH             ; AL = 1CH, AH = 25H
CD 21           INT  21H                    ; set interrupt vector from DS:DX
C3              RET                         ; return to DOS
            GET_TIME:
B4 2C           MOV  AH, 2CH                ; get DOS time
CD 21           INT  21H                    ; CH = hour CL = minute DH = second
8A C5           MOV  AL, CH                 ; display hour: AL = CH
E8 012E R       CALL OUT_TIME               ; write time
91              XCHG AX, CX                 ; display minute: AL = CL
E8 012E R       CALL OUT_TIME               ; write time
8A C6           MOV  AL, DH                 ; display second: AL = DH
B2 FF           MOV  DL, -1                 ; set DL to -1 so doesn't display ':'
            OUT_TIME:
D4 0A           AAM                         ; BCD convert: AL = AL % 10, AH = AL / 10
0D 3030         OR   AX, '00'               ; ASCII convert
86 E0           XCHG AH, AL                 ; endian convert
CD 29           INT  29H                    ; write tens
86 E0           XCHG AH, AL                 ; swap digits
CD 29           INT  29H                    ; write ones
84 D2           TEST DL, DL                 ; when DL = -1, it is seconds digit
7C 05           JL   DONE_TIME              ; if last number, write CR not ':'
B0 3A           MOV  AL, ':'                ; write ':'
CD 29           INT  29H
C3              RET                         ; return from near call
            DONE_TIME:
B0 0D           MOV  AL, 0DH                ; carriage return
CD 29           INT  29H                    ; move cursor back to beginning of line
CF              IRET                        ; return from interrupt

```

A standalone PC DOS executable COM program. Uses DOS to hook the hardware timer interrupt which calls the program every 18.2ms to update the clock on the screen. Exits when any key is pressed.

Runtime:

(A key was hit after 5 seconds, exiting the program)

# Answer
> 1 votes
# Japt, 8 bytes

```
i@OqK¤¯8

```

Test it

```
i@OqK¤¯8
i            :Every 0 milliseconds
 @           :Run the following function
  Oq         :Replace the output with
    K        :Date object
     ¤       :Convert to time string
      ¯8     :Slice to the 8th character

```

# Answer
> 1 votes
# 05AB1E, 15 bytes

```
[žažbžc':ý13ç«?

```

Try it online. (The TIO doesn't support carriage returns, so every line is printed without overwriting the previous line. I also included a footer with a 0.1 sec sleep and which stops after 5 seconds, so the output won't be flooded with the same outputs and you won't have to wait 60 seconds for it to timeout.)

*Here a gif to see it in action:*

**Explanation:**

```
[                # Loop indefinitely:
 ža              #  Push the current hours
   žb            #  Push the current minutes
     žc          #  Push the current seconds
       ':ý      '#  Join the entire stack with ":" as delimiter
          13ç    #  Push 13 and convert it to a character: '\r'
             «   #  Append this carriage return to the time-string
              ?  #  Pop and output this string (without newline)

```

# Answer
> 1 votes
# Windows Batch Scripting, 55 bytes

```
@echo off
:l
cls
echo %time:~0,8%
timeout 1 >nul
goto l

```

# Output

# Answer
> 0 votes
## Batch, 36 bytes

```
@set/p.=␈␈␈␈␈␈␈␈%time:~0,8%<nul
@%0

```

Where  represents the ASCII BS character (code 8).

# Answer
> 0 votes
# Racket, 71 bytes

```
(require srfi/19)(let l()(display(date->string(current-date)"↵~3"))(l))

```

Where the  is actually a CR (hex `0d`). Hex dump of the program for further clarification (notice byte at position hex `4d`):

```
00000000  28 72 65 71 75 69 72 65  20 73 72 66 69 2f 31 39  |(require srfi/19|
00000010  29 28 6c 65 74 20 6c 28  29 28 64 69 73 70 6c 61  |)(let l()(displa|
00000020  79 28 64 61 74 65 2d 3e  73 74 72 69 6e 67 28 63  |y(date->string(c|
00000030  75 72 72 65 6e 74 2d 64  61 74 65 29 22 0d 7e 33  |urrent-date)".~3|
00000040  22 29 29 28 6c 29 29                              |"))(l))|
00000047

```

Uses SRFI/19 included with the Racket distribution. `(current-date)` gets the current local date & time. The `date->string` format `~3` is ISO-8601 hour-minute-second format. `(let l () ... (l))` in an idiomatic infinite loop. `(require srfi/19)` loads the `srfi/19` module.

# Answer
> 0 votes
# C, 156 bytes

```
#include<stdio.h>
#include<time.h>
int main(){time_t a;struct tm *b;char c[9];for(;;){time(&a);b=localtime(&a);strftime(c,9,"%H:%M:%S",b);printf("%s\r",c);}}

```

# Answer
> 0 votes
## \*\>\<\> (Starfish), 22 bytes

```
"   ::"s@hm@donononooo

```

Try it here!

**Ungolfed**

```
>s":"m":"hnonon"   "ooo1S\
\                 ;?+1iod/

```

## Explanation

```
d                      push \r to the stack
 "   ::"               push "   ::" to the stack
        s              push seconds to the stack
         @             move seconds back 2
          hm           push hours and minutes to the stack
            @          move minutes back 2
             n         output a number
              o        output a character

```

First, we build the initial stack with `d" ::"s`, giving us `["\r", " ", ":", ":", seconds]`, building the stack this way saves two bytes by removing 4 `"`, and adding two `@`. It's important to know what the `@` instruction does here, it simply changes the end of the stack in such a way so `[1,2,3,4] @ [1,4,2,3]`. So we run `@` giving us a stack of `["\r", " ", seconds, ":", ":"]`. Then we run `hm@`, which adds the hours, then the minutes to the end of the stack and executes `@`, giving us `["\r", " ", seconds, ":", ":", hours, minutes] @ ["\r", " ", seconds, ":", minutes, ":", hours]`. In `nononoooo`, `n` outputs a number from the end of the stack, `o` outputs a byte.

Then the \>\<\> simply loops back around to the beginning!

# Answer
> 0 votes
# Excel VBA, 17 Bytes

Outputs current time to cell `A1`

```
Do:[A1]=Now:Loop

```

Note: The above subroutine does not exit so either holding `Esc` to terminate the process or adding a `DoEvents` call to the sub above (`Sub a:Do:[A1]=Now:DoEvents:Loop`) to allow for hitting the stop button is recommended

# Answer
> 0 votes
## TI-Basic, 40 Bytes

(In TI-BASIC, many characters are 2 byte tokens, and colons at the beginning of a line are 0 extra bytes)

```
:ClrHome
:Output(1,6,":
:setTmFmt(24
:While 1
:Output(1,1,getTmSrr(0
:getTime
:Output(1,7,Ans(3
:End

```

# Answer
> 0 votes
# R, 41 bytes

```
repeat{cat(format(Sys.time(),"%T"),"\r")}

```

Has one trailing space (because of `cat` default separator being a space).
Because of the refresh rate of the R GUI, running this in the GUI will occasionally skip some seconds, but if you save it to a file and run it on the command line it will display correctly every single seconds.
Will run forever until user interrupt.

# Answer
> 0 votes
# Batch, 25 bytes (not including newline)

```
:k
@echo %time% && @goto k

```

Example output:

# Answer
> 0 votes
## HP‑41C series, 9 Bytes

This program requires an HP‑41CX or an HP‑41C/CV with a time module plugged in. Press the `R/S` (run/stop) key to interrupt the program. Press the  key to return to the regular display with the current time now being the value of the `X` register (`HH.MMSSss` format). Pressing any other key will clear the display, too, but also execute the key’s associated function.

```
01♦LBL⸆T           5 Bytes  global label requires 4 + (length of string) Bytes
02 CLK24           2 Bytes  select military time format
03 CLOCK           2 Bytes  show the current time refreshing every second

```

The default setting is showing a 12‑hour clock (using AM/PM) and a calendar date (`MM/DD`). You may need to insert the `CLKT` command (2 Bytes) to revert to this setting (i. e. omitting the calendar date) to see the current seconds value, too.

Remember, if you are running low on batteries (indicated by the `BAT` annunciator and flag 49 set), the `CLOCK` command turns the calculator *off*. The continuous clock draws about 2 mA of power.

---
Tags: code-golf
---


title: One-Dimensional Pinball

text:
# Question
Title: One-Dimensional Pinball
Consider a finite, one-dimensional grid where each cell is marked with one of two symbols (I will use the symbols `<` and `>`, but you can use other symbols).

When a pinball is placed on one of the cells, it moves according to the following rules:

* If the pinball is on a cell that is marked with `<`, the pinball moves one cell left in the next second, and if marked with `>`, it moves one cell right in the next second.
* After the pinball has moved, the marker on the cell is inverted (i. e. if cell was marked with `<`, it becomes `>`, and vice versa).
* The pinball stops moving when it leaves the grid.

## Challenge

Given the initial markers on the grid and a starting location for the pinball, calculate how many seconds it would take for the pinball to leave the grid.

## Input Format

* You may represent the markers on the initial grid as an array/string containing two distinct values.
* You may take the starting position as a 0-indexed or 1-indexed value.

## Worked example

```
initial grid = ><<, start = 1
  *    *      *      *    *    *    *
 ><<   >><   <><   <<<   <<>   <>>   >>>
        1     2     3     4     5     6

```

Here the `*` represents the pinball, and the numbers on the bottom represent the time elapsed.

## Testcases

```
><<, 0 -> 3
><<, 1 -> 6
><<, 2 -> 5

<<<<, 0 -> 1
<<<<, 3 -> 4

<><<<>, 1 -> 4
<><<<>, 3 -> 10
<><<<>, 4 -> 8
<><<<>, 5 -> 1

```

---

*Based on this Codeforces problem (Same problem but you need to solve for all starting locations in linear time)*

# Answer
> 16 votes
# Minecraft Functions, 378 + 141 + 541 = 1060 bytes

Made up of 3 functions in a data pack named `a`:

`a.mcfunction`:

```
scoreboard objectives add a dummy
data modify storage s a set from storage s c[0]
data remove storage s c[0]
execute at @p if data storage s {a:0} run setblock ~ ~ ~ mud
execute at @p if data storage s {a:1} run setblock ~ ~ ~ tnt
execute at @p run tp @p ~1 ~ ~
execute if data storage s c[0] run schedule function a:a 1
execute at @p unless data storage s c[0] run function a:b

```

`b.mcfunction`:

```
summon cat
data modify entity @e[type=cat,limit=1] Pos[0] set from storage s i
execute at @e[type=cat,limit=1] run tp @p ~.5 ~ ~
function a:c

```

`c.mcfunction`:

```
execute at @p if block ~ ~ ~ air run tellraw @p {"score":{"name":"a","objective":"a"}}
execute at @p unless block ~ ~ ~ air run schedule function a:c 1
execute at @p if block ~ ~ ~ mud run data merge storage s {a:0}
execute at @p if block ~ ~ ~ tnt run data merge storage s {a:1}
execute at @p if data storage s {a:0} run setblock ~ ~ ~ tnt
execute at @p if data storage s {a:1} run setblock ~ ~ ~ mud
execute at @p if data storage s {a:0} run tp @p ~-1 ~ ~
execute at @p if data storage s {a:1} run tp @p ~1 ~ ~
scoreboard players add a a 1

```

The input grid is given as an array `c` of `0` (left) and `1` (right) in storage `s`. The starting position at is given as a double `i` in the same storage. They can be set with these commands:

```
# Set grid (<><<<>)
data modify storage s c set value [0,1,0,0,0,1]
# Set starting position (position 3)
data modify storage s i set value 3.0d

```

It's run with `/function a:a` and outputs the number of seconds to chat. For best results (well, correct results), run in a void world in Spectator mode at x=0.

Here's a slowed down GIF of it in action for test case #7 (RIP the cat).

Definitely not anywhere near optimal, but it was a fun challenge!

# Answer
> 8 votes
# K (ngn/k), 25 bytes

Takes markers as 1/-1 for left and right.

```
{1+.[o;(x;y-x[y]*:-1);0]}

```

Try it online!

# Answer
> 7 votes
# JavaScript (Node.js), 30 bytes

```
s=>g=p=>s[p]&&-~g(p-=s[p]*=-1)

```

Try it online!

-1B from Arnauld

32 if it need to be one char

# Answer
> 7 votes
# Excel ms365, ~~138~~ 129 bytes

Lovely challenge! I decided to make a recursive function that will keep calling itself through `LAMBDA()`:

Formula in `A3`:

```
=LET(v,TOCOL(1:1,1)="<",i,SEQUENCE(ROWS(v)),x,LAMBDA(f,g,s,p,IF(OR(i=p),f(f,IF(i=p,1-g,g),s+1,p-2*INDEX(g,p)+1),s)),x(x,v,,A2+1))

```

The answer is 0-indexed and is made in such a way you can alter the values in the 1st row and the starting position in cell `A2`.

The actuall `LAMBDA()` has 4 parameters;

* `f` \- A call to itself (to make this recursive);
* `g` \- A grid made up of 0's and 1's based on symbol;
* `s` \- Seconds elapsed;
* `p` \- Current position in the grid.

# Answer
> 5 votes
# 05AB1E, ~~27~~ ~~24~~ 22 bytes

```
V[ā<Yå_#DYè©(YǝY®+V¼}¾

```

Inputs in the order \\$startingPosition,gridList\\$, where the \\$gridList\\$ is a list of `-1` and `1` for `<` and `>` respectively and \\$startingPosition\\$ is 0-based.

Try it online or verify all test cases.

**Explanation:**

```
V         # Store the first (implicit) input-index in variable `Y`
[         # Start an infinite loop:
 ā<       #  Push a list in the range [0,length) (without popping)
          #  (which will use the second implicit input-list in the first iteration)
   Yå_    #  Check whether `Y` is NOT in this list
      #   #  If it isn't (aka it's out of bounds): stop the infinite loop
 D        #  Duplicate the current list
  Yè      #  Pop the copy, and get its 0-based `Y`'th value
    ©     #  Store this value in variable `®` (without popping)
     (    #  Pop and negate it (-1 becomes 1 and vice versa)
      Yǝ  #  Insert it back into the list at 0-based index `Y`
 Y        #  Push 0-based index `Y` again
  ®       #  Push the current value `®` again
   +      #  Add that to `Y`
    V     #  Overwrite the previous `Y` with this new position
 ¼        #  Increase counter variable `¾` by 1 (0 by default)
}¾        # After the infinite loop: push counter variable `¾`
          # (which is output implicitly as result)

```

# Answer
> 4 votes
# Python 3, ~~64~~ ~~60~~ 56 bytes

*-8 bytes thanks to Mukundan314.*

```
f=lambda g,p:g[p]and-~f(g[:p]+[-g[p],*g[p+1:],0],p+g[p])

```

Try it online!

# Answer
> 4 votes
# Charcoal, 24 bytes

```
ＳＪＮ⁰≔⁰ζＷＫＫ«≦⊕ζ✳ι⁻lrι»⎚Ｉζ

```

Try it online! Link is to verbose version of code. Takes input as a string of `l`s and `r`s. Explanation:

Write the pinball layout to the canvas.

```
ＪＮ⁰

```

Jump to the initial position of the pinball.

```
≔⁰ζ

```

Start with `0` steps.

```
ＷＫＫ«

```

While the pinball is on an `l` or an `r`, ...

```
≦⊕ζ

```

... increment the number of steps, and...

```
✳ι⁻lrι

```

... overwrite the current cell with the letter of `lr` that it isn't, moving the pinball in the appropriate direction.

```
»⎚Ｉζ

```

Clear the canvas and output the final number of steps.

# Answer
> 4 votes
# Uiua SBCS, 32 bytes

```
◌◌⍢(⊙⊙(+1)+⟜⊃⊡⍜⊡¯|↧≥0,>,⧻,)⊙⊙0

```

Try it!

Takes 0-indexed starting index as an integer and markers as a list of `-1` for left and `1` for right.

Someone crush this answer, I beg of you. I tried the approach of padding the markers with a 0 at the front and back and taking a fixed point, but the best I could do was tie 32 bytes.

```
◌◌⍢(⊙⊙(+1)+⟜⊃⊡⍜⊡¯|↧≥0,>,⧻,)⊙⊙0
                           ⊙⊙0  # store the count under inputs
  ⍢(             |        )     # while...
                  ↧≥0,>,⧻,      # index is in-bounds...
              ⍜⊡¯               # negate at index
          +⟜⊃⊡                  # and update index
    ⊙⊙(+1)                      # increment count
◌◌                              # pop markers and index

```

# Answer
> 4 votes
# PARI/GP, 35 bytes

```
f(s,g)=iferr(1+f(s-=g[s]*=-1,g),e,)

```

Attempt This Online!

The grid `g` is represented as a list of `1`s and `-1`s. The starting position `s` is 1-indexed.

# Answer
> 4 votes
# Google Sheets, 124 bytes

```
=sort(let(v,tocol(2:2,1),i,sequence(rows(v)),_,lambda(_,g,s,p,if(or(i=p),_(_,if(i=p,-g,g),s+1,p+index(g,p)),s)),_(_,v,,A3)))

```

Takes an array of `-1` and `+1` that represent `<` and `>`, and the starting position as a 1-indexed positive integer.

Based on JvdV's original Excel answer with some optimizations.

In Google Sheets, array iteration needs to be enabled by wrapping the formula in `arrayformula()`, `sumproduct()`, `filter()`, `index()`, `sortn()` or `sort()`. This formula uses `sort()` that manipulates data but that does not matter here because the final result is just one value.

# Answer
> 2 votes
# Perl 5 `-plF`, 49 bytes

```
$i=<>;$\++,$i+=1-2*($F[$i]^=1)while$i>=0&&$i<@F}{

```

Try it online!

Uses `0` for move right and `1` for move left.

# Answer
> 2 votes
# Swift 5.9, ~~104~~ ~~88~~ 86 bytes

> **Shaved off 10 bytes thanks to @RolandSchmitz's suggestion to use the `~=` operator and to use `[Int]` instead of `[Bool]`; and an additional 6 bytes by shuffling types around and using implicit parameters.**

> **Removed another 2 bytes thanks to another suggestion by @RolandSchmitz to use `g.indices` instead of `0..<g.count`. (This works because the `indices` property is also a `Range` when used on an `Array` — if this wasn't the case, we wouldn't be able to use the pattern matching operator.)**

```
let s={var n=0,g:[Int]=$0,i=$1+0
while g.indices~=i{g[i] *= -1
i-=g[i]
n+=1}
return n}

```

`g` is the grid; `1` corresponds to `">"`, and `-1` corresponds to `"<"`. `i` is the starting position as an `Int`, 0-indexed.

When `f` is called:

1. Three variables are created:

* `n`, which is simply a counter
    * `g`, a mutable copy of the first implicit parameter (`$0`)

    > This is where we put the type signature for `$0` -- this allows us to have a type-less closure header, letting us dispense with the header altogether and use implicit closure parameters instead.
    * `i`, similar in purpose to `g` (we add `0` to give the type checker a hint)
2. The closure loops until `i` ceases to be a valid index of `g`.

> In Swift, the `~=(lhs:rhs:)` operator is used internally for pattern matching (`switch` statements, `if case`, and the like). Here, we call it directly to take advantage of the overload defined by `Range`, which checks if `rhs` is contained in `lhs`.

Inside this loop, we:

1. flip the sign of `g[I]`

    > The whitespace around the `*=` operator is required so the compiler sees `infix operator *=` followed by `prefix operator -`, instead of the nonexistent `infix operator *=-`.
    2. *decrement* `i` by `g[i]`
    3. increment `n`
3. Once we're out of the loop, `n` has the number of iterations it took for `i` to go out of bounds. This is exactly what we want, so we just go ahead and return that.

# Answer
> 2 votes
# Wolfram Language (Mathematica), 69 bytes

1-indexed, markers are `{-1,1}`

```
({g,c}={##};t=0;While[0<c<=Tr[1^g],t++;c+=(o=g[[c]]);g[[c-o]]=-o];t)&

```

Try it online!

# Answer
> 2 votes
# Ada, 187 bytes

```
function F(G:String;P:Integer;C:Integer:=0)return Integer is(if P<0 or P>=G'Last then C else F(G(1..P)&(if G(P+1)='>'then'<'else'>')&G(P+2..G'Last),(if G(P+1)='>'then P+1 else P-1),C+1));

```

F is a recursive expression function that:

* Defaults C to 0, and uses it to count iterations
* Returns C if P (the position) is out of bounds
* Calls itself on an altered G array and an updated position

# Answer
> 2 votes
# Ruby, 42 bytes

```
->s,g{1.step.find{g-=s[g]*=-1;g<0||!s[g]}}

```

Try it online!

# Answer
> 2 votes
# Jelly, 16 bytes

```
NJf©¥¦,®ị+ɗɗ/ƬL’

```

A monadic Link that accepts a pair, `[State, Position]` and yields the step count as an integer. `State` is a list of `-1` for left and `1` for right; `Position` is the 1-indexed index at which the ball starts.

**Try it online!** Or see the test-suite (transforms from the \<\> and zero-index test cases).

### How?

```
NJf©¥¦,®ị+ɗɗ/ƬL’ - Link: pair, [State; Position]
             Ƭ   - start with [State; Position]; collect up while distinct, applying:
           ɗ/    -   reduce by last three links as a dyad - f(S=State, P=Position):
     ¦           -     apply to...
    ¥            -     ...indices: last two links as a dyad - f(S, P):
 J               -                   indices of {S} -> [1,2,...,length(S)]
  f              -                   filter keep {P} -> [P] if P is in bounds
                                                         [] otherwise
   ©             -                   (& copy this to the register)
N                -     ...action: negate -> Next_S
          ɗ      -     last three links as a dyad - f(S, P):
       ®         -       recall from the register
        ị        -       {that} index into {S} (vectorises)
         +       -       add {P} -> Next_P = [S[P]+P] if P is in bounds
                                                  [P] otherwise
      ,          -     {Next_S} pair {Next_P}
                         (the next collection all works with Next_P being
                          a singleton list, so no need to extract the value)
              L  - length
               ’ - decrement

```

# Answer
> 2 votes
# C (gcc), ~~98~~ ~~96~~ ~~59~~ ~~56~~ 54 bytes

```
f(g,n,p)int*g;{return-1<p&p<n?f(g,n,p-=g[p]*=-1)+1:0;}

```

Try it online!

Readable version:

```
int f(int* g, int n, int p) {
    return -1 < p & p < n ?
           f(g, n, p -= (g[p] *= -1)) + 1 :
           0;
}

```
* `g` is the grid with `-1` corresponding to `<` and `1` to `>`.
* `n` is the length of the grid.
* `p` is the position of the pinball on the grid.

## Edits

-1 thanks to @noodle man

-1 by changing the data type of `g` from `char*` to `int*`

-37 thanks to @ceilingcat

-3 thanks to @Roland Schmitz

-2 thanks to @ceilingcat

# Answer
> 1 votes
# APL+WIN, ~~66~~, 64 bytes

2 bytes saved thanks to Mukundan

Prompts for grid followed by pinball position. ¯1 moves left and 1 moves right. Index origin = 1

```
g←⎕⋄p←⎕⋄n←0
:while ((p>0)^p≤⍴g)
g[p]←-g[p]⋄p←p-g[p]⋄n←n+1
:end
n

```

Try it online! Thanks to Dyalog Classic

# Answer
> 1 votes
# PowerShell Core, 85 bytes

```
filter f{param($c,$s)&({$c},{2*($s[$_]=!$s[$_])-1+$_|f($c+1)$s})[$_+1-in1..$s.Count]}

```

Try it online!

Recursive filter
Takes an array of booleans

* `true` for `<`
* `false` for `>`

Returns an integer

### Explanations

```
param($c,$s)                                                    # As it is a filter, we have 3 parameters $_ the current position, $c the score, $s the pinball directions
&({  },{                                 })[$_+1-in1..$s.Count] # If the ball position is outside of the array of directions
   $c                                                           # Return the count
          ($s[$_]=!$s[$_])                                      # Change the direction on the current ball position
        2*                -1+$_|f($c+1)$s                       # Increment the score by 1 and invoke the filter recursively on the new ball position

```

# Answer
> 1 votes
# Java 8, ~~70~~ ~~69~~ 61 bytes

```
a->s->{int c=0;try{for(;;c++)s-=a[s]*=-1;}finally{return c;}}

```

-8 bytes thanks to a tip from *@Neil* of using `-1,1` for `<,>` respectively, instead of `1,0`.

Grid input as an array with `-1` and `1` for `<` and `>` respectively.

Try it online.

**Explanation:**

```
a->s->{                 // Method with integer-array & integer parameters and integer
                        // return-type
  int c=0;              //  Counter, starting at 0
  try{for(;             //  Start an infinite loop:
          ;             //    After every iteration:
           c++)         //     Increase the counter by 1
    s-=                 //   Update position `s` based on the current `s`'th value:
       a[s]*=-1;}       //    Invert the current `s`'th value (-1 to 1 and vice versa)
  finally{              //  If an error occurs (ArrayOutOfBoundsException when `s` is
                        //  out of bounds):
    return c;}}         //   Return the counter as result

```

The `try{...}finally{...}` is 1 byte shorter than a manual in-bounds check `s>=0&s<a.length` within the loop.

# Answer
> 1 votes
# TI-Basic, 40 bytes

```
Prompt L,P
While P and P≤dim(ʟL
~ʟL(P→ʟL(P
P-Ans→P
C+1→C
End
C

```

Takes input as a list (with `1` for `>` and `~1` for `<`) and a 1-indexed position. `~` represents the negative sign while `-` represents the subtraction symbol.

---
Tags: code-golf
---


title: Manipulate integers to zero

text:
# Question
Title: Manipulate integers to zero
# Objective

Given a nonempty unordered list of **positive** integers, decide whether they can be added, negated, or multiplied to yield a single zero. Each given number must be used exactly once.

There is a taboo. Do not multiply zero to anything. Adding zero to anything is OK.

# Examples

## Truthy

```
List, Solution
[1,1], 1-1
[1,1,2], 2-1-1
[2,3,5], 2+3-5
[2,3,6], 2*3-6
[1,2,3,4], 2-1+3-4
[1,1,3,4], 1*1+3-4
[2,2,3,4], 2*3-2-4
[1,1,2,2,2], (2-1*1)*2-2

```

## Falsy

```
[1]
[1,2]
[2,3,4]
[1,3,3,4] ((3-3)*1*4 isn't valid because multiplication by zero is taboo)

```

# Answer
> 3 votes
# Charcoal, 56 bytes

```
⊞υＡＦυＦＬιＦκ«≔⟦§ιλ§ικ⟧θＦΦ⟦ΠθΣθ↔↨θ±¹⟧∨μν⊞υ⊞ＯΦι∧⁻ξκ⁻ξλμ»¬⌈⌊υ

```

Try it online! Link is to verbose version of code. Explanation:

```
⊞υＡＦυ

```

Start a breadth-first search with the initial list of integers.

```
ＦＬιＦκ«

```

Loop over the indices of every pair of integers in the list.

```
≔⟦§ιλ§ικ⟧θ

```

Extract the integers.

```
ＦΦ⟦ΠθΣθ↔↨θ±¹⟧∨μν

```

Loop over the sum and the absolute difference, and also the product, if it is nonzero.

```
⊞υ⊞ＯΦι∧⁻ξκ⁻ξλμ

```

Remove the integers from the list and add the new value, then add the new list to the list of lists to search.

```
»¬⌈⌊υ

```

Check whether a zero result was obtained.

# Answer
> 4 votes
# JavaScript (ES6), 101 bytes

Returns **0** or **1**.

```
f=a=>a==0|a.some((p,i)=>a.some((q,j)=>i<j&&[p+q,p-q,p*q||f].some(v=>f(q,q[i]=v),q=a.filter(_=>j--))))

```

Try it online!

### Commented

```
f = a =>            // a[] = input array
a == 0 |            // success if a[] == [0]
a.some((p, i) =>    // for each value p at index i in a[]:
  a.some((q, j) =>  //   for each value q at index j in a[]:
    i < j &&        //     abort if i >= j
    [               //     otherwise, compute:
      p + q,        //       addition
      p - q,        //       subtraction
      p * q         //       multiplication, whose result is ...
      || f          //       ... invalidated if it's 0
    ].some(v =>     //     for each value v in the above array:
      f(            //       do a recursive call:
        q,          //         pass q[]
        q[i] = v    //         with q[i] = v
      ),            //       end of recursive call
      q =           //       initialize q[] to ...
      a.filter(_ => //       ... a copy of a[] with ...
        j--         //         ... the j-th element removed
      )             //       end of filter()
    )               //     end of some()
  )                 //   end of some()
)                   // end of some()

```

# Answer
> 3 votes
# JavaScript (Node.js), 98 bytes

```
f=(x,a,b)=>[b]<f?x.some((t,i)=>f(x.filter(_=>i--),t,a))|x==a:[a+b,a-b,a*b||f].some(y=>f([...x,y]))

```

Try it online!

# JavaScript (Node.js), 106 bytes

```
f=(x,a,b)=>1/b?f([...x,a+b])|f([...x,a-b])|a*b*f([...x,a*b]):x+x?x.some((t,i)=>f(x.filter(_=>i--),t,a)):!a

```

Try it online!

# Answer
> 1 votes
# Python3, 292 bytes

```
lambda v:0 in[*f(v)]
R=range
def f(v):
 k=[v]
 for i in R(len(v)):
  for j in R(i+1,len(v)+1):
   if j-1>1 and j-i<len(v):
    for t in f(v[i:j]):k+=[v[:i]+[t]+v[j:]]
 for i in k:
  if len(i)==1:yield i[0];continue
  if(V:=i[0]*i[1]):k+=[[V,*i[2:]]]
  for I in[-1,1]:k+=[[i[0]+I*i[1],*i[2:]]]

```

Try it online!

# Answer
> 1 votes
# Scala 3, ~~387~~ 371 bytes

A port of @Ajax1234's Python answer in scala.

Saved 16 bytes thanks to @ceilingcat

---

Golfed version (371 bytes). Attempt This Online!

```
def F(v:List[Int])=f(v).contains(0)
def f(v:List[Int]):LazyList[Int]={val k:LazyList[List[Int]]=LazyList(v)++(for{i<-(0 to v.size-1).to(LazyList);j<-(i+1 to v.size).to(LazyList);if j>2&j-i<v.size;t<-f(v.slice(i,j))}yield v.slice(0,i)++List(t)++v.drop(j));k.flatMap{i=>if(i.size==1)LazyList(i(0))else{LazyList(i(0),i(1),i(0)*i(1))++(i.drop(2):+(i(0)+i(1))):+(i(0)-i(1))}}}

```

Ungolfed version. Attempt This Online!

```
object Main {
  def main(args: Array[String]): Unit = {
    println(F(List(1, 1)))
    println(F(List(1, 1, 2)))
    println(F(List(2, 3, 5)))
    //println(F(List(2, 3, 6)))
    println(F(List(1, 2, 3, 4)))
    println(F(List(1, 1, 3, 4)))
    println(F(List(2, 2, 3, 4)))
    println(F(List(1, 1, 2, 2, 2)))
    println("-" * 20)
    println(F(List(1)))
    println(F(List(1, 2)))
    println(F(List(2, 3, 4)))
    //println(F(List(1, 3, 3, 4)))
    //println(F(List(2, 2, 2, 2, 2)))
  }

  def F(v: List[Int]): Boolean = f(v).contains(0)

  def f(v: List[Int]): LazyList[Int] = {
    val k: LazyList[List[Int]] = LazyList(v) ++ (for {
      i <- (0 until v.length).to(LazyList)
      j <- (i + 1 to v.length).to(LazyList)
      if j - 1 > 1 && j - i < v.length
      t <- f(v.slice(i, j))
    } yield v.slice(0, i) ++ List(t) ++ v.drop(j))

    k.flatMap { i =>
      if (i.length == 1) LazyList(i.head)
      else {
        val V = i.head * i(1)
        LazyList(i.head, i(1), V) ++ (i.drop(2) :+ (i.head + i(1))) :+ (i.head - i(1))
      }
    }
  }
}

```

---
Tags: code-golf, decision-problem, integer
---


title: Pareto-optimal shortest paths

text:
# Question
Title: Pareto-optimal shortest paths
Given a directed graph on the nodes `0, 1, ..n`, where each edge has *two* non-negative integer costs, return the set of all possible Pareto Optimal path costs between node `0` and node `n`.

These are the costs of paths for which you cannot decrease the first component of the cost without increasing the second component, and conversely.

In the examples, I have given the input as a dictionary of edge costs, but you could also take a matrix of edge costs, or a list of edges with their corresponding costs.

Examples:

```
{(0, 1): (1, 4), (1, 2): (4, 2), (0, 2): (2, 1)} -> [(2, 1)]

{(0, 1): (2, 2), (2, 3): (4, 2), (0, 2): (3, 1),
 (0, 3): (1, 4)} -> [(1, 4), (7, 3)]

{(1, 4): (2, 4), (2, 3): (2, 1), (1, 2): (3, 1),
 (3, 4): (4, 1), (0, 1): (2, 2), (2, 4): (1, 4),
 (0, 2): (1, 3)} -> [(4, 6), (2, 7), (7, 5)]

{(0, 3): (2, 4), (3, 5): (2, 4), (0, 1): (1, 1),
 (1, 4): (4, 1), (1, 2): (2, 1), (3, 4): (1, 1),
 (1, 3): (2, 2), (4, 5): (4, 2)} -> [(4, 8), (9, 4), (5, 7), (8, 6)]

{(1, 2): (2, 1)} -> []

```

Reference solution in Python using breadth-first search:

```
def shortest_paths(graph):
    N = max(i for t in graph for i in t) + 1

    adj = [[] for _ in range(N)]
    for (i, j) in graph:
        adj[i].append(j)

    costs = [[] for _ in range(N)]
    costs[0].append((0, 0))

    queue0 = [((0, 0), 0)]
    queue1 = []
    while queue0:
        for ((c0, c1), i) in queue0:
            for j in adj[i]:

                (d0, d1) = graph[(i, j)]
                e0, e1 = c0 + d0, c1 + d1

                #dominated by or equal to an existing path
                if any((f0 <= e0) and (f1 <= e1) for f0, f1 in costs[j]):
                    continue

                #keep only non-dominated paths
                costs[j] = [(f0, f1) for (f0, f1) in costs[j] if (f0 < e0) or (f1 < e1)]
                costs[j].append((e0, e1))

                queue1.append(((e0, e1), j))

        queue0, queue1 = queue1, queue0
        del queue1[:]
    return costs[-1]

```

# Answer
# Kotlin, ~~248~~ ~~228~~ 211 bytes

```
fun Set<IntArray>.p(i:Int=0):Set<Pair<Int,Int>>
=if(i==maxOf{it[1]})setOf(0 to 0)else
filter{it[0]==i}.flatMap{p(it[1]).map{(a,b)->a+it[2]to b+it[3]}}.run{filter{(a,b)->all{(c,d)->a<c||b<d||a==c&&b==d}}}.toSet()

```

try on playground
> 3 votes

# Answer
# Scala 3, 234 bytes

A port of @Cactusroot's Kotlin answer in Scala.

---

Golfed version. Attempt This Online!

```
def p(s:Set[Array[Int]],i:Int=0):Set[(Int,Int)]={if(i==s.map(_(1)).max)Set((0,0))else s.filter(_(0)==i).flatMap(a=>p(s,a(1)).map{case(x,y)=>(x+a(2),y+a(3))}).filter{case(x,y)=>s.forall{b=>val(c,d)=(b(2),b(3));x<c||y<d||(x==c&&y==d)}}}

```

Ungolfed version. Attempt This Online!

```
def p(set: Set[Array[Int]], i: Int = 0): Set[(Int, Int)] = {
  if (i == set.map(_(1)).max) Set((0, 0))
  else
    set
      .filter(_(0) == i)
      .flatMap(arr =>
        p(set, arr(1)).map { case (a, b) => (a + arr(2), b + arr(3)) }
      )
      .filter { case (a, b) =>
        set.forall { arr =>
          val (c, d) = (arr(2), arr(3))
          a < c || b < d || (a == c && b == d)
        }
      }
}

```
> 1 votes

---
Tags: code-golf, graph-theory
---


title: Is this a valid variable name?

text:
# Question
Title: Is this a valid variable name?
Write a program or function that

* checks if a variable name is valid and
* output `1` or `True` if it is valid,
* `0.5` if it is valid but starts with an underscore (`_`),
* and `0` or `False` if it is not valid.

## Rules

* A variable name in most languages is valid if it begins with an underscore or letter (a – z, A – Z, \_) and the rest of the characters are either underscores, letters, or numbers. (a – z, A – Z, 0 – 9, \_)
* Output `1` or `True` if the variable name is valid and `0` or `False` if not valid.
* However, it is not good practice to start a variable with an underscore, so return `0.5` if it starts with an underscore and the name is valid.
* Standard loopholes apply.

## Test Cases

| input | output | reason |
| --- | --- | --- |
| `abcdefghijklmnop` | `1` |  |
| `_test_` | `0.5` | starts with an underscore |
| `123abc` | `0` | starts with a number |
| `A_b1C_23` | `1` |  |
| `_!` | `0` | not `0.5` because it’s not valid |
| `magical pony1` | `0` | no spaces |

## Scoring

This is , so shortest code wins. **Bonus:** −10% if your program/function outputs `0` for an empty string(`""`).

# Answer
> 13 votes
## JavaScript (ES6), 37 - 10% = 33.3 bytes

Saved 4 bytes thanks to @edc65

Saved 5.6 bytes thanks to @Mateon

```
s=>!/^\d|\W|^$/.test(s)/-~(s[0]=='_')

```

# Answer
> 8 votes
# 05AB1E, ~~25~~ ~~24~~ ~~20~~ 19 bytes

Code:

```
¬D'_Qsa·+¹žj-""Q*2/

```

Explanation:

```
¬                     # Push input and also push the first character.
 D                    # Duplicate the first character.
  '_Q                 # Check if it is equal to an underscore character.
     sa               # Swap and check the duplicate if it's an alphabetic character.
       ·              # Double the value.
        +             # Add both values up
         ¹            # Take the first input.
          žj-         # žj is short for [a-zA-Z0-9_]. This will be substracted from the
                        initial string.
             ""Q      # Check if the string is empty.
                *     # Multiply this with the first value.
                 2/   # Halve it, resulting into 0.0, 0.5, or 1.0.

```

In short, the formula for the string `s` in pseudocode is:

```
((s[0] == '_' + s.isalpha() × 2) × (s.remove([a-zA-Z0-9_]) == "")) / 2

```

Try it online!

Uses **CP-1252** encoding.

# Answer
> 6 votes
## PHP (50 - 10% = 45)

Thanks to Schism for the -2 :)

```
preg_match('/^[a-z_]\w*$/i',$s)?$s[0]=='_'?.5:1:0;

```

Not to compete with the golflang answers, but I thought I'd try it anyways.

```
preg_match('/^[a-z_]\w*$/i', $s) # Matches every a-zA-Z0-9_ string that doesnt start with a number
?   $s[0] == '_'                   # Then, if it starts with an _
    ?   .5                         # give 0.5 points
    :   1                          # If it doesn't, give 1
:   0;                             # If it didn't match the regex, give 0

```

Something to note is that in PHP, without the `/u` modifier, `\w` only selects ASCII letters. In some other languages/Regex flavours, this pattern won't work.

**Edit**: I see a lot of people using \w and \d in their answers, when they use a language that includes non-ASCII letters and digits too. That is NOT the puzzle. They are wrong. (Can't downvote/comment yet, sorry to need to tell it this way.)

# Answer
> 5 votes
# Retina, ~~30 - 10% = 27~~ ~~28 - 10% = 25.2~~ 29 - 10% = 26.1 bytes

Both versions qualify for bonus, as they handle empty input correctly (outputs `0`)

I had to fix a bug caused by one of .NET regex features, which considers some (read as many) Unicode characters as "word" characters. Fortunately, this cost me only a single byte in both versions. It only came down to adding a modifier to make the regex matching behavior compliant to ECMAScript standards. More about that here.

### New ~~28~~ 29-byte version, made by @MartinBüttner. Thanks!

```
^_
$_¶_
Mme`^(?!\d)\w+$
2
0.5
```

### Explanation

First, we check if the input starts with an underscore. If it does, the input is duplicated, with a newline in between. For example: `_test_` -\> `_test_\n_test_`, where `\n` is the newline. Then we try to match anything, that doesn't start with a number, but is followed by any number of "word" characters (`a-z`, `A-Z`, digits, and underscore) *on each line*. Note that if input started with an underscore and was replaced to two lines, this will match both lines. Then we check if we had 2 matches, and replace them with `0.5`. Empty or invalid line will always yield 0 matches, and valid variable names always yield 1 match.

---

### My own ~~30~~ 31-byte version

```
Ae`^\d|\W
^_.*
0.5
^\D.*
1
^$
0
```

### Explanation

First of all, we check if input starts with a digit or contains a non-word character (anything other than `a-z`, `A-Z`, digits and underscore). If it does, it's discarded, because it's invalid. Then we check if it starts with an underscore. If it does, it's replaced with `0.5`. Then we check if it starts with a non-digit character (at this point the first character is either `0`, `a-z`, or `A-Z`. Only `a-z` and `A-Z` are non-digits, obviously). If it does, it's replaced with a `1`. Then we check for empty string and replace it with `0`.

Try it online!
Try it online! Old version

# Answer
> 4 votes
# Python 3, 36 bytes

```
lambda s:s.isidentifier()/-~(s[:1]=='_')

```

The code is **40 bytes** long and qualifies for the **-10% bonus**.

Note that this will only work correctly for code pages that don't have non-ASCII letters/digits.

# Answer
> 3 votes
# MATL, 27 bytes

```
1)95=2/8M3Y2m+G7M95h4Y2hmA*

```

This works in current version(15.0.0) of the language.

Input is a string with single quotes.

**Try it online!**

### Explanation

```
1)      % take input implicitly. Get its first element
95=     % true if it equals 95 (underscore)
2/      % divide by 2: gives 0.5 if underscore, 0 if not
8M      % push first element of input again
3Y2     % predefined literal: string with all letters
m       % true if it's a letter
+       % add. Gives 1 if letter, 0.5 if underscore
G       % push input again
7M      % push string with all letters again
95h     % concatenate underscore
4Y2h    % predefined literal: string with all digits. Concatenate
mA      % true if all input chars belong to that concatenated string
*       % multiply. Display implicitly

```

# Answer
> 3 votes
## Pyke, 21 bytes

### (noncompeting, added string subtraction, various string constants)

```
Qh~u{Q~J\_+-|!Qh\_qh/

```

Explanation:

```
Qh~u{                 - Check first char isn't a digit
     Q~J\_+-          - Is the input alphanumeric + "_"
            |!        - Combine
              Qh\_q   - Is the first char an "_"
                   h/ - Combine

```

# Answer
> 2 votes
## Pyth, 27 bytes

```
c!|-rz0++G\_JjkUT}hzJhqhz\_

```

Test Suite

# Answer
> 2 votes
# Gogh, 29 bytes

```
÷"[^\W\d]\w*"g¦"_.*"g+÷2=0.5¿

```

Run using:

```
$ ./gogh no '÷"[^\W\d]\w*"g¦"_.*"g+÷2=0.5¿' "_test"

```

---

### Explanation

```
                   “ Implicit input                               ”
÷                  “ Duplicate the TOS                            ”
"[^\W\d]\w*"g      “ Fully match the STOS against the TOS (regex) ”
¦                  “ Swap the STOS and TOS                        ”
"_.*"g             “ Fully match the STOS against the TOS (regex) ”
+                  “ Add the TOS to the STOS                      ”
÷                  “ Duplicate the TOS                            ”
2=                 “ Determine if the TOS is equal to 2           ”
0.5¿               “ Leave the correct output on the stack        ”
                   “ Implicit output                              ”

```

# Answer
> 2 votes
# Perl, 21 bytes

```
$_=!/\W|^\d//2**/^_/

```

The score includes **+1 byte** for the `-p` switch. Try it on Ideone.

# Answer
> 2 votes
# Pyth, 19 bytes

```
c!:z"\W|^\d"0h!xz\_

```

Try it with the Pyth Compiler.

Note that this will only work correctly for code pages that don't have non-ASCII letters/digits.

### How it works

```
c!:z"\W|^\d"0h!xz\_  (implicit) Save the input in z.

  :z        0        Test if z matches the following regex:
    "\W|^\d"           A non-word character or a digit at the beginning.
                     This returns True iff z is an invalid name.
 !                   Apply logical NOT to yield True iff z is a valid name.
               xz\_  Find the first index of the underscore in z.
                     This yields 0 iff z begins with an underscore.
             h!      Apply logical NOT and increment.
                     This yields 2 if z begins with an underscore, 1 otherwise.
c                    Divide the two results.

```

# Answer
> 2 votes
# Dyalog APL, 19 bytes - 10% = 17.1

```
{(0≤⎕NC⍵)÷1+'_'=⊃⍵}

```

`{``}` anonymous function where the right argument is represented by
`⊃⍵` first character (gives space if empty)
`'_'=` 1 if equal to 'underbar, 0 otherwise
`1+` evaluates to 2 if initial underbar, 1 otherwise
`⎕NC⍵` name class; -1 if invalid name, 0 if undefined (but valid name), 2-9 if defined (and thus valid)

# Answer
> 2 votes
# Factor, 84 * 0.9 = 76.5

```
USE: regexp
[ R/ [_a-zA-Z]\w*/ R/ _.*/ [ matches? 1 0 ? ] bi-curry@ bi 0 = 1 2 ? / ]

```

Runs on the listener (repl), defines a quotation (anonymous function) that takes a string and outputs { 0 | 1/2 | 1 }.

Defining it as a word it's 97 chars:

```
USE: regexp
: v ( s -- n ) R/ [_a-zA-Z]\w*/ R/ _.*/ [ matches? 1 0 ? ] bi-curry@ bi 0 = 1 2 ? / ;

```

### How does it work:

`R/ [_a-zA-Z]\w*/ R/ _.*/` defines two regular expressions. `bi-curry@` partially applies the quotation `[ matches? 1 0 ? ]` to each regex, leaving two curried quotations on the stack. `bi` applies each quotation to the argument string.

Each of those (curried quotations) leave either a 1 or a 0, depending if they matched. The first matches on the well formed names, the second on names starting with underscore.

`0 = 1 2 ? /` The last value is replaced with a 1 if it was 0, or with a 2 if it was 1. Then the first (1 or 0, valid or not) is divided by the second (2 or 1, starts with underscore or not).

This is loooong! Any pointers to shrinking a bit more appreciated...

And I hate regexps!

### PS.

```
{ 0 } [ "" v ] unit-test
{ 0 } [ "" v ] unit-test
{ 0 } [ "1" v ] unit-test
{ 0 } [ "1var" v ] unit-test
{ 0 } [ "var$" v ] unit-test
{ 0 } [ "foo var" v ] unit-test
{ 1 } [ "v" v ] unit-test
{ 1 } [ "var" v ] unit-test
{ 1 } [ "var_i_able" v ] unit-test
{ 1 } [ "v4r14bl3" v ] unit-test
{ 1/2 } [ "_" v ] unit-test
{ 1/2 } [ "_v" v ] unit-test
{ 1/2 } [ "_var" v ] unit-test
{ 1/2 } [ "_var_i_able" v ] unit-test
{ 1/2 } [ "_v4r14bl3" v ] unit-test

```

all test pass ;)

# Answer
> 1 votes
# Perl, 34 + 1 = 35 bytes

```
$_=/^([^\W\d])\w*$//(($1 eq"_")+1)

```

Uses the `-p` flag.

## Explanation

```
$_=/^([^\W\d])\w*$//(($1 eq"_")+1)
   /^([^\W\d])\w*$/                 matches any string that starts with an underscore or a letter of the alphabet followed by 0 or more alphanumeric + underscore characters. The first character is stored in a capture group
                   /                divide result by
                    (($1 eq"_")+1)  (capture == "_") + 1. This is 1 if the first character was not an underscore and 2 if it was.
$_=                                 assign to $_ and implicitly print

```

# Answer
> 1 votes
# Mathematica, 93 bytes

```
If[#~StringMatchQ~RegularExpression@"[A-Za-z_][0-9A-Za-z_]*",If[#~StringTake~1=="_",.5,1],0]&

```

I'm honestly not sure if this *can* be golfed further.

# Answer
> 1 votes
# Python, 84 -10% = 76 bytes

```
lambda x:[0,[[.5,1][x[0]>'z'],0][x[0]<'A']][x.replace('_','a').isalnum()]if x else 0

```

# Answer
> 1 votes
# Vyxal, 22 bytes

```
hkdc¬:[kr\_+?F¬?h\_=ß½

```

Try it Online!

A mess.

# Answer
> 1 votes
# Japt, 23 bytes

Guess which genius once upon a time suggested removing `_` from Japt's `\w` character class thereby costing himself 3 bytes here! ETH *was* going to add a new class with `_` included but then he disappeared.

```
¥f"[%l_][%w_]+")/ÒUè"^_

```

Try it or run all test cases

# Answer
> 0 votes
# JavaScript ES7, 37 bytes

```
x=>!x.match(/\W|^\d/)/2**/^_/.test(x)

```

Try it online

How it works:

```
x=>                                   // Fat arrow function
   !x.match(/\W|^\d/)                 // Gives false if contains non word or starting
                                      //   with a digit. Booleans in numeric context will
                                      //   be 0 or 1
                      2**             // 2 to the power of...
                         /^_/.test(x) // gives true if starting with '_'.
                                      //   true -> 1 -> 2**1 -> 2
                                      //   false -> 0 -> 2**0 -> 1
                     /                // Devide the lValue boolean with the numeric rValue:
                                      // lValue = 0 or 1
                                      // rValue = 2 or 1

```

Port of @Dennis's Perl answer

# Answer
> 0 votes
# Ruby, 57 - 10% = 51.3 bytes

```
->(s){case s
when'',/^\d/,/\W/
0
when/^_/
0.5
else
1
end}

```

A pretty naïve approach

# Answer
> 0 votes
# Ruby, 44 bytes

```
->(s){s=~/^(_|\d)?\w*$/?$1?$1==?_?0.5:0:1:0}

```

# Answer
> 0 votes
# Lua, 82 - 10% = 73.8

```
v=function(s)return(s:match("^[_%a]+[_%w]*$")and 1or 0)*(s:match("_")and.5or 1)end

```

Test Cases:

```
print(v("a") == 1) -- true
print(v("1") == 0) -- true
print(v("_") == 0.5) -- true
print(v("") == 0) -- true
print(v("1a") == 0) -- true
print(v("a1") == 1) -- true
print(v("_1") == 0.5) -- true
print(v("_a") == 0.5) -- true
print(v("1_") == 0) -- true
print(v("a_") == 0.5) -- true

```

# Answer
> 0 votes
# Lua, 68 * .9 = 61.2 bytes

```
s=arg[1]print(s:find("^[%a_][%w_]*$")and(s:find("^_")and.5or 1)or 0)

```

Takes arguments on the command line

# Answer
> 0 votes
# Julia 1.3, ~~46~~ 44 -10% = ~~41.4~~ 39.6 bytes

```
!s=[1 .5]count.(r"^[a-z]\w*$"i=>r"^_\w*$",s)

```

Try it online!

### explanation

* `r"^[a-z]\w*$"i` is the regex for a variable not starting with a `_` (the `i` means case-insensitive)
* `r"^_\w*$"` for a variable starting with a `_`
* `count.()` counts the number of time each regex appears in s, result is in a vector (similar to a 2×1 matrix)
* `[1 .5]` is a 1×2 matrix, when multiplied by the previous result, gives the expected result (0.5 when starting with `_`, 1 otherwise)

# Answer
> 0 votes
# Scala 3, 85 bytes

Golfed version. Attempt This Online!

```
s=>if(s.isEmpty||s(0).isDigit|| !s.matches("^\\w+$")).0 else if(s(0)=='_').5 else 1.0

```

Ungolfed version. Attempt This Online!

```
object Main {
  def main(args: Array[String]): Unit = {
    val testCases = Map(
      "abcdefghijklmnop" -> 1,
      "_test_" -> 0.5,
      "123abc" -> 0,
      "A_b1C_23" -> 1,
      "_!" -> 0,
      "magical pony1" -> 0
    )

    testCases.foreach { case (input, expected) =>
      val result = validateString(input)
      println(s"Input: $input, Expected: $expected, Result: $result, Correct: ${result == expected}")
    }
  }

  def validateString(s: String): Double = {
    if(s.isEmpty || s.head.isDigit || !s.matches("^\\w+$")) {
      0.0
    } else if(s.head == '_') {
      0.5
    } else {
      1.0
    }
  }
}

```

# Answer
> 0 votes
# Perl 5, (22 + 1 `-p` bytes) * .9 = 20.7

```
$_=!/\W/*/^\D//2**/^_/

```

Try it online!

---
Tags: code-golf, string
---


title: Reversed Iota's

text:
# Question
Title: Reversed Iota's
I didn't invent this challenge, but I find it very interesting to solve.

For **every** input number, e.g.:

```
4

```

Generate a range from 1 to that number:

```
[1 2 3 4]

```

And then, for every item in that list, generate a list from 1 to that number:

```
[[1] [1 2] [1 2 3] [1 2 3 4]]

```

Then, reverse every item of that list.

```
[[1] [2 1] [3 2 1] [4 3 2 1]]

```

## Notes:

* 1 being a loose item is allowed, since flattening will not matter with this anyway.
* To preserve the spirit of the challenge, the range has to be 1-indexed.
* You may flatten the list if your platform doesn't support the concept of nested lists.

# Answer
> 11 votes
# APL (Dyalog Unicode), ~~5~~ 4 bytesSBCS

Anonymous tacit prefix function.

```
,⍨\⍳

```

Try it online!

`,⍨\` cumulative reverse-concatenation reduction of

the iota

# Answer
> 9 votes
# , ~~22~~ 19 bytes

```
Map(`:`,1:scan(),1)

```

Try it online!

`Map(f,...)` applies `f` elementwise to each member of `...`, recycling as needed, resulting in a `list`, so we just supply `1` as the `to` argument to `:` to get the reversed.

-3 bytes thanks to Vlo!

# Answer
> 8 votes
# Jelly, 3 bytes

```
RRU

```

```
R     Range from 1 to input
 R    (implicitly) map over said range and create a range from 1 to this element
  U   reverse each of those

```

You can try it online!

Courtesy of @JonathanAllan, we also have two other 3-"byters"

```
RrL
RrE

```

I think it is not often that golfing languages solve a challenge with only `a-zA-Z` characters

# Answer
> 7 votes
# Pure Bash (no external utilities), 29

```
eval eval echo \\{{1..$1}..1}

```

Try it online!

# Answer
> 6 votes
# 05AB1E, 3 bytes

```
LLí

```

Try it online!

# Answer
> 5 votes
# Wolfram Language (Mathematica), 20 bytes

```
Range[Range@#,1,-1]&

```

Try it online!

-3 bytes from @att

# Answer
> 5 votes
# shell + sed, 15 bytes

```
seq $1|sed G\;h

```

Try it online!

Outputs like so, `1\n\n2\n1\n\n3\n2\n1\n\n[...]`

`seq $1` creates a sequence from 1 to the first argument `$1`

`|sed ...` which is piped into a sed script

sed works on a line-by-line basis; it first reads the first line into the buffer, called the "pattern space", after which the program commands is run on it. At the end of the program's execution on the first line, the remaining pattern space is implicitly printed. Then sed reads the next line into the pattern space, replacing the previous contents, and runs the commands on it, repeating for all lines of input (unless a command specifies otherwise).

The pattern space is not saved between lines, but what is is the hold space. The hold space is another buffer, that starts empty, and can be modified by program commands. Its contents are carried on to the execution of the next line of input.

The `G` command appends a newline followed by the content of the hold space to that of the pattern space. Then the `h` command replaces the hold space with the content of the pattern space. This effectively reverses the lines of input encountered so far, writing them to the pattern space – implicitly printing at the end of processing the current line – and saving them to the hold space so that upon reading subsequent lines of input, the new reversed "list" can be constructed with `G;h`.

The `;` is escaped in the program as `\;` because otherwise the shell interprets it as terminating a shell command.

# Answer
> 5 votes
# ~~Perl 6~~ Raku, ~~24 15 13~~ 10 bytes

-2 removed parenthesis

-3 thanks to nwellnhof

```
^*+1 X…1

```

Try it online!

## Explanation

```
^*+1     # make a range from 1 .. argument (whatever star).
     X…1 # create ranges descending to 1 using cross product metaoperator.

```

## Previous version, 24 bytes

```
(^<<(^*+1)X+1)>>.reverse

```

Try it online!

### Explanation

```
     ^*+1                # make a range from 1 .. argument (whatever star)
 ^<<(    )               # replace each element with a range from 0 .. element - 1
                         # (via hyper prefix operator)
          X+1            # shift the range to 1 .. element
                         # (via cross product metaoperator)
(            )>>.reverse # reverse each list (via hyper method operator)

```

# Answer
> 5 votes
# K (ngn/k), 8 bytes

```
|',\1+!:

```

Try it online!

-2 thanks to ngn :-)

# Answer
> 4 votes
# JavaScript (ES6),  ~~50~~  49 bytes

*Saved 1 byte thanks to @Shaggy*

```
f=n=>n?[...f(n-1),(g=_=>n?[n,...g(--n)]:[])()]:[]

```

Try it online!

# Answer
> 4 votes
# PHP, 54 bytes

```
function($x){for(;$y<$x;$a[]=range(++$y,1));return$a;}

```

Try it online!

Or recursive:

# PHP, 54 bytes

```
function f($x){return$x?f($x-1)+[$x=>range($x,1)]:[];}

```

Try it online!

Or with PHP-formatted printed output:

# PHP, 38 bytes

```
for(;$x<$argn;print_r(range(++$x,1)));

```

Try it online!

# Answer
> 4 votes
# x86-16 machine code, 12 bytes

Binary:

```
00000000: 33c0 4050 ab48 75fc 58e2 f7c3         3.@P.Hu.X...

```

Unassembled listing:

```
33 C0       XOR  AX, AX         ; AX = 0
        OUT_LOOP:
40          INC  AX             ; start at 1
50          PUSH AX             ; save starting position
        IN_LOOP:
AB          STOSW               ; write to output buffer, increment DI
48          DEC  AX             ; AX--
75 FC       JNZ  IN_LOOP        ; if AX > 0, keep looping
58          POP  AX             ; restore starting position
E2 F7       LOOP OUT_LOOP
C3          RET                 ; return to caller

```

Input Number in `CX`, output array of `WORD`, at `[DI]`.

Example I/O using DOS test driver program:

# Answer
> 4 votes
# Raku, 13 bytes

```
{[\R,] 1..$_}

```

Try it online!

Cumulative reverse with the range 1 to input.

# Answer
> 4 votes
# BQN, 10 bytes

Anonymous tacit prefix function.

```
(⌽1+↕)¨1+↕

```

Try it online!

### Explanation

```
(⌽1+↕)¨1+↕
       1+↕    1.  Get list of integers from 1 to n.
      ¨       2a. For each integer i in the list...
( 1+↕)        2b. get a list of integers from 1 to i...
(⌽   )        2c. and then reverse that list.

```

# Answer
> 3 votes
# PowerShell, 19 bytes

```
1.."$args"|%{$_..1}

```

Try it online!

Generates the range from `1` to input `$args`, then constructs the reversed range for each of those numbers. Tack on a `-join` to better see how the arrays are created (because PowerShell inserts a newline between each element, it's tough to see the individual arrays).

# Answer
> 3 votes
# Python 3, 46 bytes

```
lambda n:[[*range(i+1,0,-1)]for i in range(n)]

```

Try it online!

# Answer
> 3 votes
# GolfScript, 12 (13) bytes

```
,{)),(;-1%}%`

```

```
,{)),(;-1%}%` #Reversed iota of iota
,             #0 to n-1 iota
 {        }%  #For each element in the iota
 {))      }   #Increment by 2
 {  ,     }   #Iota
 {   (;   }   #Pop leading 0
 {     -1%}   #Reverse it
            ` #Pretty output, not needed if you use a better stack-interpreter

```

Try it online!

Below is my old solution, I gained inspiration after posting and improved it.

```
),(;{),(;-1%}%`

```

Comma is the function that builds an array 0 to n-1, "iota expand".

```
),(;{),(;-1%}%` #Take in a number, output reversed expanded iota
)               #Increment input by 1
 ,              #Iota expand
  (;            #Remove leading 0
    {       }%  #For every element, do the following
    {)      }   #Increment by 1
    { ,     }   #Iota expand
    {  (;   }   #Remove leading 0
    {    -1%}   #Reverse
              ` #Pretty output; technically not needed

```

Try it online!

# Answer
> 3 votes
# Ruby, ~~34~~ 30 bytes

```
->n,*a{(1..n).map{|x|a=[x]+a}}

```

Try it online!

Thanks Value Ink (as usual) for -4 bytes.

# Answer
> 3 votes
# Factor, 45 bytes

```
: f ( n -- s ) [1,b] [ 1 [a,b] >array ] map ;

```

Try it online!

# Answer
> 3 votes
# Haskell, 27 bytes

```
f n=scanl(flip(:))[1][2..n]

```

# Answer
> 3 votes
# Zsh, 22 bytes

```
eval echo {{1..$1}..1}

```

Try it online!

`{{1..$1}..1}` -\> `{1..1} {2..1} {3..1} {4..1} ...`

`eval echo {1..1} {2..1} {3..1} ...` -\> `echo 1 2 1 3 2 1 ...`

If the sublists must be delimited, then 25 bytes for `,` or 26 bytes for newline.

# Answer
> 3 votes
# Fortran (GFortran), 47 bytes

```
read*,i
print*,("{",(j,j=k,1,-1),"}",k=1,i)
end

```

Try it online!

Could remove 8 chars by getting rid of printed brackets if anyone would believe that they are lists otherwise.

# Answer
> 3 votes
# Arturo, ~~22~~ 18 bytes

```
$=>[map&=>[@&..1]]

```

Try it

# Answer
> 3 votes
# Elm, 45 bytes

```
r=List.range 1
f=List.map(List.reverse<<r)<<r

```

Try it on Ellie

# Answer
> 2 votes
## Haskell, 74 73 51 bytes

`main=do i<-getLine;print[[x,x-1..1]|x<-[1..read i]]`

Try it online!

-22 bytes thanks to @79037662

# Answer
> 2 votes
# Brachylog, 5 bytes

```
⟦₁⟧₁ᵐ

```

Try it online!

### Explanation

```
⟦₁     Ascending range from 1 to the input
    ᵐ  Map:
  ⟧₁     Descending range from 1 to the mapped element

```

# Answer
> 2 votes
# Burlesque, 9 bytes

```
riroq<-pa

```

Try it online!

```
ri  # Read int
ro  # Range [1,N]
q<- # Boxed reverse
pa  # Operate over ((1), (1 2), (1 2 3),...)

```

Alternative 9 byter, but this also has an empty list as the first element:

```
riroiT)<-

```

# Answer
> 2 votes
# Go, 105 bytes

```
func(n int)(o[][]int){for i:=1;i<=n;i++{J:=[]int{}
for j:=i;j>0;j--{J=append(J,j)}
o=append(o,J)}
return}

```

Attempt This Online!

# Answer
> 2 votes
# shell with `seq` loop, 46 bytes

```
for n in `seq $1`;do seq -s\  -t'\n' $n 1;done

```

# Answer
> 2 votes
# JavaScript, 60 bytes

Without recursion:

```
n=>eval('for(a=[];n;a[--n]=b)for(b=[j=n];j-->1;b[n-j]=j);a')

```

Try it:

```
f=n=>eval('for(a=[];n;a[--n]=b)for(b=[j=n];j-->1;b[n-j]=j);a')

console.log(JSON.stringify(f(1)));
console.log(JSON.stringify(f(2)));
console.log(JSON.stringify(f(3)));
console.log(JSON.stringify(f(4)));
```

# Answer
> 2 votes
# Nibbles, 2 bytes

```
,$\,

```

Attempt This Online!

```
  Map
,  range
$   input (each line)
\  reverse
,   range
     it

```

# Answer
> 2 votes
# Erlang 58 bytes

```
f(N)->[lists:reverse(lists:seq(1,X))||X<-lists:seq(1,N)].

```

# Answer
> 2 votes
# FunStack alpha, 25 bytes

```
Reverse map IFrom1 IFrom1

```

Try it at Replit!

### Explanation

```
                   IFrom1  Inclusive range from 1 to the argument
            IFrom1         Inclusive range from 1 to each of those numbers
Reverse map                Reverse each sublist

```

# Answer
> 1 votes
# Python 3, ~~69~~ \\$\cdots\\$ ~~48~~ 46 bytes

```
lambda n:[[*range(i+1,0,-1)]for i in range(n)]

```

Try it online!

# Answer
> 1 votes
# Pyth, 5 bytes

```
_MSMS

```

Try it online!

# Answer
> 1 votes
# Japt, 4 bytes

```
õ!õ1

```

Try it here

# Answer
> 1 votes
# C (gcc), 54 bytes

```
i,t;f(n){for(i=0;n/++i;)for(t=i;t;)printf("%d ",t--);}

```

Try it online!

# Answer
> 1 votes
# PHP, 54 bytes

```
for(;$i++<$argn;)$a[]=str_split($s=$i.$s);print_r($a);

```

Try it online!

# Answer
> 1 votes
# Retina, 20 bytes

```
.+
*
L$w`_+
$.&
O$^`

```

Try it online! Explanation:

```
.+
*

```

Convert the input to a string of `_`s of that length.

```
L$w`_+
$.&

```

List the lengths of all the possible substrings. The way Retina enumerates substrings means that the lengths are in the exact reverse of the desired order.

```
O$^`

```

Reverse the output line-by-line.

# Answer
> 1 votes
# , 11 bytes

```
[:<@|.\1+i.

```

Try it online!

```
         i.    a list 0..n-1
        +      add
       1       one to it -> a list 1..n
      \        for each prefix of the list (1, 1 2, 1 2 3...)
    |.         reverse
   @           and
  <            box
[:             cap the fork

```

# K (oK), 14 bytes

```
{{|1+!x}'1+!x}

```

Try it online!

```
{            }  a function with parameter x
           !x   a list 0..n-1
         1+     add one to it -> a list 1..n
 {     }'       apply this function to each of the elements of the above list
     !x         a list 0..n-1
   1+           add one to it -> a list 1..n
  |             reverse

```

# Answer
> 1 votes
# MathGolf, 4 bytes

```
╒╒mx

```

Try it online.

**Explanation:**

```
╒     # Push a list in the range [1, (implicit) input-integer]
 ╒    # Convert each inner value to a list in the range [1, value]
  m   # Map over this list of lists:
   x  #  And reverse each inner list
      # (after which the entire stack joined together is output implicitly as result)

```

# Answer
> 1 votes
# C (gcc), 42

I felt like there must be an elegant recursive solution to this. This is the shortest I could come up with, though there is probably more room for golf.

* 4 bytes saved thanks to @S.S.Anne.

```
f(n,m){n&&f(n-m/n,m%n+1)*printf("%d ",m);}

```

Initially, the function is called as `f(N, 1)`, where N is the input integer.

Try it online!

# Answer
> 1 votes
# Java (JDK), 98 bytes

```
n->{int a[][]=new int[n][],i=0,j;for(;i<n;)for(a[i]=new int[j=++i];j>0;)a[i-1][--j]=i-j;return a;}

```

Try it online!

# Answer
> 1 votes
# Coffeescript, 29 bytes

```
r=(x)->[[y..1]for y in[1..x]]

```

Try it online!

# Answer
> 1 votes
# T-SQL, 145 bytes

```
WITH a(n)as(SELECT number FROM spt_values
WHERE'p'=type)SELECT string_agg(@+1-a.n,' ')FROM
a,a b WHERE a.n<=@ and b.n<a.n
GROUP BY b.n ORDER BY 1

```

**Try it online**

# Answer
> 1 votes
# Stax, 6 bytes

```
RmRr|u

```

Run and debug it

# Answer
> 1 votes
# Pyt, 5 bytes

```
řĐř-⁺

```

Try it online!

Code worked on input of 3:

| Code | Stack | Description |
| --- | --- | --- |
| `ř` | \[1,2,3\] | implicit input; **ř**angify \[1,2,...,n\] |
| `Đ` | \[1,2,3\] \[1,2,3\] | **Đ**uplicate |
| `ř` | \[1,2,3\] \[\[1\],\[1,2\],\[1,2,3\]\] | **ř**angify |
| `-` | \[\[0\],\[1,0\],\[2,1,0\]\] | subtract |
|  | \[\[1\],\[2,1\],\[3,2,1\]\] | increment; implicit print |

# Answer
> 1 votes
# Vyxal, 3 bytes

```
ɾɾR

```

Try it Online!

Can't believe I never answered this challenge despite the fact it was asked by one of the greatest golfers I ever knew

## Explained

```
ɾɾR
ɾ   # the range [1, input]
 ɾ  # and that for each item in the range
  R # vectorised reverse

```

# Answer
> 1 votes
# tinylisp 2, 14 bytes

```
(.(p m to1)1to

```

Try it at Replit! Example session:

```
tl2> (.(p m to1)1to
(() (_arg) ((p m to1) (1to _arg)))
tl2> (d F _)
F
tl2> (F 5)
((1) (2 1) (3 2 1) (4 3 2 1) (5 4 3 2 1))

```

### Explanation

```
(.(p m to1)1to)
  (p      )      ; Partially apply
     m           ;  the map function
       to1       ;  to the to1 function (given N, return the list of numbers from
                 ;  N down to 1)
(.            )  ; Compose that with
           1to   ; the 1to function (given N, return the list of numbers from
                 ; 1 up to N)

```

Thus: take one argument `N`; generate the range from 1 to `N`; then for each of those numbers, generate the range from it down to 1.

# Answer
> 1 votes
# Swift 5.6+, 42 bytes

```
{(1...$0).map{n->[_]in(1...n).reversed()}}

```

Type information (here `->[_]`) is required. Without it, the return type is `[ReversedCollection<ClosedRange<_>>]`, as the range primitive's `.reversed()` method is lazy by default.

SwiftFiddle link with both ways (with and without type info) to highlight the difference.

This technically isn't even full type info, as the actual type of number used is left unspecified, as `_`. It doesn't even necessarily have to be a builtin type as long as it meets certain requirements. With full generics, the function might look something like this (ungolfed):

```
func f<T: Strideable & ExpressibleByIntegerLiteral>(_ n: T) -> [[T]]
where T.Stride: SignedInteger {
    return (1 ... n).map { i in
        (1 ... i).reversed()
    }
}

```

# Answer
> 1 votes
# Pip, `-p` 12 bytes

```
Fl\,aO R\,lx

```

How?

```
Fl\,aO R\,lx  : One arg; int
    a         : First input(max for range)
Fl            : For each in:
  \,a         : Range from 1 to a
        \,l     : Range from 1 to l(int from range)
       R        : Reverse
     O          : Output
           x  : Trigger output

```

Try It Online!

# Answer
> 1 votes
# Julia 1.0, ~~27~~ 21 bytes

```
~n=1:n.|>i->[i:-1:1;]

```

Try it online!

-6 bytes (!!) thanks to MarcMush: Replace `map` with a broadcast `.|>`

# Answer
> 1 votes
# Nekomata, 4 bytes

```
RRᵐ↔

```

Attempt This Online!

```
R       Range
 R      Range
  ᵐ     Map
   ↔    Reverse

```

# Answer
> 1 votes
# J-uby, ~~19~~ 13 bytes

```
:+|:*&(:+|:~)

```

Attempt This Online!

## Explanation

```
:+ | :* & (:+ | :~)
:+ |                 # Range 1..input, then
     :* & (       )  # Map with...
           :+ | :~   #   Range 1..n, then reverse

```

# Answer
> 1 votes
# Thunno 2, 3 bytes

```
RRṃ

```

Attempt This Online!

#### Explanation

```
RRṃ  # Implicit input   ->  5
R    # Push [1..input]  ->  [1 2 3 4 5]
 R   # Push [1..each]   ->  [[1] [1 2] [1 2 3] [1 2 3 4] [1 2 3 4 5]]
  ṃ  # Reverse each     ->  [[1] [2 1] [3 2 1] [4 3 2 1] [5 4 3 2 1]]
     # Implicit output

```

# Answer
> 1 votes
# Pip `-p`, 7 bytes

```
R*\,\,a

```

Attempt This Online!

### Explanation

```
R*\,\,a
      a  ; Command-line argument
    \,   ; Inclusive range from 1 to that number
  \,     ; Inclusive range from 1 to each of those numbers
R*       ; Reverse each

```

# Answer
> 1 votes
# Uiua SBCS, 7 bytes

```
¯⍚⇌⍚⇡⇡¯

```

Try it!

```
¯⍚⇌⍚⇡⇡¯
      ¯  # negate
     ⇡   # range
   ⍚⇡    # range w/ boxing
 ⍚⇌      # reverse each
¯        # negate

```

# Answer
> 1 votes
# Swift 5.9, 44 bytes

```
let f={(1...$0).map{(1...$0).reversed()+[]}}

```

# Answer
> 0 votes
# Charcoal, 9 bytes

```
ＩＥＮ⮌Ｅ⊕ι⊕μ

```

Try it online! Link is to verbose version of code. Explanation:

```
  Ｎ         Input as a number
 Ｅ          Map over implicit 0-indexed range
      ι     Current index
     ⊕      Incremented
    Ｅ       Map over implicit 0-indexed range
        μ   Inner index
       ⊕    Incremented
   ⮌        Reversed
Ｉ           Cast to string for implicit print

```

There are other ways of getting the inner range such as `InclusiveRange(1, Incremented(i))` and `Range(1, Plus(2, i))` for the same byte count.

# Answer
> 0 votes
# Clojure, 36 bytes

```
#(for[i(range %)](range(inc i)0 -1))

```

Try it online!

# Answer
> 0 votes
# Kotlin, 37 bytes

```
{(1..it).map{(it downTo 1).toList()}}

```

Try it online!

---
Tags: code-golf
---