title: RGB to hexadecimal

text:
# Question
Title: RGB to hexadecimal
> Based off a Scratch project

The pen extension in Scratch has a `set pen color to ()` block. The `()` is normally a color dropdown, but you can also use the `join()()` block. In the `join()()` block, normally a hex value is in the first input, but the second is just an empty string.

However, many new Scratchers that want to take advantage of this find it hard (after all we count in decimal). Your task today, is: given three positive integers `r`,`g`,`b`, calculate the hex value and return it as `#rrggbb`.

## Input:

`r`, `g`, `b`.

1. \\$0\le r\le255\\$
2. \\$0\le g\le255\\$
3. \\$0\le b\le255\\$
4. Input will always follow these rules
5. Input won't have leading zeros except for `0` itself

## Output

A string in the format `#rrggbb`. Hexadecimal letters can be all uppercase or all lowercase.

## Method

1. Convert `r`,`g`,`b` to hexadecimal
2. Concatenate `r`,`g`,`b`
3. Prepend a `#`
4. Return it

## Testcases:

```
r, g, b     -> Output

0, 127, 255   -> #007fff
1, 1, 1       -> #010101
245, 43, 2    -> #f52b02
72, 1, 134    -> #480186
0, 0, 0       -> #000000
255, 255, 255 -> #ffffff

```

This is , so shortest answer wins!

**NOTE**: There's an earlier question that qualifies this as a duplicate, but it's closed (because the scoring criterion was ambiguous)

# Answer
# Thunno 2 `j`, 5 bytes

```
Ḥ2ṛ'#

```

Attempt This Online!

#### Explanation

```
Ḥ2ṛ'#  # Implicit input
Ḥ      # Convert each to hexadecimal
 2ṛ    # Pad each with 0s to length 2
   '#  # Push a "#" to the stack
       # Implicit output of joined stack

```
> 1 votes

# Answer
# Python 3, 22 bytes

```
("#"+"%02x"*3).__mod__

```

Try it online!

Takes inputs as a tuple. The idea is to avoid a `lambda` or `def` by having the answer be an object method.

Same length:

```
f"#{'%02x'*3}".__mod__

```
> 16 votes

# Answer
# `[5,171,30]` \- 05AB1E, 9 bytes

```
₁+h€¦J'#ì

```

Input as list `[r,g,b]`. Outputs in uppercase.

Try it online or verify all test cases.

**Explanation:**

```
₁+         # Add 256 to each value in the (implicit) input-triplet
  h        # Convert each from integer to a hexadecimal string
   €¦      # Remove the leading "1" from each string
     J     # Join them together
      '#ì '# Prepend a leading "#"
           # (after which the result is output implicitly)

```
> 7 votes

# Answer
# C (GCC), 39 bytes

```
m(r,g,b){printf("#%06x",r<<16|g<<8|b);}

```

Attempt This Online!

I could to this all day in every language
> 7 votes

# Answer
# , 20 bytes

```
\(...)rgb(...,m=255)

```

Attempt This Online!

Somehow, when I first posted this answer, I managed to overlook the linked related challenge, where it was clearly pointed out that R has a built-in for this specific task...

My original non-built-in solution:

# , 38 bytes

```
cat("#",sprintf("%02x",scan()),sep="")

```

Attempt This Online!
> 7 votes

# Answer
# JavaScript (ES6), 49 bytes

Not the right tool for the job.

Expects `[r,g,b]`.

```
a=>'#'+a.map(x=>(x>>4&&'')+x.toString(16)).join``

```

Try it online!

---

# JavaScript (ES6), 53 bytes

Expects `r,g,b`.

```
(r,g,b)=>'#'+(r+256<<16|g<<8|b).toString(16).slice(1)

```

Try it online!
> 5 votes

# Answer
# Vyxal `s`, 7 bytes

```
H2↳›\#p

```

Try it Online!

The benefits of string padding. And flags. Helps not be beaten by half a byte :p

## Explained

```
H2↳›\#p
H         # Convert each item in the input to hexadecimal
 2↳›      # append 0s until each string is of length 2
    \#p   # and prepend a "#"
          # the s flag joins the top of the stack into a single string

```
> 5 votes

# Answer
# Ruby, 19 bytes

```
->*v{?#+"%02x"*3%v}

```

Try it online!
> 5 votes

# Answer
# Excel, ~~31~~ 29 bytes

-7 bytes thanks to Dominic van Essen

-2 bytes thanks to Taylor Alex Raine

```
="#"&CONCAT(DEC2HEX(0&A1#,2))

```

Where `A1` contains the following: `={0,127,255}`.
> 5 votes

# Answer
# Jelly, 9 bytes

```
”#2Øhṗị@‘

```

A full program that accepts a list of integers from \\$\[0,255\]\\$ and prints the resulting hexadecimal string.

**Try it online!**

...a fair bit shorter than the naive approach of a monadic Link like `+⁹b⁴Ḋ€‘ịØh”#;` which comes in at 13 bytes - TIO.

### How?

```
”#2Øhṗị@‘ - Main Link: list of integers, Colours
”#        - '#' character
            ... the chaining of `nilad nilad nilad` (”#2Øh)
                forces this to be printed to STDOUT with no trailing character(s)
  2       - two
   Øh     - hexadecimal characters -> "0123456789abcdef"
     ṗ    - Cartesian power -> ["00","01",...,"ff"]
        ‘ - increment (Colours) (vectorises)
       @  - with swapped arguments:
      ị   -   index into
          - implicit, smashing print

```
> 4 votes

# Answer
# Nibbles, 7.5 bytes (15 nibbles)

```
"#"+.$&"0"2hex

```

```
"#"+.$&"0"2hex
    .           # map over
     $          # each number in the input
           hex  # converting it to hexadecimal
      $         # and justifying it
          2     # to two characters wide
       "0"      # using "0" as filler,
   +            # then, flatten this list
"#"             # and prepend a "#" character.

```
> 4 votes

# Answer
# CP-1610 machine code, 34 DECLEs1 = 42.5 bytes2

*1. A CP-1610 opcode is encoded with a 10-bit value (0x000 to 0x3FF), known as a 'DECLE'.*
*2. This routine is 34 DECLEs long, i.e. 340 bits. As per the exception described in this meta answer, the score is **42.5 bytes**.*

A routine expecting a pointer to three bytes in **R3** and writing the result at **R4** (in white, assuming ColorStack mode).

### Test code

```
    |           |        ROMW    10            ; 10-bit ROM
    |           |        ORG     $4800         ; map the program at $4800
    |           |
4800|001        |        SDBD                  ; set up an ISR for minimal
4801|2B8 030 048|        MVII    #isr,   R0    ; STIC initialization
4804|240 100    |        MVO     R0,     $100
4806|040        |        SWAP    R0
4807|240 101    |        MVO     R0,     $101
    |           |
4809|002        |        EIS                   ; enable interrupts
    |           |
480A|001        |        SDBD                  ; R4 = BACKTAB pointer
480B|2BC 000 002|        MVII    #$200,  R4
480E|001        |        SDBD                  ; R3 = pointer to test cases
480F|2BB 01E 048|        MVII    #test,  R3
    |           |
4812|004 148 040|loop    CALL    rgb           ; invoke our routine
    |           |
4815|2FC 00D    |        ADDI    #13,    R4    ; advance to the beginning
    |           |                              ; of the next line
4817|001        |        SDBD
4818|37B 030 048|        CMPI    #done,  R3    ; done?
481B|225 00A    |        BLT     loop
    |           |
481D|017        |        DECR    R7            ; loop forever
    |           |
481E|000 07F 0FF|test    DECLE   0, 127, 255   ; #007fff
4821|001 001 001|        DECLE   1, 1, 1       ; #010101
4824|0F5 02B 002|        DECLE   245, 43, 2    ; #f52b02
4827|048 001 086|        DECLE   72, 1, 134    ; #480186
482A|000 000 000|        DECLE   0, 0, 0       ; #000000
482D|0FF 0FF 0FF|        DECLE   255, 255, 255 ; #ffffff
    |           |done
    |           |        ;; ------------------------------------------- ;;
    |           |        ;;  ISR                                        ;;
    |           |        ;; ------------------------------------------- ;;
    |           |isr     PROC
4830|240 020    |        MVO     R0,     $0020 ; enable display
4832|280 021    |        MVI     $0021,  R0    ; colorstack mode
    |           |
4834|1C0        |        CLRR    R0
4835|240 030    |        MVO     R0,     $0030 ; no horizontal delay
4837|240 031    |        MVO     R0,     $0031 ; no vertical delay
4839|240 032    |        MVO     R0,     $0032 ; no border extension
483B|240 028    |        MVO     R0,     $0028 ; black background
483D|240 02C    |        MVO     R0,     $002C ; black border
    |           |
483F|0AF        |        JR      R5            ; return from ISR
    |           |        ENDP

```

### Routine ($4840-$4861)

```
    |           |        ;; ------------------------------------------- ;;
    |           |        ;;  our routine                                ;;
    |           |        ;; ------------------------------------------- ;;
    |           |rgb     PROC
4840|275        |        PSHR    R5            ; push the return address
    |           |
4841|2B8 01F    |        MVII    #$1F,   R0    ; draw the '#'
4843|260        |        MVO@    R0,     R4
    |           |
4844|2BA 003    |        MVII    #3,     R2    ; repeat 3 times
    |           |
4846|298        |@@loop  MVI@    R3,     R0    ; R0 = byte to display
4847|00B        |        INCR    R3            ; advance R3
4848|004 148 054|        CALL    @@hexa        ; draw the upper nibble
484B|04C        |        SLL     R0,     2     ; shift the lower nibble
484C|04C        |        SLL     R0,     2
484D|004 148 054|        CALL    @@hexa        ; draw it
4850|012        |        DECR    R2            ; loop?
4851|22C 00C    |        BNEQ    @@loop
    |           |
4853|2B7        |        PULR    R7            ; return
    |           |
4854|081        |@@hexa  MOVR    R0,     R1    ; copy R0 into R1
4855|3B9 0F0    |        ANDI    #$F0,   R1    ; isolate the upper nibble
4857|2F9 10F    |        ADDI    #$10F,  R1    ; add the offset for '0'
    |           |                              ; and set the lower nibble
    |           |                              ; so that we write in white
4859|379 19F    |        CMPI    #$19F,  R1    ; if greater than '9' ...
485B|206 002    |        BLE     @@print
    |           |
485D|2F9 270    |        ADDI    #$270,  R1    ; ... advance to 'a'
    |           |
485F|061        |@@print SLR     R1            ; right-shift to get the
    |           |                              ; final value
4860|261        |        MVO@    R1,     R4    ; write it
4861|0AF        |        JR      R5            ; return
    |           |        ENDP

```

### Output

*screenshot from jzIntv*
> 4 votes

# Answer
# Python 3, 20 bytes

```
lambda x:"#"+x.hex()

```

Try it online!

Takes input as a `bytearray`.

Test bed borrowed from @xnor.
> 4 votes

# Answer
# C (gcc), ~~86 84 76 75 69 65 61~~ 57 bytes

```
b;main(c){for(;~scanf("%d",&c);printf("#%02X"+!!b++,c));}

```

Try it online!

* Kudos to @mousetail for shaving 2 bytes (from 86 to 84)
* Kudos to @corvus\_192 for shaving 4 bytes (from 65 to 61)
* Kudos to @jdt for shaving 4 bytes (from 61 to 57)

### Ungolfed with comments, courtesy of @jdt:

# C (gcc), 326 bytes

```
// all global and static variables are initiated to 0.
int b = 0;

main(int c)
{
    // scanf will retun -1 when done. ~-1 = 0
    while (~scanf("%d",&c))
    {
	// Here we do some pointer arithmetic.
        char* format = "#%02X";
        printf(format + (b != 0) , c);

        // now we increment b
        b++;
    }
}

```

Try it online!
> 4 votes

# Answer
# Python, ~~38~~ 23 bytes

* -1 byte thanks to @py3\_and\_c\_programmer

```
lambda*x:"#"+"%02x"*3%x

```

Attempt This Online!
> 3 votes

# Answer
# Perl 5 \+ `-pl043`, 19 bytes

```
$\.=unpack H2,chr}{
```

Try it online!

## Explanation

Uses the commandline flag `-l043` to prepopulate `$\` with `'#'` and for each input line, appends the result of `unpack`ing the number to `H2` (`0`-padded hex representation).
> 3 votes

# Answer
# Java 8, ~~41~~ 40 bytes

```
(r,g,b)->"".format("#%06x",r<<16|g<<8|b)

```

-1 byte thanks to *@Arnauld* by porting @mousetail's C answer.

Output in lowercase. Could be in uppercase by replacing the `x` with `X`.

Try it online.

**Explanation:**

```
(r,g,b)->             // Method with three integer parameters and String return-type
  "".format("#%06x",  //  Return a String with a format as:
             #        //   A leading hash "#"
              %  x    //   And an integer converted to a hexadecimal value
                6     //   of size 6
               0      //   with potential leading 0s if it's smaller than 6
                      //  Where the integer is:
    r<<16             //   Input `r` bitwise right-shifted by 16
    |                 //   Bitwise-ORed with
    g<<18             //   Input `g` bitwise right-shifted by 8
    |                 //   Bitwise-ORed with
    b)                //   Input `b` as is

```
> 3 votes

# Answer
# Retina 0.8.2, 49 bytes

```
.+
$*
%`^(.{16})*(.)*
$#1¶$#2
T`d`l`..
.\B|¶

^
#

```

Try it online! Takes input on separate lines but link is to test suite that splits on commas for convenience. Explanation:

```
.+
$*

```

Convert to unary.

```
%`^(.{16})*(.)*
$#1¶$#2

```

Divmod by `16`, resulting in a list of six integers from `0-15`.

```
T`d`l`..

```

Adjust `10-15` by transliterating `0-5` to `a-f`.

```
.\B|¶

```

Remove the leading digit from integers that used to be above `9` and join all of the digits together.

```
^
#

```

Prefix a `#`.
> 3 votes

# Answer
# Julia 1.0, 36 bytes

```
~x="#"*(string.(x,base=16,pad=2)...)

```

Try it online!

-1 byte thanks to @amelies: Replace `prod` with `*`. A single operator can behave as both a monad and dyad in Julia!
> 3 votes

# Answer
# Bash, 25

```
printf \#${f=%02x}$f$f $@

```

Try it online!
> 3 votes

# Answer
# Raku, ~~26~~ 25 bytes

```
{printf '#'~'%02x'x 3,@_}

```

Try it online!

*-1 byte thanks to @IsmaelMiguel*
> 3 votes

# Answer
# \>\<\> (Fish), 102 bytes

Since this challenge is super easy I wanted to try some esolangs.

Takes input as raw byte values.

```
"#"o03i:&82*,01.
 :9)?v68*+o.
v+"W"<;
o14&82*%01.
\.05i:&82*,01.
 06&82*%01.
 07i:&82*,01.
 52&82*%01.

```

See it in action (animated) \- Try it online

## Explanation:

This is a function that prints a single hexadecimal number:

```
 :9)?v68*+o.
v+"W"<
o
\.

```

Basically, check if the number is more than 9, if so add "W" ("W"+9 = 'a'), and print it. Otherwise add 6\*8='0'. In both cases we use . to "return" from the function.

The function wraps around the left margin since this is "dead space". Since you can't jump to the leftmost

The rest of the code is either of these 2 statements repeated:

```
07i:&82*,01.

```

First 2 values are the return pointer, it's where the function will return. Then we take input and copy 1 value to the register. We divide by 16 (2\*8), then push the start address of the print function, and call it with .

The other variant is very similar:

```
14&82*%01.

```

Again 14 is the return value. We take the value form the register, but this time modulo it by 16. Again we call the function at 01.

Notice the last function returns to 52, which is the location of the stray `;` (right of the `<` inside the function) that exits the program.

# \>\<\>, 119 bytes

```
"#"oi:&82*,:9)"'"*+"0"+o&82*%:9)"'"*+"0"+oi:&82*,:9)"'"*+"0"+o&82*%:9)"'"*+"0"+oi:&82*,:9)"'"*+"0"+o&82*%:9)"'"*+"0"+o;

```

Try it online!

Alternate solution that uses just 1 line.
> 3 votes

# Answer
# K (ngn/k), 12 bytes

```
"#",`hex@`c$

```

Try it online!

Takes input as a list of 3 integers.

``c$` Cast to string (bytes).
``hex@` Format bytes as hexadecimal values.
`"#",` Prepend a `#`.
> 3 votes

# Answer
# Bitcoin Cash Script (BitAuth IDE), 601 bytes, 93 bytes as raw bytecode

```
// Input
<127>
<0>
<255>
// Program
OP_DUP
<16> OP_MOD
OP_SWAP
<16> OP_DIV
OP_DUP <9> OP_GREATERTHAN
OP_IF
<7> OP_ADD
OP_ENDIF
<48> OP_ADD
OP_SWAP
OP_DUP <9> OP_GREATERTHAN
OP_IF
<7> OP_ADD
OP_ENDIF
<48> OP_ADD
OP_CAT
OP_ROT
OP_DUP
<16> OP_MOD
OP_SWAP
<16> OP_DIV
OP_DUP <9> OP_GREATERTHAN
OP_IF
<7> OP_ADD
OP_ENDIF
<48> OP_ADD
OP_SWAP
OP_DUP <9> OP_GREATERTHAN
OP_IF
<7> OP_ADD
OP_ENDIF
<48> OP_ADD
OP_CAT
OP_ROT
OP_DUP
<16> OP_MOD
OP_SWAP
<16> OP_DIV
OP_DUP <9> OP_GREATERTHAN
OP_IF
<7> OP_ADD
OP_ENDIF
<48> OP_ADD
OP_SWAP
OP_DUP <9> OP_GREATERTHAN
OP_IF
<7> OP_ADD
OP_ENDIF
<48> OP_ADD
OP_CAT
OP_ROT
OP_CAT OP_CAT
<'#'> OP_SWAP OP_CAT
// Output string left on stack

// We can also execute it all using raw bytecode
OP_DROP // Clean up
// Input
<127>
<0>
<255>
/// Program
0x7660977c60967659a0635793680130937c7659a0635793680130937e7b7660977c60967659a0635793680130937c7659a0635793680130937e7b7660977c60967659a0635793680130937c7659a0635793680130937e7b7e7e01237c7e

```

Try it online!
> 3 votes

# Answer
# C#, 31 bytes

```
(r,g,b)=>$"#{r:X2}{g:X2}{b:X2}"

```
> 3 votes

# Answer
# x86-32 machine code, 28 27 bytes

```
"\x6a\x23\x58\x99\xaa\xb1\x1c\xac\xd3\xc0\x3c\x0a\x1c\x69\x2f\xaa"
"\xd3\xe8\x30\xce\x75\xf4\x42\x7b\xee\x88\x27"

```

#### Requirements:

* SS:ESP-4 -\> 4 bytes of writable memory
* DS:ESI -\> 3 bytes of readable memory containing `r`, `g`, `b`
* ES:EDI -\> 8 bytes of writable memory to receive NUL-terminated ASCII string (`"#XXXXXX\0"`)
* Direction Flag clear

#### In assembly language:

```
6a 23           push 23h  ; "#"
58              pop eax
99              cdq
aa              stosb
b1 1c           mov cl, 1Ch
__byteloop:
ac              lodsb
d3 c0           rol eax, cl
__nibbleloop:
3c 0a           cmp al, 0Ah  ; someone's old trick for converting a nibble to hex
1c 69           sbb al, 69h
2f              das
aa              stosb
d3 e8           shr eax, cl
30 ce           xor dh, cl
75 f4           jnz __nibbleloop
42              inc edx
7b ee           jnp __byteloop
88 27           mov [edi], ah

```
> 3 votes

# Answer
# Scratch, 235 Bytes

Link to the editor for the script

Source:

```
when gf clicked
set[I v]to(0
set[X v]to[#
repeat(3
change[I v]by(1
set[X v]to(join(x)(join(letter(((item(I)of[C v])-((item(I)of[C v])mod(16)))+(1))of[0123456789ABCDEF])(letter(((item(I)of[C v])mod(16))+(1))of[0123456789ABCDEF
end
say(X

```

It was exhausting to put this into plain text, so I'm not golfing this down YET.
> 3 votes

# Answer
# Factor, 25 bytes

```
[ "#%02x%02x%02x"printf ]

```

Try it online!
> 2 votes

# Answer
# Sequences, \\$22 \log\_{256}(96) \approx 18.1\\$ bytes

```
"#"H3x{\016iB2jH}g""JF

```

### Explanation

```
"#"H3x{\016iB2jH}g""JF
"#"H                    // Push "#" to the list
    3x{         }       // Repeat 3 times:
           i            //   Get a numeric input
         16 B           //   Convert to hexadecimal
       \0    2j         //   Fill with 0s on the left up to 2 characters
               H        //   Append to the list
                 g      // Get the list
                  ""J   // And join by ""
                     F  // Output the joined string

```

### Screenshot
> 2 votes

# Answer
# Clojure, 30 bytes

```
#(format"#%02x%02x%02x"% %2%3)

```

Try it online!
> 2 votes

# Answer
# Gaia, 28 bytes

```
h¦⟨)₵HE¤\⟩¦¦$¦⟨0¤+3⊂ḥ⟩¦$'#¤+

```

Try it online!

28 bytes may seem like a lot of bytes until you discover that there is no "convert a number to hexadecimal as a string" built-in in Gaia. Why was "convert to base 16 as a list of digits" the thing that got added and not to string?

Using a similar algorithm to the 05AB1E and MathGolf answers would probably be longer.

Gaia does not have list input in the input box, so this is a function submission.

## Explained

```
h¦⟨)₵HE¤\⟩¦¦$¦⟨0¤+3⊂ḥ⟩¦$'#¤+
h¦                          # Convert each number to base 16 (list of digits)
  ⟨      ⟩¦¦                 # To each digit in each number:
   )                        #  Increment it to account for 1-indexing
    ₵HE                     #  and index it into the string "0123456789ABCDEF"
       ¤\                   #  Remove some extra junk from the stack
           $¦               # Convert each list to a single string
             ⟨      ⟩¦       # To each hex string:
              0¤+           #  Prepend 0
                 3⊂         #  repeat the first character of the string enough times to make it at least length 3
                   ḥ        #  remove the leading 0
                     $'#¤+  # join into a single string and prepend the # character

```
> 2 votes

# Answer
# Pyth, 11 bytes

```
s+\#%L"%02x

```

Try it online! (test suite) Takes a list of integers as input.

**Explanation:**

```
s+\#%L"%02x"Q # Whole program. Closing quote and implicit input (Q) added

     L        #   left map
    %         #   using format operator
      "%02x"  #    this string -> pad leading 0 until length 2, hex form
            Q #   into implicit input
 +            #  concatenated into
  \#          #   single character '#'
s             # joined into a single string

```
> 2 votes

# Answer
# PowerShell, 26 bytes

```
'#'+-join($args|% *g 'x2')

```

Try it online!

Ungolfed:

```
'#' + (-join ($args | ForEach-Object -MemberName ToString 'x2' -ArgumentList 'x2'))

```

Straight-forward: takes the rgb arguments, calls the method ToString('x2') for each, joins them, adds the hash.
> 2 votes

# Answer
# Haskell, 54 bytes

```
('#':).(((mapM(\_->['0'..'9']++['a'..'f'])"__")!!)=<<)

```

Try it online! Anonymous function that takes input as a list `[r, g, b]`.

### Explanation

`mapM(\_->['0'..'9']++['a'..'f'])"__"` constructs the following list:

```
["00","01","02","03","04","05","06","07","08","09","0a","0b", ... ,"fd","fe","ff"]

```

`=<<` in this context acts like `concatMap`, so for every element in the input list `[r, g, b]` we index with `!!` into the above list and concatenate the resulting strings. Finally, `('#':)` prepends the leading `#`.
> 2 votes

# Answer
# APL (Dyalog), 41 bytes

```
,/'#'∘,{((⌊⍵÷16)∘⊃,(16⊤⍵)∘⊃)⎕A,⍨⊃,/⍕¨⍳9}¨

```

You can try it on **TryAPL**!

* It's 41 bytes assuming a SBCS. In UTF-8 it's about **72 bytes**

The code asumes a list of RGB values as input (Eg. `(255 255 200)`) and returns the hex representation (Eg. `'#FFFFC7'`).

## About this solution

This solution does not rely on having a zero index array environment. The important part is this `⎕A,⍨⊃,/⍕¨⍳9` which generates a string of digits and letters staring at one, like: `123456789ABCDEF.....` which i use to create the hex string. That expression in itself is 11 characters which is a lot. We could do better by using `⎕D,⎕A`; which generates `0123456789ABC......` starting from zero. In an environment that indexes arrays starting from zero that would shave us **6 bytes for free**. But not all APLs are zero indexed. And crucially. Dyalog, which this answer is sadly relying on is NOT zero indexed by default. And to make it zero index we need to use thise expression `⎕IO←0` (Plus  if we want to just append that to our answer). Which adds those 6 bytes back. So another valid solution would be this one (Also **41 bytes**)

```
⎕IO←0⋄,/'#'∘,{((⌊⍵÷16)∘⊃,(16⊤⍵)∘⊃)⎕D,⎕A}¨

```

The reason this one is important is that. If executed in a Dyalog-compatible environment with `⎕IO←0` by default the answer will reduce to this:

```
,/'#'∘,{((⌊⍵÷16)∘⊃,(16⊤⍵)∘⊃)⎕D,⎕A}¨

```

Which would get us down to **35 bytes**

I'm still very new and I feel this can be improved quite a bit. Feel free to edit if you have any ideas!
> 2 votes

# Answer
# Japt `-P`, 11 bytes

```
msG ùT2 i'#

```

Try it

```
msG ùT2 i'#     :Implicit input of array
m               :Map
 s              :  To string in base
  G             :  16
    ù           :Left pad each
     T          :  With 0s
      2         :  To length 2
        i'#     :Prepend "#"
                :Implicitly join & output

```
> 1 votes

# Answer
# MathGolf, 9 bytes

```
'#\♠+¢m╞~

```

Port of my 05AB1E answer, so also input as list \[r,g,b\] and outputs in uppercase.

Try it online.

**Explanation:**

```
'#        '# Push character "#"
  \        # Swap so the (implicit) input-triplet is at the top
   ♠+      # Add 256 to each value in the triplet
     ¢     # Convert each to an hexadecimal string
      m╞   # Remove the leading "1" from each string
        ~  # Pop and dump the contents of the triplet to the stack
           # (after which the entire stack is joined together and output implicitly)

```
> 1 votes

# Answer
# Charcoal, 9 bytes

```
#Ｆ³﹪%02xＮ

```

Try it online! Link is to verbose version of code. Outputs in lower case. Explanation:

```
#

```

Output the leading `#`.

```
Ｆ³

```

Repeat thrice.

```
﹪%02xＮ

```

Input the next integer and format it as two hexadecimal digits.
> 1 votes

# Answer
# Red, 49 bytes

```
func[r g b][to-hex/size to 1 to#{}reduce[r g b]6]

```

Try it online!

# 53 bytes

```
func[r g b][probe to-hex/size(r << 16)+(g << 8)+ b 6]

```

Try it online!

It's shorter to `probe` the hex value instead of return it, because it `mold`s the value and keeps its literal representation.

Alternative:

# 62 bytes

```
func[r g b][h: func[c][to-hex/size c 2]rejoin["#"h r h g h b]]

```

Try it online!
> 1 votes

# Answer
# Pip, 14 bytes

```
O'#;S*g+E8TB16

```

Takes numbers as command-line arguments; outputs to stdout. Try It Online!

### Explanation

Same basic approach as Kevin Cruijssen's 05AB1E answer:

```
O'#;S*g+E8TB16
O'#;            Output a # symbol without a trailing newline
      g         List of command-line args
       +        To each, add
        E8      2 to the 8th power (256)
          TB16  Convert each to its base-16 string representation
    S*          All but first character of each
                Concatenate and autoprint (implicit)

```
> 1 votes

# Answer
# MATLAB, 38 bytes

```
@(r,g,b) ['#' num2str([r g b],'%02X')]

```

Using builtin num2str formatting to convert to a 2-field width hexadecimal value, and prepending a '#' character.

Try it online!
> 1 votes

# Answer
# Go, 60 bytes

```
import."fmt"
func f(r,g,b int){Printf("#%06x",r<<16|g<<8|b)}

```

Attempt This Online!

Port of @mousetail's answer.
> 1 votes

# Answer
# Nim, 69 bytes

```
import strutils
proc f(r,g,b:int)=echo'#'&toHex(r shl 16+g shl 8+b,6)

```

Attempt This Online!
> 1 votes

# Answer
# PHP 8.x, ~~44~~ 41 bytes

This simply creates an anonymous function that displays the expected value.

```
fn(...$a)=>'#'.bin2hex(pack('C*',...$a));

```

## How does it work?

This anonymous function receives the arguments in the RGB order.

Then, it packs the arguments into binary unsigned chars, using `pack('C*', ...)`.
In essence, this binary string contains ASCII characters, from the values to be packed.

The resulting binary string is converted to hexadecimal using `bin2hex()`.
Each byte (`0`-`255`) is already 0-padded on the left, by the function, saving a lot of work.

## Example of usage

A simple example:

```
$fn = fn(...$a)=>'#'.bin2hex(pack('C*',...$a));

// Should display: #ff4002
echo $fn(255, 64, 2);

```

You can try this on: https://onlinephp.io/c/4470e

---

---

## Old version, 44 bytes

```
fn(...$a)=>printf("#%'02x%'02x%'02x",...$a);

```

## How does it work?

The function `printf` displays the arguments formatted by a format specifier.
However, by default, it displays the value padded by spaces, instead of `0`.
As such, it is required to specify the character with `'0`.

You also need to specify that it is a 2-char long hex value, which you do with `%2x`.

Using the spread operator, I can put all arguments into an array and spread them on the function call, saving precious bytes.

---

You can try this online on: https://onlinephp.io/c/effd1
> 1 votes

# Answer
# Rust, 38 bytes

```
|r,g,b|format!("#{:06x}",r<<16|g<<8|b)

```

Try it online!

A `fn(u32,u32,u32) -> String`.
> 1 votes

# Answer
# K (ngn/k), 48 bytes

```
"#",,/{$[1=#t:"0123456789abcdef"@16\x;"0",t;t]}'

```

Try it online!

I really wish ngn/k has built-in hexadecimal converter. Takes a list of number `[r, g, b]`.

Explanation:

```
"#",,/{$[1=#t:"0123456789abcdef"@16\x;"0",t;t]}' Main function. Takes implicit input
                                               ' For each number in the list...
      {                                       }  Execute a function that
       $[                                    ]   Checks if
                                 16\x            The number turned into base 16 (a list)
              "0123456789abcdef"                 The string "0123456789abcdef"
                                @                at each number in the sub-list
            t:                                   Assigned to variable `t`
           #                                     Length
         1=                                      Is equal to 1
                                     ;           If so, then
                                      "0",t      Add a `0` before `t`
                                           ;t    Else, just return `t`
    ,/                                           Join every hexadecimal strings of each
                                                 number together
   ,                                             Concat with
"#"                                              The string "#"

```
> 1 votes

# Answer
# \>\<\>, 47 bytes

```
3:1(?v$:82*%}82*,:1%-}1-!
+ob1.>~"#"or:9)7*+"0"

```

Try it online

**Explanation**

```
3:1(?v                  !  # Loop the rest of the 1st row 3 times then move down
      $:82*%}82*,:1%-}1-   # Convert each input to pair of hex numbers
     >~"#"or               # Discard counter, print "#" and reorder stack
            :9)7*+         # add 7 if it's supposed to be a letter (>9)
+o                "0"      # add 48 to get from 1 to "1" for example
  b1.                      # handle the next number (jump to line 4 in explanation)

```
> 1 votes

# Answer
# POSIX shell, 24 bytes

```
printf \#;printf %02x $@

```

Try it online!
> 1 votes

# Answer
# , ~~18~~ 17 bytes

```
'#',16,@}.@hfd@,]

```

Accepts a list of ints. Prepending 16 is for unconditional padding. Thanks to Jonah for the -1.

Attempt This Online!
> 1 votes

# Answer
# Stax, 8 bytes

```
ü↨▌/¶$ø∟

```

Run and debug it

Unpacks to the following:

# Stax, 9 bytes

```
{2:hm'#s+

```

Run and debug it

```
{2:hm'#s+
{   m     # map the following over each value in the input array
  :h      # convert to hex, padded with zeroes to length
 2        # 2
     '#   # string literal "#"
       s  # swapped before the hex string
        + # and added

```
> 1 votes

# Answer
# Python, 55 Bytes

```
lambda x:'#'+''.join(hex(y)[2:].rjust(2,'0')for y in x)

```

Input is given as an iterable. Iterates through the list, converts to hex, snipps of the `0x`, makes sure each hex number is of length 2, joins it together and prepends a `#`.

Run on TIO
> 1 votes

# Answer
# Scala 3, ~~65~~ 45 bytes

Saved 20 bytes thanks to @The Thonnu

---

Golfed version. Attempt this online!

```
(r,g,b)=>{"#"+"%06x".format(r*65536+g*256+b)}

```

Ungolfed version. Attempt this online!

```
import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val scanner = new Scanner(System.in)
    while(true) {
      val input = scanner.nextLine()
      val rgbValues = input.split(", ").map(_.toInt)
      println(format(rgbValues(0), rgbValues(1), rgbValues(2)))
    }
  }

  def format(r: Int, g: Int, b: Int): String = {
    "#" + "%02x".format(r) + "%02x".format(g) + "%02x".format(b)
  }
}

```
> 1 votes

# Answer
# Mathematica, 39 bytes

```
ResourceFunction["ColorToHex"]@(#/255)&

```

# Mathematica (without `ResourceFunction`), 42 bytes

```
"#"<>IntegerString[#~FromDigits~256,16,6]&

```

View them on Wolfram Cloud!
> 0 votes

# Answer
# APL (Dyalog Unicode), 32 bytes

```
{'#',∊{{(⍵+1)⌷⎕D,⎕A}¨⍵⊤⍨2⍴16}¨⍵}

```

Try it online!

I'm quite sure this could be tacit, I'm just bad at it.

```
{'#',∊{{(⍵+1)⌷⎕D,⎕A}¨⍵⊤⍨2⍴16}¨⍵}
{     {                        }¨⍵} ⍝ For every number in the input
                       ⍵⊤⍨         ⍝ Convert to
                            2⍴       ⍝ 2 digits of
                              16     ⍝ Base 16
       {             }¨              ⍝ For every digit
              ⌷                      ⍝ Index
        (⍵+1)                       ⍝ Digit + 1
               ⎕D,⎕A                ⍝ Into '0123456789ABCDEFGHI...'
      ∊                              ⍝ Flatten
  '#',                               ⍝ Prepend a '#'

```
> 0 votes

# Answer
# Arturo, 17 bytes

```
$[b]->to :color b

```

Try it
> 0 votes

# Answer
# Scala, 47 bytes

Golfed version. Try it online!

```
def m(r:Int,g:Int,b:Int)=f"#$r%02x$g%02x$b%02x"

```
> 0 votes

# Answer
# Lua, 36 bytes

```
print(('#%02x%02x%02x'):format(...))

```

Try it online!
> 0 votes

# Answer
# ARBLE, 29 bytes

```
format("#%02x%02x%02x",b,g,r)

```

Try it online!
> 0 votes

# Answer
# Nim, 47 bytes

```
import colors
proc h(r,g,b:int)=echo rgb(r,g,b)

```

Attempt This Online!
> 0 votes

# Answer
# Uiua, 30 bytes

```
⊂@#♭∵($"__"∩(⍥(+@W)>9.)⌊⊃÷◿16)

```

Try it!
> 0 votes

---
Tags: code-golf, hexadecimal, color
---


title: Output each second

text:
# Question
Title: Output each second
With roughly one second (plus or minus 10 ms) between outputs, output anything.
The first output must be at most one second after the start of the program, but can be as soon as right when the program starts.
So, the first output can be up to a second after the program starts, the second exactly one second after that, the third a second after that, and so on to infinity.

The outputs do not need to be consistent, nor have any sort of delimiter. However, they must be visible (even if it's only visible when highlighted).

# Answer
# MacOS shell, 3

```
top

```

On the Mac, `top`'s default refresh period is 1 sec.

---

# Linux shell, 7

```
top -d1

```

Unfortunately on Linux, `top`'s default refresh period is more like 2 secs, so we need an extra 4 bytes.

Since this is just one command, both variants are shell-agnostic.
> 29 votes

# Answer
# Bash \+ `iputils`, 6 bytes

```
ping 0

```

send `ICMP ECHO_REQUEST` to 0 (127.0.0.1) once per second.

---

# Bash \+ `procps-ng`, 8 bytes

```
free -s1

```

Display amount of free and used memory in the system with one second between outputs.
> 13 votes

# Answer
# Python 3, ~~40~~ 39 bytes

```
import time
while[help()]:time.sleep(1)

```

Try it online!

Improved by Sisyphus
> 10 votes

# Answer
# Desmos, 5+3+3+2=13 bytes

Ticker expression (5 bytes)

```
a->-a

```

Ticker repeat delay (3 bytes)

```
999

```

Main expressions (3 bytes)

```
a=1

```

2 bytes for "file boundaries" (treat each expression as a separate "file"; there are 3 "files", so there are two "file boundaries", as per this comment)

Try It On Desmos!

To run, click the ticker icon (the metronome) near the top left of the screen. This switches the variable `a` between the values `1` and `-1` every 999 milliseconds. While this isn't outputting onto the console or stdin in the traditional sense, you can still clearly see the code switching between the `1` and the `-1`, which hopefully emulates outputting close enough.
> 8 votes

# Answer
# C (gcc), 30 bytes

Prints a newline every second.

```
main(){main(sleep(puts("")));}

```

Try it online!
> 8 votes

# Answer
# Factor, 18 bytes

```
[ .s ] 1e9 every .

```

Try it online!

`every` calls a function each time a duration has passed. If `every` is not given a duration such as `1 seconds`, and instead given a number, it defaults to nanoseconds. Thus, one billion (or 1e9) means one second. `.s` simply prints the contents of the data stack without consuming them, which in this case will print the timer object `every` uses to do its thing. The `.` at the end is necessary to satisfy the stack effect checker by removing the item on the data stack (because Factor programs must end with an empty stack), even though it will never be reached.
> 7 votes

# Answer
# Javascript, ~~22~~ ~~20~~ 19 Bytes

Thanks to @Kaiido for -2 Bytes Thanks to @Elias Holzmann for -1 Bytes

```
setInterval({},1e3)

```

https://jsfiddle.net/ry2sgkz7/
> 7 votes

# Answer
# shell + GNU/Linux core utils, 11 bytes

`watch -n1 w`

A bit of a boring answer.
> 6 votes

# Answer
# \*\>\<\>, 4 bytes

Prints "10" on startup, and once every second

```
a:nS

```

Try it online!

## Explanation

```
a      # Push 10 onto the stack
 :     # Duplicate it
  n    # Pop a value off the stack, and print it as a decimal number
   S   # Pop a value off the stack, and sleep for 100ms * the popped value

```
> 6 votes

# Answer
# Vyxal `j`, 5 bytes

```
⁽kNḞU

```

Don't Try it Online! \- it doesn't work there.

This one's kind of hilarious. It creates an infinite list of times, and then uniquifies them. The `j` flag is necessary due to how Vyxal handles printing infinite lists.

```
   Ḟ  # Generate an infinite list from...
⁽     # A function that returns
 kN   # The current time of day (hh:mm:ss)
    U # Get unique values

```
> 6 votes

# Answer
# (,), ~~60~~ ~~62~~ 61 Chars or \\$61\log\_{256}(3)\approx\\$ 12.09 Bytes

```
((),((()))((())))((()),((())))(,((()),(),(),,((())),()),,,())

```

```
((),((()))((()))) Sets variable 1 to -2.
((()),((()))) sets variable -2 (time) to itself. (AKA setting the current time to 0)
(, Start of loop
((()),(),(),,((())),()) If variable -2 (time) is at least 1, reduce it by 1 and output 1\n
,,,()) Loop forever

```

First solution sometimes had the second output less than a second after the first.
> 5 votes

# Answer
# MATL, 7 bytes

```
`@D1Y.T

```

This displays the natural numbers in order. Try at MATL online!

### How it works

```
`      % Do...while
  @    %   Push iteration index, starting at 1
  D    %   Display
  1    %   Push 1
  Y.   %   Pause for that many seconds
  T    %   Push true. This is used as loop condition, causing an infinite loop
       % End (implicit)

```
> 5 votes

# Answer
# Jelly, 5 bytes

```
1œSṄ¿

```

A full program which prints `1` and a newline and then after (just over) one second has elapsed prints another, then repeats this step forever.

It's "just over" as it takes some time to do the work. The first pause could take more than 1 second on slow hardware as Jelly has to initialise Python, and itself (create an interpreter, import some cruft, etc.) and parse the code. Subsequent pauses are unlikely to be over the 1.01 second threshold however as it just needs to check that the result is truthy and print to STDOUT.

**Try it online!** (TIO does not output anything as a program runs, but kill it while in flight and take a look; killing within a second should give a single `1` in the "Output" section, leaving it running longer should give more outputted `1`s for each second that passed.)

### How?

```
1œSṄ¿ - Main Link: no arguments
1     - set the left argument to one
    ¿ - while...
 Ṅ    - ...condition: print {left=1} and a newline, and yield {left=1}
  œS  - ...action: sleep for {implicit right=left=1} seconds and yield {left=1}

```

---

Replace  with `Ȯ` for no newlines.
> 5 votes

# Answer
# PHP, ~~22~~ ~~21~~ 17 bytes

```
for(;;a)sleep(1);

```

Try it online!

I think the naive approach will be the shortest here. On TIO the output will be visible only when stopping the program of course

EDIT: saved 1 byte by echoing the falsey result of `sleep`, it works because `sleep` returns zero instead of `false` which would have lead to an empty string

EDIT 2: stole the suggestion from this JS answer by triggering a warning instead of an echo
> 4 votes

# Answer
# TI-Basic (TI-84+), 22 bytes

```
startTmr
While 1
If checkTmr(Ans:Then
Disp Ans
startTmr
End
End

```
> 4 votes

# Answer
# Racket, ~~43~~ ~~37~~ ~~28~~ 26 bytes

## Changelog

1. Thanks to @Dadsdy for the `-2` bytes.
2. The `-4` bytes comes from converting `#lang racket` to `#!racket`.
3. Another `-9` as I found out that language statements may go into the header of TIO, and as such, don't contribute to number of bytes.
4. I just learnt about Racket's `do` loop! `-2` bytes!

## Code

```
(do()(#f)(write(sleep 1)))

```

Try it online!

---

## Explanation

We create a *do* loop that runs infinitely. Since we used `#f` (false) in `do`s second argument, the loop won't terminate as it will only terminate if there is a `#t` value.

If we were to expand this out and make it more readable, it would look like this:

```
(do () (#f)
  ; (sleep 1) doesn't return anything, so #<void> will be printed.
  (write (sleep 1)))

```

The `do` loop acts a bit similar to JavaScript's `while` loop:

```
while (!false) {
  // ...
}

```
> 4 votes

# Answer
## Batch, ~~15~~ ~~13~~ 9 bytes

```
ping -t 0

```

After some initial output, outputs the following every second:

```
PING: transmit failed. General failure.

```

Edit: Saved 4 bytes thanks to @c--.

Previous 15-byte solution:

```
timeout/t 1
%0

```

Repeatedly outputs the following:

```

C:\Users\Neil>timeout/t 1

Waiting for 1 seconds, press a key to continue ...0

C:\Users\Neil>262205.bat

```

When output is to the screen, the cursor is moved so that the `0` overwrites the `1`.
> 3 votes

# Answer
# GFA-Basic 3.51 (Atari ST), 15 bytes

A manually edited listing in .LST format. All lines end with `CR`, including the last one.

```
DO
?0
PA 50
LO

```

which expands to:

```
DO
  PRINT 0
  PAUSE 50
LOOP

```

We could use `DELAY 1` instead of `PAUSE 50`. Unfortunately, the shortest unambiguous abbreviation of `DELAY` is `DELA`.

### Output

After 5 seconds:
> 3 votes

# Answer
# Japt, ~~7~~ 4 bytes

Outputs a `ReferenceError`.
Any lowercase letter word work instead of the second `i`.

```
A³ii

```

Test it (Open your browser's console)
> 3 votes

# Answer
# x86-16 machine code, PC DOS, 14 bytes

```
00000000: b42c cd21 3ac6 74fa 8ac6 cd29 ebf4       .,.!:.t....)..

```

**Listing**

```
B4 2C       MOV  AH, 2CH        ; DOS API get system time function
        SEC_LOOP:
CD 21       INT  21H            ; Read time: DH = seconds
3A C6       CMP  AL, DH         ; second changed?
74 FA       JE   SEC_LOOP       ; continue polling if not
8A C6       MOV  AL, DH         ; save new second
CD 29       INT  29H            ; write AL to console
EB F4       JMP  SEC_LOOP       ; loop indefinitely

```

A standalone executable DOS COM program. Spams the DOS time function and writes the corresponding ASCII codepoint for the number of seconds.

*Several minutes later...*
> 3 votes

# Answer
# Julia 1.0, ~~24~~ 21 bytes

```
!x=!show(sleep(1))
!0

```

Try it online!

-3 bytes thanks to ovs: improve recursion, and redefine an operator (An argument has to be passed to it, but this can be ignored by the function)
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), 45 bytes

Nothing special

```
for(;;){Thread.Sleep(1000);Console.Write(1);}

```

Try it online!
> 3 votes

# Answer
# Nim, 36 bytes

```
import os
while 0<1:echo 1;sleep 999

```

Attempt This Online!
> 3 votes

# Answer
# Perl 5, 19 bytes

```
say 2 while sleep 1

```

Try it online!
> 3 votes

# Answer
# ELF (x86/x64, Linux), 112 bytes

Prints 'A' about once per second, indefinitely.

```
00000000: 7f45 4c46 fec0 505f e81b 0000 0000 0000  .ELF..P_........
00000010: 0200 3e00 0000 0000 0400 0000 4100 0000  ..>.........A...
00000020: 3800 0000 0000 0000 5e40 80c6 3f50 5a0f  8.......^@..?PZ.
00000030: 0504 2256 eb32 3800 0100 0000 0500 0000  .."V.28.........
00000040: 0000 0000 0000 0000 0000 0000 4100 0000  ............A...
00000050: 0100 0000 0000 0000 7000 0000 0000 0000  ........p.......
00000060: 7000 0000 0000 0000 5faf 0f05 eb96 0000  p......._.......

```

Try it online! (Prints 60 `A`'s before TIO kills the process)

## Explanation

The file abuses a lot of undefined behavior within the Linux ELF loader; the kernel is able to make a lot of (correct) assumptions when certain fields are not the right value. Here is the full NASM source.

Basically, the executable is just an ELF header, a program header (partially merged into the ELF header), and the actual program (which is spread throughout the two headers so that it doesn't take up any additional space). The full program calls `sys_write(stdout, "A", 1)`, then `sys_nanosleep({tv_sec=1, tv_nsec=112}, <nonsense valid pointer>)`, and then loops back to the start.
> 3 votes

# Answer
# , ~~27~~ 25 bytes

*Edit: -2 bytes thanks to @Dominic van Essen.*

```
repeat show(Sys.sleep(1))

```

Try it online!

This works well on my local machine, but TIO accumulates output until it finishes execution, so you don't see the progress.
> 2 votes

# Answer
# Arturo, 23 bytes

```
whileø[1:s>>{a}1pause]

```

```
whileø[     ; start infinite loop (while loop with null for condition)
    1:s     ; push duration of 1 second to stack
    >>{a}1  ; create/overwrite file named a
    pause   ; pause execution for one second (which we left on the stack earlier)
]           ; end while

```
> 2 votes

# Answer
# Pyth, 6 bytes

```
#.d
.j

```

Try it online!

### Explanation

```
#        # loop forever until error (no error will occur)
   .j    # imaginary number i, printed
 .d      # sleep for abs(i) seconds

```

It may seem weird that I have to sleep for \\$|i|\\$ seconds, why not just 1? While that would save a byte, unfortunately `.d1` is a predefined macro which returns the amount of time which has passed since the program started, which is not really useful for this challenge.
> 2 votes

# Answer
# Charcoal, 10 bytes

```
ＲＷφψＰＩ¬ΣＫＫ

```

Try it online! Link is to verbose version of code. Uses control codes to toggle the top left corner between `1` and `0`, so on TIO you need to let it run for a few seconds and then interrupt it to see the control codes and `1`s and `0`s. Explanation:

```
ＲＷφψ

```

Repeat indefinitely, showing the current canvas with a 1000ms delay on each repeat.

```
ＰＩ¬ΣＫＫ

```

Toggle the current character between `1` and `0`.
> 2 votes

# Answer
# Lua, 50 bytes

```
o=os.time::a::t=o()repeat until t<o()print()goto a

```

Try it online!

A platform independent solution. You *can* make this shorter by using `os.execute`, but that solution is both platform dependent and not very interesting.
> 2 votes

# Answer
# GBZ80 machine code (DMG mode): 19 bytes

```
21 0F FF 3E 01 E0 FF 06 78 76 70 05 20 FB 2F E0 47 18 F4

```

Assembly:

```
Entrypoint:
    ld hl, $ff0f
    ld a, $01
    ldh [$ffff], a ; only accept vblank interrupts

.outerLoop:
    ld b, 120

.innerLoop:
    db $76 ; directly encoded halt. saves one byte over "halt" in my assembler.
           ; since by deliberate design IE & IF is sometimes not zero here, we encounter the halt bug. fortunately, "ld [hl], b" is a one byte instruction whose duplication is, excluding time, transparent (with exceptions that would be familiar to those who encounter them)
    ld [hl], b ; discard the pending interrupt every other pass (even parity)
    dec b
    jr nz, .innerLoop

    cpl
    ldh [$ff47], a ; invert the palette
    jr .outerLoop

```

This is just counting vblanks, with some mangling to save a single byte from not loading an immediate to clear the vblank interrupt flag. The effect produced every second is inverting the screen colors. This does not work in CGB mode because the register for the DMG background palette does nothing in CGB mode.
> 2 votes

# Answer
# 05AB1E, 5 bytes

```
[₄=.W

```

Keeps printing `1000\n` every second.

Try it online.

**Explanation:**

```
[      # Start an infinite loop:
 ₄     #  Push 1000
  =    #  Print it with trailing newline (without popping)
   .W  #  Pop and sleep that many milliseconds

```
> 2 votes

# Answer
# Python 2, 38 Bytes

```
import time
while[time.sleep(1)]:print

```

TIO
> 2 votes

# Answer
# simply, 93 bytes

Outputs a 9x9 image with a random color, every 999 milliseconds - which is within the 10ms error range.

```
%C=run!CANVAS->init(9,9)run%C->ontick(fn()=>run%C->fillRect(0 0 9 9run%C->getRandomColor)999)

```

It does exactly what it's supposed to.

---

## Ungolfed

This code does exactly the same.

```
$fn = anonymous function() {
    $color = call %canvas->getRandomColor();
    call %canvas->fillRect(0, 0, 9, 9, $color);
};

%canvas = call !CANVAS->init(9, 9);
call %canvas->ontick($fn, 999);

```

I'm too lazy to write a full English-like version.

---

If you need more information, to confirm it does do what it's supposed to do, just add this after the code:

```
// Golfed version:
call %C->showDebug();

// Ungolfed version:
call %canvas->showDebug();

```

To make sure it is running, just check that the (manually) underlined value changes at a rate of ~1 second:

That value represents the number of frames that were actually drawn.
By default, the code avoids re-drawing the canvas if there were no updates.
And each call to `fillRect` will trigger a single update.

You can replace `ontick` with `onframe` or `onclick` to verify that the value really represents what I've said.
> 1 votes

# Answer
# Commodore BASIC (Commodore C64/C128, C16/+4, VIC-20, PET), ~61 ~45 tokenised BASIC bytes

```
0printti$:b=val(ti$)+1
1ifval(ti$)<bthen1
2goto

```

This works by using the Commodore `TI$` system variable. Firstly, this outputs the value of `TI$` to the screen (which is in HHMMSS format). It then take the value of `TI$` as a number and add one to it. It then waits until the current numeric value of `TI$` is no longer a less significant number than the `B` variable, and then we `GOTO` line 0 to output the new value of `TI$` to the screen. This continues until the `STOP` key is pressed, which will break the program (it may be continued with the `CONT` command).

Screenshot reflects an older iteration of this entry.
> 1 votes

# Answer
# PowerShell, 16 bytes

Paste it into a PS console (Windows or Core) (not using TIO because that will only show the output once the script is stopped):

```
for(){sleep 1;1}

```

Will print `1` every second until Ctrl-C is pressed.
Nothing remarkable, just for the sake of completeness when it comes to languages.
> 1 votes

# Answer
# QBasic, 13 bytes

I'm not sure how rules-bendy to get, but here's the shortest possible version:

```
?
SLEEP 1
RUN

```

You can try it at Archive.org.

### Explanation

```
?        ' Print a blank line
SLEEP 1  ' Wait 1 second
RUN      ' Restart the program

```

Once the screen is filled up with blank lines, you won't be able to see new output happening, and you can't select the outputted text. So here's a **15-byte** version that will be visually different each time something is printed:

```
?0;      ' Print 0 without a newline
SLEEP 1  ' Wait 1 second
RUN      ' Restart the program

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 21 bytes

```
Dynamic@Floor@Clock@2

```

A dynamic object that alternates between 0 and 1 every second. This only works in the Notebook interface, so no TIO link.

---

# Wolfram Language (Mathematica), 23 bytes

```
Echo@True~While~Pause@1

```

Try it online!

Prints `True` every second.
> 1 votes

# Answer
# Vyxal , 5 Bytes

```
{1¨w,

```

Try it online (collects all the output received in ten seconds (or sooner if it halts) and prints it all at once.)
> 1 votes

# Answer
# \>\<\> `-t0.5`, 2 bytes

```
1n

```

Try it online!

`><>` has an extra flag to set the time between ticks, presumably to help with debugging. This code simply outputs a `1` every 2\*0.5 seconds.
> 1 votes

# Answer
# Swift, ~~41~~ 40 bytes

```
import Darwin
while 0<1{print(sleep(1))}

```

Prints "`0\n`" every second. Probably macOS-only due to `import Darwin`.
> 1 votes

# Answer
# ARM Thumb machine code + Linux syscalls, 28 bytes

```
00: 2202       movs r2, #2    // 2 bytes
02: 2704       movs r7, #4    // write()
04: 2001       movs r0, #1    // stdout
06: a104       adr  r1, #0x18 // pointer to 0x18 "!\n"
08: df00       svc  #0        // syscall write(1, "!\n", 2)
0a: 27a2       movs r7, #162  // nanosleep()
0c: a001       adr  r0, #0x14 // pointer to 0x14
0e: 2100       movs r1, #0    // NULL
10: df00       svc  #0        // syscall nanosleep(&{1, 2593}, 0)
12: e7f6       b.n  #0x02     // jump to 0x02, r2 won't have changed
14: 0000 0001  .word 1        // 1 second
18: 0000 0a21  .word 0x0a21   // "!\n" or 2593 nanoseconds

```
> 1 votes

# Answer
# Minecraft Function, 30 bytes

```
say a
schedule function a:b 1s

```

Must be run as a function named `b` in a data pack named `a`. It prints `[Server] a` to chat once per second.

The first command simply says `a`, and the second command schedules the function to execute again in one second.
> 1 votes

# Answer
# Uiua, 11 bytes

```
⍥(&pπ&sl1)∞

```

Doesn't work online, but works locally.

```
⍥(&pπ&sl1)∞
⍥(       )∞  # infinite loop
     &sl1    # sleep for one second
  &pπ        # print pi

```
> 0 votes

# Answer
# TI-Basic (TI-84), 15 bytes

```
startTimer
Disp Ans
Repeat checkTmr(Ans
End
prgmA

```

needs to be stored in `prgmA` for the recursion

based on and improved over Yousername's answer
> 0 votes

---
Tags: code-golf, date
---


title: Become the Hydra Slayer

text:
# Question
Title: Become the Hydra Slayer
You are the best and most famous hero of the area. Lately there have been rumors that a Hydra has been hanging out in a nearby ravine. Being the brave and virtuous hero that you are you figure you'll go check it out sometime later today.

The problem with hydrae is that every time you try to cut off their heads some new ones grow back. Luckily for you you have swords that can cut off multiple heads at once. But there's a catch, if the hydra has less heads than your sword cuts, you wont be able to attack the hydra. When the hydra has exactly zero heads, you have killed it.

There is also a special sword called ***The Bisector*** that will cut off half of the Hydra's heads, but only if the number of heads is even. The Bisector *cannot be used at all* when the number of heads is odd. This is different from cutting off zero heads.

So you have decided you will write a computer program to figure out the best way to slay the hydra.

## Task

You will be given as input

* the number of heads the Hydra starts with
* the number of heads the Hydra regrows each turn
* a list of swords available for use each (each either is a bisector or cuts a fixed number of heads each turn)

You should output a list of moves that will kill the hydra in the least number of turns possible. If there is no way to kill the hydra you must output some other value indicating so (and empty list is fine if your language is strongly typed). If there are multiple optimal ways to kill the hydra you may output any one of them or all of them.

This is a question so answers will be scored in bytes, with fewer bytes being better.

## Test Cases

*More available upon request*

```
5 heads, 9 each turn,  [-1,-2,-5] -> [-5]
12 heads, 1 each turn, [/2,-1] -> No solution
8 heads, 2 each turn,  [-9, -1] -> [-1,-9]
3 heads, 23 each turn, [/2,-1,-26] -> [-1,-1,-26,-26,-26,-26,-26,-26,-26,-26]
16 heads, 1 each turn, [/2, 4, 2] -> [/2,-4,/2,-4]

```

> This question is a simplified version of the main mechanic of HydraSlayer. If you like this type of puzzle I recommend checking it out, its pretty fun. I do not have any affiliation with the game.

# Answer
> 3 votes
# JavaScript, ~~230~~ 223 bytes

```
f=(h,t,s)=>{m=h-Math.min(...s),d=1,q=[],s.map(a=>q.push([],h));while(q.length){p=q.shift(),h=q.shift(),s.map(w=>!(a=w?h+w:h/2)?d=w:!(a%1)&a>0&a<m&!f[a+=t]?f[q.push([...p,w],a),a]=1:0);d<1?(q=[],p).push(d):0}return d<1?p:[]}

```

```
_=_=>f=(h,t,s)=>{m=h-Math.min(...s),d=1,q=[],s.map(a=>q.push([],h));while(q.length){p=q.shift(),h=q.shift(),s.map(w=>!(a=w?h+w:h/2)?d=w:!(a%1)&a>0&a<m&!f[a+=t]?f[q.push([...p,w],a),a]=1:0);d<1?(q=[],p).push(d):0}return d<1?p:[]}

console.log(`[${_()(5, 9,  [-1,-2,-5])}]`);
console.log(`[${_()(12, 1, [0,-1])}]`);
console.log(`[${_()(8, 2,  [-9,-1])}]`);
console.log(`[${_()(1, 2,  [0,-4])}]`);
console.log(`[${_()(3, 2,  [0,-4,-1])}]`);
console.log(`[${_()(3, 4,  [0,-4,-1])}]`);
console.log(`[${_()(3, 23, [0,-1,-26])}]`);
console.log(`[${_()(16, 1, [0,-4,-2])}]`);
```

**Ungolfed version:**

```
f=(heads,turn,swords)=>{
  max=heads-Math.min(...swords);

  found=1;
  flags=[];
  queue=[];
  swords.map(a=>queue.push([],heads));

  while(queue.length){
    path=queue.shift();
    heads=queue.shift();

    swords.map(sword=>{
      after=sword?heads+sword:heads/2;

      if(!after){
        found=sword;
      }else if(!(after%1)&after>0&after<max&!flags[after+=turn]){
        flags[after]=1;
        queue.push([...path,sword],after);
      }
    });

    if(found<1){
      path.push(found);
      break;
    }
  }

  return found<1?path:[];
}

```

The bisector is represented as `0`.

# Answer
> 0 votes
# Python3, 197 bytes:

```
def f(h,H,s):
 q=[(h,[])]
 while q:
  h,m=q.pop(0)
  if 0==h:return m
  if m:h+=H
  for S in s:
   if((S==0.5 and 0==h%2)or(S!=0.5 and h>=abs(S)))and(h,S)not in m:q+=[([h/2,h+S][S!=0.5],m+[(h,S)])]

```

Try it online!

---
Tags: code-golf, math, game
---


title: Can the chefs go?

text:
# Question
Title: Can the chefs go?
On the TV cooking show Guy's Grocery Games, the chefs cannot begin shopping until Guy Fieri, the show's host, says "Three, two, one, go!" However, the words do not have to be all together. He often "hides" the words in things like this (based on a real example, but not quoting verbatim):

> There are *three* of you here; after this round there will be *two*; but only *one* of you will *go* shop for up to $20,000.

(At the end of the show, the winning chef must find either five or ten items, depending on the episode, from the store; the number of items found determines how much money they win.)

Fairly regularly, he succeeds in confusing the chefs and they don't go. Often, they realize after a few seconds that they can go and frantically run down the aisles trying to make up for the lost time; other times, they don't realize it until the judges start shouting "Go! Go! Go!"

Can you do better?

Write a program that determines

1. Whether the input string allows the chefs to go, and
2. If so, at what point in the string they may go.

The chefs may go if the string contains `three`, followed by zero or more other characters, followed by `two`, followed by zero or more other characters, followed by `one`, followed by zero or more other characters, followed by `go`. Matching is case-insensitive.

The point at which the chefs may go is the zero-based index of the `o` in `go`.

Because `ThreeTwoOneGo` is 13 characters, this number will always be at least 12. If the chefs can go, return the point at which they can go. If they cannot, return no value, any falsy value, or any number of your choice less than or equal to 11. This number does not need to be consistent; it's okay if it varies randomly and/or with the input, as long as it is consistently less than or equal to 11.

# Answer
> 8 votes
# R, 51 bytes

`regexpr("three.*two.*one.*g\\Ko",scan(,""),,T)[1]-1`

Thanks to Bbrk24 for pointing out that `\K` (you have to use an extra backslash in R) sets where the match is considered to start.

R has a lot of built in regex functions, and this one handily tells you where the first match starts (-1 if there is no match). It's 1-indexed though, so we have to take 1 off (and hence, if the chefs can't go, -2 is returned, but that's less than 11 so we're good).

We need to specify `perl=TRUE` to use the `\K` feature. It's cheapest to specify that positionally rather than use `pe=T`.

Depending on conventions for how the input is available, the `scan(,"")` could turn into a variable (e.g. `x`) or function (`\(x)`) saving 8 or 4 bytes respectively.

# Answer
> 6 votes
# Perl 5 \+ `-p`, 34 bytes

Returns `0` on invalid inputs. Performs a match against the input, using the result to decrement the last position of the match, via `@+`, by `1` (on successful matches, otherwise `0`).

```
$_=-/three.*?two.*?one.*?go/i+"@+"
```

Try it online!

# Answer
> 5 votes
# JavaScript (ES11), 40 bytes

*-6 bytes thanks to InSync*

Returns -1 for invalid inputs.

```
s=>s.search(/(?<=three.*two.*one.*g)o/i)

```

Attempt This Online!

### Method

Using a lookbehind assertion, we look for the position of the first `"o"` in the input string which is preceded by the pattern `"three.*two.*one.*g"`.

# Answer
> 4 votes
# Vyxal 3, 24 bytes

```
ʀ"ỌṚUmn»\6”Ṃ".*?"j∥ẋMṪL+

```

Try it Online! | Literate mode equivalent (doesn't work)

**Explanation**:

```
ʀ"ỌṚUmn»\6”Ṃ".*?"j∥ẋMṪL+
 "ỌṚUmn»\6”Ṃ".*?"j        # Split "ỌṚUmn»\6” ("three two one go") on spaces and join by ".*?"
ʀ                 ∥ẋM     # Parallel apply regex search and regex match to lowercased input
                     ṪL+  # Add length - 1 to index

```

Created with the help of Luminespire.

# Answer
> 4 votes
# Retina, 25 bytes

```
I^iw0`three.*two.*one.*go

```

Try it online!

The regex is pretty straightforward, all the magic comes from the configuration flags at the beginning:

* `I`: find the position of the matches
* `^`: use the position of the last character instead of the first
* `i`: case insensitive
* `w`: do this for all possible ways (even overlapping) of matching this regex
* `0`: return only the first one

In practice, `w0` will make sure that we return the earliest possible complete match, and is shorter than any other option based on lazy matching (`.*?`)

# Answer
> 3 votes
# Retina 0.8.2, 36 bytes

```
i1M!`.*?three.*?two.*?one.*?g(?=o)
.

```

Try it online! Link includes test cases. Outputs `0` for disallowed inputs. Explanation:

```
i1M!`.*?three.*?two.*?one.*?g(?=o)

```

Keep only the text up to the `g` of `go` (or delete the text entirely if it doesn't contain the words in the right order).

```
.

```

Count the number of characters remaining.

# Answer
> 3 votes
# Scala 3, 77 bytes

```
s=>new Regex("(?i)(?<=three.*two.*one.*g)o").findFirstMatchIn(s).map(_.start)

```

Attempt This Online!

# Answer
> 3 votes
# Jelly, 24 bytes

```
“Ç<*tẉ{cIE»Ḳṫw¥ƒŒlL’ȧạ¥L

```

Try it online!

A monadic link taking a string and returning an integer.

*Thanks to @JonathanAllan for pointing out the case-insensitive requirement!*

## Explanation

```
“Ç<*tẉ{cIE»Ḳ              | Compressed string "three two one go" split at spaces
            ṫw¥ƒŒl        | Reduce, starting with the main link argument lower-cased, then for each of the strings above, find the first position in the current string and take the tail starting from there
                   L      | Length
                    ’     | Decrease by 1
                     ȧạ¥L | And with absolute difference from this and the length of the original string

```

# Answer
> 2 votes
# 05AB1E, ~~39~~ 37 bytes

```
lηÅΔηU“„í‚•€µ‚œ“#εXsδÅ¿ƶ0K}.«âε˜D{Q}à

```

What a mess.. Once again I hate that 05AB1E lacks a builtin to get all matching indices, instead of only the first.. The `ηU` and `εXsδÅ¿ƶ0K}` are all to do that manually.. -\_-

Will output `-1` if it's invalid.

Try it online or verify a few test cases.

**Explanation:**

```
l                # Convert the (implicit) input-string to lowercase
 η               # Convert it to a list of prefixes
  ÅΔ             # Get the index of the first prefix that's truthy for
                 # (or -1 if none are):
    η            #  Get the prefixes of the current prefix
     U           #  Pop and store it in variable `X`
    “„í‚•€µ‚œ“   #  Push dictionary string "three two one go"
     #           #  Split it on spaces
      ε          #  Map over all four words:
       X         #   Push the earlier list of prefixes of the prefix
        s        #   Swap so the current word is at the top again
         δ       #   Map over each prefix, using the word as argument:
          Å¿     #    Check whether the prefix ends with the word as substring
            ƶ    #   Multiply each check by its 1-based index
             0K  #   Remove all 0s
      }.«        #  After the map: reduce this list of lists by:
         â       #   Taking the cartesian product of two lists
          ε      #  Map over each combination of values:
           ˜     #   Flatten it to a single list
            D{Q  #   Check if the four indices are in increasing order:
            D    #    Duplicate the list
             {   #    Sort the copy
              Q  #    Check if both lists are still the same
          }à     #  After the map: check if any was truthy
                 # (after which the found index is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `“„í‚•€µ‚œ“` is `"three two one go"`.

# Answer
> 2 votes
# Charcoal, 42 bytes

```
≔θηＦ⪪”↶⌊¶z₂1γmι.Jχ” ≔✂η⌕↧ηιＬη¹η¿⊖ＬηＩ⁻Ｌθ⊖Ｌη

```

Try it online! Link is to verbose version of code. Does not output anything for disallowed inputs. Explanation:

```
≔θη

```

Make a copy of the input string.

```
Ｆ⪪”....”

```

Loop over the four relevant words.

```
≔✂η⌕↧ηιＬη¹η

```

Slice the string so that it starts at that word. (But if the word is not present, the `Find` returns `-1`, which causes the `Slice` to return the last character.)

```
¿⊖Ｌη

```

If the string still contains at least two characters (which means it begins `go`), then...

```
Ｉ⁻Ｌθ⊖Ｌη

```

Output `1` more than the number of characters removed.

# Answer
> 1 votes
# JavaScript (Node.js), 51 bytes

```
s=>(z=/three.*two.*one.*?go/gi).test(s)*z.lastIndex

```

Attempt This Online!

This outputs 0 for no match, or the index.

The `RegExp.lastIndex` property (which only works for RegExes that have the `g` flag enabled) gives the index of the end of the previous match.

# Answer
> 1 votes
# Python 3, ~~93~~ 77 bytes

I'm new to `regex`, so open to golfs. Returns an integer for truthy and a `None` object for falsy.

```
lambda n:((x:=re.search("three.*?two.*?one.*?go",n,2))and~-x.end())
import re

```

# Answer
> 1 votes
# (gcc): ~~119~~ 113 bytes

```
main(c,v)char**v;{char*s="go\0.one\0two\0three",*p=*++v;for(c=4;c--;)p+=strcasestr(p,s+4*c)-(int)p;exit(++p-*v);}

```

Edit: Thanks to everyone helping in improving the answer! :D

1. As always a minor improvement was made thanks to @ceilingcat (124 -\> 122 bytes).
2. Thanks to @Command Master for getting rid of the prototype (119 -\> 113 bytes).

# (gcc -m32): 105 bytes

```
main(c,v)char**v;{char*s="go\0.one\0two\0three",*p=*++v;for(c=4;c--;)p=strcasestr(p,s+4*c);exit(++p-*v);}

```

~~The prototype feels like a huge waste of bytes. Unfortunately, I could not figure out how to work around that. :/~~

Edit: Using the `-m32` flag you can get rid of the prototype entirely (explained in the comments below). Thanks to @Command Master for suggesting this trick. :)

Try it online

**Explanation**:

```
main(c,v)char**v;{
    // 's' contains the keywords that are padded with '.' so the pointer can
    // be moved by a fixed value to go to the next keyword.
    //
    // 'p' contains the index of each keyword (eventually the index of 'go').
    // If no match is found 'p' will be NULL and cause a segmentation fault.
    // which indicates that the input does not allow the chefs to go.
    // The sequence is stored in reverse as it saves more space.
    char*s="go\0.one\0two\0three",*p=*++v;

    for(c=4;c--;)
        // The haystack is 'p' instead of v[1] since this discards any characters
        // before the last match which prevent false positives like:
        // "two...three..one..go..."
        //
        // Adds the needle's offset from 'p' to 'p', the casting tricks the
        // compiler to get around the issue of having the declare the prototype
        // of strcasestr().
        p+=strcasestr(p,s+4*c)-(int)p;

    // 'p' has to be incremented as it contains the index of 'g' of 'go'.
    exit(++p-*v);
}

```

# Answer
> 1 votes
# Uiua 0.6.1, 38 bytes

```
-1⧻⊢⊢regex"(?is).*three.*two.*one.*go"

```

Try it yourself

# Answer
> 1 votes
# Pip, 30 bytes

```
a~-`three.*?two.*?one.*?go`D$)

```

Outputs an index, or nothing if the chefs cannot go. Try It Online!

(Note that this doesn't work on ATO as of posting, and might stop working on DSO in the future, because the way Pip currently handles regex case-insensitivity doesn't play well with newer versions of Python. I may get around to fixing that someday.)

### Explanation

```
   `three.*?two.*?one.*?go`     ; Regex, with non-greedy quantifiers
  -                             ; Make it case-insensitive
a~                              ; Find the first match in the program argument
                            $)  ; Get the index of the end of that match
                           D    ; Decrement

```

# Answer
> 1 votes
# Swift, 156 bytes

Short version:

```
func c(_ s:String)->Int{let s=s.lowercased();return s.ranges(of: /three.*two.*one.*go/).first.map({s.distance(from:s.startIndex,to:$0.upperBound)-1}) ?? 0}

```

Verbose version:

```
func c2_(_ s: String) -> Int {
    let s = s.lowercased()
    return s.ranges(of: /three.*two.*one.*go/).first.map({
        s.distance(from: s.startIndex, to: $0.upperBound) - 1
    }) ?? 0
}

```

# Answer
> 1 votes
# TypeScript’s type system, ~~213~~ 203 bytes

```
//@ts-ignore
type F<S,A=0,Z=any,B=Lowercase<S>>=B extends`${Z}three${Z}two${Z}one${Z}go${infer D}`?F<B extends`${infer B}go${D}`?B:0,[1]>:A extends 0?0:S extends`${Z}${infer R}`?F<R,[...A,1]>:A["length"]

```

Try it at the TS playground

# Answer
> 1 votes
# Gema, 38 characters

```
*\Cthree*two*one*g\Po*=@column@end
*=0

```

Sample run:

```
bash-5.2$ gema '*\Cthree*two*one*g\Po*=@column@end;*=0' <<< 'There are three of you here; after this round there will be two; but only one of you will go shop for up to $20,000.'
91

```

Try it online! / Try all ~~test~~ collected cases online!

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


title: The leading zeroes challenge

text:
# Question
Title: The leading zeroes challenge
# The challenge

Given two integers as input (`x` and `y`), output `x` as a string with as many leading zeroes necessary for it to be `y` characters long without the sign.

## Rules

* If `x` has more than `y` digits, output `x` as string without modification.
* Output as integer is not accepted, even if there are no leading zeroes.
* When `x` is negative, keep the `-` as is and operate on the absolute value.
* Negative `y` should be treated as 0, meaning you output `x` as is (but as string)

### Examples:

```
IN: (1,1)   OUT: "1"
IN: (1,2)   OUT: "01"
IN: (10,1)  OUT: "10"
IN: (-7,3)  OUT: "-007"
IN: (-1,1)  OUT: "-1"
IN: (10,-1) OUT: "10"
IN: (0,0)   OUT: "0"
IN: (0,1)   OUT: "0"
IN: (0,4)   OUT: "0000"

```

Shortest code in bytes wins, standard loopholes apply.

# Answer
> 4 votes
# Japt, ~~13~~ 8 bytes

Takes first input (`x`) as a string.

```
®©ùTV}'-

```

Try it

Saved a massive 5 bytes thanks to ETHproductions.

---

## Explanation

Implicit input of string `U=x` and integer `V=y`.

`® }'-` splits `U` to an array on the minus symbol, maps over it and rejoins it to a string with a minus symbol.

`©` is logical AND (`&&`) so if the current element is truthy (a non-empty string) then pad left (`ù`) with 0 (`T`) to length `V`.

# Answer
> 8 votes
# Pyth, 12 bytes

```
%"%0*d",+E>0

```

**Try it here!**

# Answer
> 8 votes
# Python 2, 29 bytes

```
lambda x,y:x.zfill(y+(x<'.'))

```

Try it online!

Just `str.zfill` comes so close.

# Answer
> 6 votes
# Python, 29 bytes

Take input as `f(x,y)`. Using Python's `%` operator.

```
lambda x,y:'%0*d'%(y+(x<0),x)

```

Try it online!

# Answer
> 6 votes
# 05AB1E, ~~11~~ 10 bytes

Input given as `amount_of_digits, number`

```
ÎIÄg-×ì'-†

```

Try it online!

**Explanation**

```
Î            # push 0 and first input
 IÄ          # push the absolute value of the second input
   g         # length
    -        # subtract, (input1-len(abs(input2))
     ×       # repeat the zero that many times
      ì      # prepend to the second input
       '-†   # move any "-" to the front

```

# Answer
> 5 votes
# C#, 56 bytes

Try it Online!

```
a=>b=>(a<0?"-":"")+((a<0?-a:a)+"").PadLeft(b<0?0:b,'0')

```

# Answer
> 5 votes
# **Python 3.6, ~~28~~ 37 bytes**

```
lambda x,y:f'{x:0{(y,0)[y<0]+(x<0)}}'

```

Try it online! (Test case from Colera Su's answer)

Taking advantage of the new way to format strings in python 3.6

+9 bytes to handle `y<0`

# Answer
> 5 votes
# Java (OpenJDK 8), 47 bytes

```
x->y->"".format("%0"+((y<1?1:y)-(x>>31))+"d",x)

```

Try it online!

At first I thought, easy, 30 chars max (which is quite short when manipulating strings in Java). Then the exceptions happened.

# Answer
> 5 votes
# JavaScript (ES6), 42

Recursive, parameters in reverse order, first y then x. And Currying

```
y=>r=x=>x<0?'-'+r(-x):`${x}`.padStart(y,0)

```

**Test**

```
var F=
y=>r=x=>x<0?'-'+r(-x):`${x}`.padStart(y,0)

;`IN: (1,1)   OUT: "1"
IN: (1,2)   OUT: "01"
IN: (10,1)  OUT: "10"
IN: (-7,3)  OUT: "-007"
IN: (-1,1)  OUT: "-1"
IN: (10,-1) OUT: "10"
IN: (0,0)   OUT: "0"
IN: (0,1)   OUT: "0"
IN: (0,4)   OUT: "0000"`
.split(`\n`).map(r => r.match(/[-\d]+/g))
.forEach(([x,y,k])=>{
  o = F(y)(x)
  ok = o == k
  console.log(ok?'OK':'KO',x,y,'->', o)
})
```

# Answer
> 5 votes
# bash, ~~27~~, 25 bytes

-2 bytes thanks to Bruce Forte

```
printf %0$[$2+($1<0)]d $1

```

try it online

# Answer
> 5 votes
# R, ~~56~~ 48 bytes

```
function(x,y)sprintf(paste0("%0",y+(x<0),"d"),x)

```

Try it online!

-8 bytes thanks to djhurio

### Explanation

* `sprintf("%0zd",x)` returns `x` as a string padded with zeros to be of length `z`
* `paste0("%0",y+(x<0),"d")` constructs the string `"%0zd"`, where `z` is `y`, plus 1 if `x` is less than zero
* If `z` is less than the number of digits in `x`, `x` is printed as a string as is

# Answer
> 5 votes
# Husk, 12 bytes

```
Ö±Ωo≥⁰#±:'0s

```

Try it online!

## Explanation

```
Ö±Ωo≥⁰#±:'0s  Inputs are y=4 and x=-20
           s  Convert x to string: "-20"
        :'0   Prepend '0'
  Ω           until
      #±      the number of digits
   o≥⁰        is at least y: "00-20"
Ö±            Sort by is-digit: "-0020"
              Print implicitly.

```

# Answer
> 4 votes
## Retina, 39 bytes

```
\d+$
$*0
((\d)*),(?<-2>-0+|0)*(0*)
$3$1

```

Try it online!

Input should be comma-separated with the number first and the width second.

# Answer
> 4 votes
## Alice, 23 bytes

```
/oRe./'+Ao
\I*tI&0-R$@/

```

Try it online!

Input should be linefeed-separated with the number on the first line and the width on the second.

### Explanation

```
/...
\...@/

```

This is the usual framework for linear programs in Ordinal mode. The only catch in this case is this bit:

```
.../...
...&...

```

This causes the IP to enter Cardinal mode vertically and execute just the `&` in Cardinal mode before resuming in Ordinal mode.

Unfolding the zigzag control flow then gives:

```
IRt.&'-A$o*eI/&/0+Ro@

I    Read the first line of input (the value) as a string.
R    Reverse the string.
t.   Split off the last character and duplicate it.
&    Fold the next command over this string. This doesn't really do anything,
     because the string contains only one character (so folding the next
     command is identical to executing it normally).
'-   Push "-".
A    Set intersection. Gives "-" for negative inputs and "" otherwise.
$o   If it's "-", print it, otherwise it must have been a digit which we
     leave on the stack.
*    Join the digit back onto the number. If the number was negative, this
     joins the (absolute value of the) number to an implicit empty string,
     doing nothing.
e    Push an empty string.
I    Read the width W.
/&/  Iterate the next command W times.
0    Append a zero. So we get a string of W zeros on top of the absolute
     value of the input number.
+    Superimpose. This takes the character-wise maximum of both strings
     and appends extraneous characters from the longer string. Since the
     string of zeros can never be larger than the digits in the input,
     the input itself will be uneffected, but extraneous zeros are appended,
     padding the string to the required length.
R    Reverse the result.
o    Print it.
@    Terminate the program.

```

Here are two alternatives, also at 23 bytes, which use Cardinal `H` (*abs*) to get rid of the `-`:

```
/R.I&0-RoH
\Ie#\'+Ao\@/

```

```
/R.H#/.+Xo
\Ie\I&0QRo@/

```

In principle, these are a command shorter, but the `&` doesn't fit into a position where there's a 1-character string on the stack, so we need to skip it with a `#`.

# Answer
> 4 votes
# Charcoal, 16 13 bytes

```
‹Ｎ⁰﹪⁺⁺%0ηd↔Ｉθ

```

Try it online!

This is the shortest I could get using Charcoal without printing leading or trailing whitespaces. At least I am now starting to understand how to use the `Modulo` function to format strings.

The deverbosed code is as follows:

```
Print(Less(InputNumber(),0));    # Prints a - if the first input is less than 0
Print(Modulo(Add(Add("%0",h),"d"),Abs(Cast(q))));   # q: first input;  h: second input

```
* 3 bytes saved thanks to Neil!

# Answer
> 4 votes
# PHP, 45 bytes

```
printf("%0".($argv[2]+(0>$n=$argv[1])).d,$n);

```

or

```
[,$n,$e]=$argv;printf("%0".($e+(0>$n)).d,$n);       # requires PHP 7.1 or later

```

Run with `-nr` or try them online.

# Answer
> 4 votes
# C, 33 bytes

```
f(x,y){printf("%0*d",y+(x<0),x);}

```

Try it online!

# Answer
> 3 votes
# Mathematica, 118 bytes

```
(j=ToString;If[#2<=0,j@#,If[(z=IntegerLength@#)>=#2,t=z,t=#2];s=j/@PadLeft[IntegerDigits@#,t];If[#>=0,""<>s,"-"<>s]])&

```

Try it online!

# Answer
> 3 votes
# Mathematica, ~~63~~ 62 bytes

```
If[#<0,"-",""]<>IntegerString[#,10,Max[#2,IntegerLength@#,1]]&

```

Try it online!

# Answer
> 2 votes
# Haskell, 54 bytes

```
x#y|s<-show$abs$x=['-'|x<0]++('0'<$[length s+1..y])++s

```

Try it online!

# Answer
> 2 votes
# Excel, 29 bytes

Using Excel's `TEXT` functionality ("Converts a value to text in a specific number format").

`x` in A1, `y` in B1

```
=TEXT(A1,REPT("0",MAX(1,B1)))

```

# Answer
> 2 votes
# Octave, 44 bytes

```
@(x,y)fprintf(['%0',num2str(y+(x<0)),'d'],x)

```

Try it online!

# Answer
> 2 votes
# Japt, ~~14~~ 12 bytes

*Saved 2 bytes thanks to @ETHproductions*

```
s r"%d+"_ù0V

```

Try it online

# Answer
> 2 votes
# Ruby, ~~31~~ 28 bytes

Thanks Carl for saving 3 bytes using interpolation.

```
->x,y{"%0#{y+(x<0?1:0)}d"%x}

```

Try it online!

# Answer
> 2 votes
# PowerShell, ~~25~~ 40 bytes

```
param($a,$b)$a|% *g $("D$b"*($b|% *o 0))

```

Try it online!

## Explanation

This calls `.ToString()` on the number with a generated format string, but multiplies it by -1, 0, or 1 based on whether `$b` (`y`) is negative, 0, or positive respectively; this is to handle negative `y` values which format strings don't by themselves.

This seems to require wrapping negative numbers in a substatement `()` for it to work which is just a quirk of the invocation when using literals; if passed variables of type integer, it would not need that.

# Answer
> 2 votes
# C# 6.0, 35 bytes

```
(x,y)=>(x.ToString($"D{y<0?0:y}"));

```

### Alternative solution (51 bytes)

```
(x,y)=>(x.ToString(string.Format("D{0}",y<0?0:y)));

```

# Answer
> 2 votes
# Clean, ~~90~~ ~~86~~ 83 bytes

```
import StdEnv
@x y=if(y<0)"-"""+++{if(c>'-')c'0'\\c<-rjustify x[k\\k<-:toString y]}

```

Try it online!

# Answer
> 1 votes
# Perl 5, 22 + 1 (-`n`) = 23 bytes

```
printf"%0*d",<>+/-/,$_

```

Try it online

# Answer
> 1 votes
# Stacked, 30 bytes

```
[@x'@:'!'\d+'['0'x pad]1/repl]

```

Try it online!

Highlighted:

## Explanation

```
[@x'@:'!'\d+'['0'x pad]1/repl]
[                            ]   anonymous function, take two args: (y x)
 @x                              name pad length argument
   '@:'!                         convert to string*
        '\d+'[        ]1/repl    replace all runs of digits with...
              '0'x pad              ...the digits padded to x '0's

```

## Stringification

Usually, one would use `tostr` to convert something to a string; however, due to the way string formatting works...

```
'@:'!
    !   format the string
'@:'    apply the `:` function t the top of the stack
        this creates a sub-stack, and : duplicates.
        the formatting obtains the top value, which is just the original TOS,
        and casts it to a string

```

The reason we use `'@:'!` instead of `tostr` is to avoid the space between `@x` and `tostr`.

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

```
f(x,y){printf("%s%0*i","-"+(x>=0),y,abs(x));}

```

Try it online!

## Explanation

`printf` formats three arguments:

```
%s      ->    "-"+(x>=0)
%0*i    ->    y
        ->    abs(x)

```

`%s` formats the string `"-"+(x>=0)`. `"-"` is really just an address, something like `41961441`. In memory, this looks something like this:

```
MEMORY ADDRESS | 41961441  41961442 ...
VALUE          | 45 ('-')  0 (0x00) ...

```

When formatted into a string, C takes the address (say 41961441) and keeps on acquiring characters until a null byte (0x00) is met. When x is less than zero, the value `"-"+(x>=0)` has that of the original address (41961441). Otherwise, `x>=0` is 1, so the expression becomes `"-"+1`, which points the null byte after `"-"`, which prints nothing.

`%0*i` prints an integer padded with a specified number of `0`s. `y` denotes this number. We pad `abs(x)` to avoid the negative in some arguments.

# Answer
> 1 votes
## Perl, 25 + `-n` flag = 26 bytes

```
printf"%0*d",<>+($_<0),$_

```

Try it online!

# Answer
> 1 votes
# Perl 6,  ~~39 31~~  30 bytes

```
->\a,\b{'-'x(0>a)~a.abs.fmt("\%0{b}d")}

```

Test it

```
->\a,\b{a.fmt("\%0{b+(0>a)}d")}

```

Test it

```
{$^a.fmt: '%0'~$^b+(0>$a)~'d'}

```

Test it

## Expanded:

```
{  # bare block lambda with placeholder parameters ｢$a｣ and ｢$b｣

  $^a         # declare and use first parameter
  .fmt:       # format it

  '%0'        # '%05d'
  ~
    $^b       # make it ｢$b｣ digits wide
    + (0>$a)  # add 1 if ｢$a｣ is negative
  ~
 'd'
}

```

# Answer
> 1 votes
# **PHP, 49 bytes**

```
echo str_pad($argv[1],$argv[2],'0',STR_PAD_LEFT);

```

# Answer
> 1 votes
# Husk, 18 bytes

Likely not the right approach, this is ~~feels~~ really long for Husk, but there wasn't one already.

```
F+Ṁ+R'0-Ld⁰¹↕='-s⁰

```

Try it online!

# Answer
> 1 votes
# Pip, 13 bytes

```
aR+XD0Xb-#_._

```

Takes the number and minimum number of digits as command-line arguments. Try it online!

### Explanation

```
               a, b are cmdline args; XD is regex `\d` (implicit)
aR             In the number a, replace
  +XD           a run of digits (regex `\d+`)
                with this callback function:
     0X          0 string-multiplied by
       b-#_      minimum digit count minus length of match
           ._    to which concatenate the match itself
               Autoprint the result of the replacement

```

Since string-multiplication gives an empty string when the right operand is negative, this works correctly for all test cases.

# Answer
> 1 votes
# Jelly, 20 bytes

```
0;$L<⁹$$¿
ṣ”-Ç€0¦j”-

```

Try it online!

Take first input `x` as a string.

Apparently there is no existing Jelly answer...

`L<¥` doesn't seem to work.

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), ~~95~~ 89 bytes

```
	DEFINE('F(X,B)')
F	L =GT(B) B
	N =LT(X) 1
	F =DUPL('-',N) LPAD(-1 ^ N * X,L,0)	:(RETURN)

```

Try it online!

defining a function is equivalent to a full program in bytes, so I figured I'd do this instead.

# Answer
> 1 votes
# Thunno 2 `j`, 9 bytes

```
AṘṛ$ʂṄ'-×

```

Try it online!

#### Explanation

```
AṘṛ$ʂṄ'-×  '# Implicit input
AṘ          # Take the absolute value and convert to string
  ṛ         # Pad with zeros to length of second input
   $ʂṄ      # Check if the first input was negative
      '-×  '# If it was, push a "-"
            # Implicit output of joined stack

```

# Answer
> 1 votes
# Vyxal, 70 bitsv2, 8.75 bytes

```
ȧS∆Z¹±SṪp

```

Try it Online!

Bitstring:

```
1001110000000100000100010000100111100010101011011000110001011000011111

```

Idk why Vyxal 2 doesnt have an "is negative?" element but i found a way around that

# Answer
> 0 votes
# Tcl, 46 bytes

```
proc Z n\ p {format %0[expr $n<0?$p+1:$p]d $n}

```

Try it online!

# Answer
> 0 votes
## Swift, 37 bytes (65 inside a function):

```
String(format:"%0\(y+(x<0 ?1:0))d",x)

```

Inside a function:

```
func c(x:Int,y:Int){print(String(format:"%0\(y+(x<0 ?1:0))d",x))}

```

# Answer
> 0 votes
# Java, 218 bytes

```
 import org.apache.commons.lang3.StringUtils;interface B{static void main(String z[]){int x=Integer.parseInt(z[1]);if(x>z[0].length()){System.out.printf(StringUtils.leftPad(z[0],x,"0"));}else{System.out.printf(z[0]);}}}

```

Ungolfed:

```
import org.apache.commons.lang3.StringUtils;

interface B {
   static void main(String z[]) {
      int x = Integer.parseInt(z[1]);
      if (x > z[0].length()) {
        System.out.printf(StringUtils.leftPad(z[0], x, "0"));
      } else {
        System.out.printf(z[0]);
      }
  }
}

```

# Answer
> 0 votes
# Sinclair ZX81/Timex TS1000/1500 BASIC, ~163 tokenized BASIC bytes

```
 1 DIM A(SGN PI,VAL "2")
 2 LET A(SGN PI,SGN PI)=NOT PI
 3 LET A(SGN PI,VAL "2")=INT PI
 4 IF A(SGN PI,SGN PI)<NOT PI THEN PRINT "-";
 5 IF A(SGN PI,VAL "2")=SGN PI THEN GOTO INT PI*PI
 6 FOR I=VAL "2" TO A(SGN PI,VAL "2")
 7 PRINT NOT PI;
 8 NEXT I
 9 PRINT ABS A(SGN PI,SGN PI)

```

Explanations: ZX81 BASIC is quite costly when storing numbers as each number is stored as a 5 byte (I think) floating point number even if you store an integer value like 1. Even line numbers cost 5 bytes per line, then add in the `NEW LINE` character at the end of each line, and the lowest byte count for a BASIC line in Sinclair ZX81 BASIC is 7 (for instance, `1 PRINT`). `SGN PI` is 1, and costs fewer bytes than `1` on this basis, NOT PI is `0` and costs two bytes etc.

* Line `1` sets up a numeric array `1, 2`; arrays are not zero-indexed in this case.
* Line `2` sets `A[1, 1]` to zero.
* Line `3` sets `A[1, 2]` to 3, so the test case is `(1,3)`.
* Line `4` tests to see if the number to be printed is negative; if so, a minus sign is displayed.
* Line `5` checks if the padding is set to 1, if so we don't need to print any leading zeros.
* Line `6` then loops through from 2 to the value of our padding (in this case, 3).
* Line `7` prints the leading zeros.
* Line `8` ends the loop.
* Line `9` prints the positive value of our `A[1,1]`, which in this case is zero.

# Answer
> 0 votes
# Jelly, 18 bytes

```
R¬+Ṛ}AṚṾ€”-x⁴<0¤¤;

```

Try it online!

Takes `y` and `x` (in that order) as integers.

**Explanation**

Example input `5` and `-123`.

```
R¬+Ṛ}AṚṾ€”-x⁴<0¤¤;  Dyadic link
R¬                  Not the range of y. This gives a list of y zeroes. [0,0,0,0,0]
   Ṛ}               Reverse the digits of x. [-3,-2,-1]
  +                 Add these lists. [-3,-2,-1,0,0]
     A              Absolute value. [3,2,1,0,0].
      Ṛ             Reverse. [0,0,1,2,3]
       Ṿ€           Make each digit a string. '00123'
         ”-         The character '-'.
            ⁴<0     x<0? 0 or 1. (1 in this example)
           x        Repeat '-' 0 or 1 times
               ¤¤   Closes ”-x⁴<0 as a nilad
                 ;  Prepend '-' to '00123'

```

The absolute difference atom  would work here over `+` making `A` unnecessary except for the case where `y` is zero or negative where it doesn't work.

# Answer
> 0 votes
# Excel VBA, 33 Bytes

Anonymous VBE immediate window function that takes input as `n` from `[A1]` and `length` from `[B1]` and outputs the appropriately formatted string to the VBE immediate window

```
?Format([A1],[Rept(0,Max(1,B1))])

```

# Answer
> 0 votes
# Gema, 40 characters

```
<y><D>,<N>=$1@subst{\\ =0;@right{$3;$2}}

```

(Not really for Gema. For some weird reason it can only pad with spaces.)

Sample run:

```
bash-5.2$ gema '<y><D>,<N>=$1@subst{\\ =0;@right{$3;$2}}' <<< '-7,3'
-007

```

Try it online! / Try all test cases online!

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