# Question
Title: Converting Strings to Decimals (Gone Wrong)
# What?

*Many programming languages, both practical and esoteric, have functions, methods, etc to convert a given string to a decimal number.* This is how the process might work:

* For each character in the given string.
    + Take the character's ASCII value and subtract it by 48.
    + Multiply the output value by 10. (The output at the first iteration is 0)
    + Add the subtracted ASCII value to the output.

Let us do this process for the string `"109"`:

1. The ASCII value of `1` is 49. Subtract it by 48, and we get 1. We multiply the output by 10, we get 0. Finally, we add 1 to 0 and get one.
2. Next, we subtract `0`'s ASCII value (48) by 48, we get 0. We multiply 1 by 10, we get 10. Nothing happens when we add 0.
3. Then we subtract `9`'s ASCII value (57) by 48, we get 9. We multiply 10 by 10 and get 100. We add 9 to 100 and get 109.

There, we successfully converted `"109"` to 109! It is just as simple!

The problem is that most languages do not like it when the converting string has non-digital characters (characters with an ASCII value not in the range 48-57 inclusive). They would most likely throw some nasty errors or exceptions at us.

*How 'bout we ignore that!*

# Task

Given a printable string from STDIN (you can assume that \\$1 ≤ \text{Input Length} ≤ 10\\$), implement a program or function to badly convert it to an integer according to the above steps, and output or return it back.

Strings can contain whitespace characters (Spaces, tabs and linefeeds).

For another example string `"Hi!"`:

1. The ASCII value of `H` is 72:
`72 - 48 = 24`
`0 * 10 = 0`
`0 + 24 = 24`
2. The ASCII value of `i` is 105:
`105 - 48 = 57`
`24 * 10 = 240`
`240 + 57 = 297.`
3. The ASCII value of `!` is 33:
`33 - 48 = -15`
`297 * 10 = 2970`
`2970 + -15 = 2955`

This means that `"Hi!"` converted to an integer is 2955!

Standard I/O rules apply.

*Note: if your language does not support input, feel free to tell me in your answers (you can put the "input" strings in your source code)!*

# More test cases

```
STDIN                  Output
"123456789"         ->  123456789
"0123456789"        ->  123456789
"-12345"            -> -287655
"Lorem"             ->  350191
"Ipsum"             ->  321451
"AAAAAAAA"          ->  188888887
"        "          -> -177777776
"A"                 ->  17
" "                 -> -16
"
"                   -> -38

```

Standard rules apply!

# Answer
# Shakespeare Programming Language, ~~258~~ 252 bytes

-6 bytes thanks to the default.

```
,.Ajax,.Puck,.Act I:.Scene I:.[Exeunt][Enter Ajax and Puck]
Ajax:Open mind.
Puck:Is I nicer zero?If soYou is the sum ofI twice the difference
     betweenthe product ofyou the sum ofa cat a big big cat the factorial
     ofa big big cat.
     If soLet usAct I.Open heart

```

Try it online!

The golfiest representation of the integer 48 is as `twice the factorial of a big big cat`, i.e. \\$48=2\times (2\times2\times1)!\\$.

This corresponds to

```
Ajax = 0
Puck = 0
Begin Act I
Puck = read_input (as ASCII codepoint value)
if(Puck>0){
    Ajax = Puck + 2 * (Ajax * (4+1) - 4!)
    Go to Act I
}
print(Ajax) (as an integer)

```
> 14 votes

# Answer
# Jelly, 5 bytes

```
O_48Ḍ

```

Try it online!

## How it works

```
O_48Ḍ - Main link. Takes a string s on the left
O     - Convert to ordinal code points
 _48  - Subtract 48 from each
    Ḍ - Convert from base-10

```
> 11 votes

# Answer
# MATL, 8 bytes

As long as we're doing things wrong, why not turn a string into a polynomial?

```
48-[X]ZQ

```

Try it online!

Evaluates the polynomial

$$p\_1x^{n-1} + \cdots + p\_{n-1}x^1 + p\_nx^0$$

where \\$p\\$ is the input string (minus '0') and \\$x\\$ is 10.
> 11 votes

# Answer
# Poetic, 153 bytes

```
decoding a num got WRONG
I/O digits i get?converting fails,o darn
i am bummed if the I/O fails
i have a number i got based on counting it badly,i suppose

```

Try it online!
> 8 votes

# Answer
# JavaScript (ES6/2015), 43 bytes

```
s=>s.map(c=>r=r*10+c.charCodeAt()-48,r=0)|r

```

```
let f = s=>s.map(c=>r=r*10+c.charCodeAt()-48,r=0)|r

console.log(f([..."123456789" ])) //  123456789
console.log(f([..."0123456789"])) //  123456789
console.log(f([..."Lorem"     ])) //  350191
console.log(f([..."Ipsum"     ])) //  321451
console.log(f([..."AAAAAAAA"  ])) //  188888887
console.log(f([..."        "  ])) // -177777776
console.log(f([..."A"         ])) //  17
console.log(f([..." "         ])) // -16
```

Try it online!

**Edit #1:** -1 byte thanks to l4m2

**Edit #2:** -7 bytes thanks to EzioMercer
> 8 votes

# Answer
# , ~~51~~ 48 bytes

*Edit: -3 bytes thanks to Robin Ryder*

```
function(s)(utf8ToInt(s)-48)%*%10^(nchar(s):1-1)

```

Try it online!

Multiplies Utf8 value of each character minus 48 by powers-of-ten from the length of the string minus one, down to zero, and outputs the sum.
> 6 votes

# Answer
# Scala, 18 bytes

```
_./:(0)(_*10+_-48)

```

Try it online!

Explanation:

```
_./:(0)(_*10+_-48)
  /:                Fold left
_                   the input string
    (0)             with an initial value of 0
       (_*10+_-48)  Multiply the accumulator by 10, and add the next character - 48

```
> 6 votes

# Answer
# PowerShell Core, ~~35~~ 26 bytes

```
$args|%{$r=$r*10+$_-48}
$r

```

Saved 9 bytes using splatting

Try it online!
> 6 votes

# Answer
# Python 3, ~~46~~ ~~45~~ 42 bytes

```
f=lambda s:s>[]and ord(s.pop())-48+10*f(s)

```

Try it online!

-1 thanks to Sisyphus

-3 taking a list of characters as input thanks to ovs
> 6 votes

# Answer
# Brachylog, 13 bytes

```
ạ-₄₈ᵐ{×₁₀ʰ+}ˡ

```

Try it online!

For single-"digit" inputs, the output is wrapped in a list, since the fold isn't actually executed. If this isn't acceptable, two 15-byte alternatives exist:

`ạ-₄₈ᵐ,0↻{×₁₀ʰ+}ˡ`

`ạ↔-₄₈ᵐ{i×₁₀ⁱ⁾}ᶠ+`

```
ạ                Convert to codepoints.
 -₄₈ᵐ            Subtract 48 from each.
     {     }ˡ    Left fold:
      ×₁₀ʰ       multiply the accumulator (initialized to first element) by 10
          +      and add it to the next element.

```

Brachylog's base conversion builtin actually disallows values outside the usual range, because it's actually quite useful sometimes on top of preserving proper inverse behavior, so I'm forced to implement the described algorithm directly.
> 6 votes

# Answer
# APL (Dyalog Unicode), 11 bytes

```
10⊥48-⍨⎕UCS

```

Try it online!

`⎕UCS` converts string to a vector of ASCII values, `48-⍨` subtracts 48 from each value and `10⊥` converts from base 10.
> 5 votes

# Answer
# Vyxal, 5 bytes

```
C48-I

```

Try it Online!

Wow it's actually ASCII.
> 5 votes

# Answer
# Haskell, ~~45~~ 43 bytes

```
n#(h:t)=(n*10+fromEnum h-48)#t
n#_=n
f=(0#)

```

Try it online!

```
n#(h:t)=       - # -> infix function taking a number and a string(head:tail)
(n*10+fromEnum h-48)#t
                 - compute first char and call recursively on tail

n#_=n          - end condition

f=(0#)         - apply 0 to #

```
> 5 votes

# Answer
# Java 8, 46 bytes

```
a->{int r=0;for(var c:a)r=r*10+c-48;return r;}

```

Input as a character-array.

Try it online.

**Explanation:**

```
a->{            // Method with character-array parameter and integer return-type
  int r=0;      //  Result-integer, starting at 0
  for(var c:a)  //  Loop over the input-characters:
    r=          //   Change the result to:
      r*10      //    The current result multiplied by 10
      +c-48;    //    And add the codepoint of the current characters minus 48
  return r;}    //  After the loop, return the result

```
> 5 votes

# Answer
# Assembly (NASM, 32-bit, Linux), ~~221~~ ~~185~~ 147 bytes

*Edit: -36 bytes + bugfix*

*Edit: -38 bytes*

```
mov edi,0
push 48
l:imul edi,edi,10
add edi,[esp]
sub edi,48
mov edx,1
mov ecx,esp
mov ebx,0
mov eax,3
int 128
mov ax,[esp]
xor ax,10
jnz l
pop eax

```

Try it Online!

The result is in `edi`.
> 5 votes

# Answer
# Japt, 8 bytes

Takes input as an array of characters.

```
£48nXcÃì

```

Try it (Header splits string input to array)

```
£48nXcÃì     :Implicit input of array
£            :Map each X
 48n         :  Subtract 48 from
    Xc       :  Charcode of X
      Ã      :End map
       ì     :Convert to integer from base-10 digit array

```
> 4 votes

# Answer
# Stax, 7 bytes

```
ëk╜ΓOíU

```

Run and debug it

Explanation:

```
{48-mA|E Unpacked source, implicit input
{   m    Map over code points of input string
 48-       Subtract 48 from each
     A|E Convert from base 10

```
> 4 votes

# Answer
# Perl 5, 40 bytes

```
sub{my$r;map$r=$r.0-48+ord,pop=~/./g;$r}

```

Try it online!
> 4 votes

# Answer
# Befunge-98 (PyFunge), ~~14~~ 12 bytes

Thanks to Gegell for -2 bytes!

```
2j@.~'0-\a*+

```

Try it online!

**Explanation**:

Initially the instruction pointer (IP) is moving right and the stack is filled with `0`'s.
`2j` skips the next two instruction (`@.`).
`~` reads one character of input.
`'0-` subtracts 48 from the input.
`\` swaps the two elements at the top of the stack. Now the intermediate result is on the top.
`a*` multiplies the result by 10.
`+` adds the new number.
After that the IP wraps around to process the next character.

If there is no input left `~` reflects the IP.
`.` prints the result at the top of the stack, and `@` terminates the program.

Animation of the code with input `Lorem`:

I'm not sure why there are black bars on two frames, I blame ImageMagick :/
> 4 votes

# Answer
# JavaScript (Node.js),  ~~39~~  38 bytes

*Saved 1 byte thanks to @Shaggy*

```
s=>Buffer(s).map(c=>p=p*10+c-48,p=0)|p

```

Try it online!
> 4 votes

# Answer
# C (gcc), ~~48~~ 44 bytes

Usually using a temporary variable to store the current character is shorter than doing array processing, but not this time!

```
i;f(char*s){for(i=0;*s;i=i*10+*s++-48);s=i;}

```

Try it online!
> 4 votes

# Answer
# , 12 bytes

```
10#._48+3&u:

```

Try it online!
> 4 votes

# Answer
# Python 3, 53 bytes

```
def f(x):
 o=0
 for i in x:o=o*10+ord(i)-48
 return o

```

Try it online!
> 4 votes

# Answer
# brainfuck, ~~43~~ 38 bytes

```
,[<[>++++++++++<-]>+++>+[<->+++++],]<.

```

Try it online!

Thanks to JosiahRyanW for -5 bytes.

Since by our consensus, output can be given as character code, this is pretty straightforward in brainfuck. Note that the brainfuck interpreter on tio.run has 8-bit wrapping cells, so the maximum value is 255.

```
,[                  while input
  <[>++++++++++<-]  add 10 times previous sum to input
  >+++>+[<->+++++]  add 208 to it (effectively subtracting 48 by 8 bit wrapping)
  ,                 read next character
]
<.                  output

```
> 4 votes

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

```
10/-48+

```

Try it online!
> 4 votes

# Answer
# 05AB1E, 6 bytes

```
Ç48-Tβ

```

Similar as some other answers.

Try it online or verify all test cases.

**Explanation:**

```
Ç       # Convert the (implicit) input-string to a list of codepoint integers
 48-    # Subtract 48 from each value
    Tβ  # Convert this from a base-10 list to a base-10 integer
        # (after which it is output implicitly as result)

```
> 4 votes

# Answer
# Rust, 42 bytes

```
|s|s.chars().fold(0,|n,x|n*10+x as i32-48)

```

Try it online!

Takes input as an &str and outputs the number based on utf-8 codepoints.
> 4 votes

# Answer
# Ruby, 38 bytes

```
->s{s.bytes.inject(0){|a,b|b-48+a*10}}

```

35 bytes with the new Ruby 2.7 syntax:

```
->s{s.bytes.inject(0){_2-48+_1*10}}

```

Try it online!
> 4 votes

# Answer
# \>\<\>, 15 bytes

```
0l1=?na*{68*-+!

```

Try it Online!

Explanation

```
0             !         Accumulator initialisation, skipped on subsequent loops
 l1=?na*                Print-and-terminate condition
      a*                Decimal shift
        {               Next character of input
         68*-+          Subtract 48 and add

```
> 4 votes

# Answer
# Clojure, 41 bytes

```
#(reduce(fn[x y](+(* 10 x)-48(int y)))0%)

```

Try it online!

Or alternatively, for the same byte count with a different order of full and shorthand function notation:

```
(fn[x](reduce #(+(* 10%)-48(int %2))0 x))

```

Try it online!
> 4 votes

# Answer
# GolfScript, ~~13~~ 12 bytes

```
{48-}%10base

```

Try it online!

```
{   }%         # For each byte in the input
 48-           # Subtract 48
      10base   # Convert to base 10

```
> 4 votes

# Answer
# Whitespace, 88 bytes

```
[S S S N
_Push_0][N
S S N
_Create_Label_LOOP][S S S N
_Push_0][S N
S _Duplicate_top][T N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve][S N
S _Duplicate][S S S T   N
_Push_1][T  S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_EXIT][S S S T   T   S S S S N
_Push_48][T S S T   _Subtract][S N
T   _Swap_top_two][S S S T  S T S N
_Push_10][T S S N
_Multiply][T    S S S _Add][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_EXIT][S N
N
_Discard_top][T N
S T _Print_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Since Whitespace inputs one character at a time, the input should contain a trailing ␁ (character with codepoint 1) so it knows when to stop reading characters and the input is done.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer result = 0
Start LOOP:
  Integer input = STDIN as character
  If(input - 1 == 0):
    Jump to Label EXIT
  input = input - 48
  result = result * 10
  result = result + input
  Go to the next iteration of LOOP

Label EXIT:
  Print result as integer to STDOUT

```

**Example run: `input = "Hi!"`**

```
Command     Explanation                Stack           Heap     STDIN  STDOUT  STDERR

SSSN        Push 0                     [0]
NSSN        Create Label LOOP          [0]
 SSSN       Push 0                     [0,0]
 SNS        Duplicate top (0)          [0,0,0]
 TNTS       Read STDIN as character    [0,0]           {0:72}   H
 TTT        Retrieve at address (0)    [0,72]          {0:72}
 SNS        Duplicate top (72)         [0,72,72]       {0:72}
 SSSTN      Push 1                     [0,72,72,1]     {0:72}
 TSST       Subtract top two (72-1)    [0,72,71]       {0:72}
 NTSSN      If 0: Jump to Label EXIT   [0,72]          {0:72}
 SSSTTSSSN  Push 48                    [0,72,48]       {0:72}
 TSST       Subtract top two (72-48)   [0,24]          {0:72}
 SNT        Swap top two               [24,0]          {0:72}
 SSSTSTSN   Push 10                    [24,0,10]       {0:72}
 TSSN       Multiply top two (0*10)    [24,0]          {0:72}
 TSSS       Add top two (24+0)         [24]            {0:72}
 NSNN       Jump to Label LOOP         [24]            {0:72}

 SSSN       Push 0                     [24,0]          {0:72}
 SNS        Duplicate top (0)          [24,0,0]        {0:72}
 TNTS       Read STDIN as character    [24,0]          {0:105}  i
 TTT        Retrieve at address (0)    [24,105]        {0:105}
 SNS        Duplicate top (105)        [24,105,105]    {0:105}
 SSSTN      Push 1                     [24,105,105,1]  {0:105}
 TSST       Subtract top two (105-1)   [24,105,104]    {0:105}
 NTSSN      If 0: Jump to Label EXIT   [24,105]        {0:105}
 SSSTTSSSN  Push 48                    [24,105,48]     {0:105}
 TSST       Subtract top two (106-48)  [24,57]         {0:105}
 SNT        Swap top two               [57,24]         {0:105}
 SSSTSTSN   Push 10                    [57,24,10]      {0:105}
 TSSN       Multiply top two (24*10)   [57,240]        {0:105}
 TSSS       Add top two (57+240)       [297]           {0:105}
 NSNN       Jump to Label LOOP         [297]           {0:105}

 SSSN       Push 0                     [297,0]         {0:105}
 SNS        Duplicate top (0)          [297,0,0]       {0:105}
 TNTS       Read STDIN as character    [297,0]         {0:33}   !
 TTT        Retrieve at address (0)    [297,33]        {0:33}
 SNS        Duplicate top (33)         [297,33,33]     {0:33}
 SSSTN      Push 1                     [297,33,33,1]   {0:33}
 TSST       Subtract top two (33-1)    [297,33,32]     {0:33}
 NTSSN      If 0: Jump to Label EXIT   [297,33]        {0:33}
 SSSTTSSSN  Push 48                    [297,33,48]     {0:33}
 TSST       Subtract top two (33-48)   [297,-15]       {0:33}
 SNT        Swap top two               [-15,297]       {0:33}
 SSSTSTSN   Push 10                    [-15,297,10]    {0:33}
 TSSN       Multiply top two (297*10)  [-15,2970]      {0:33}
 TSSS       Add top two (57+240)       [2955]          {0:33}
 NSNN       Jump to Label LOOP         [2955]          {0:33}

 SSSN       Push 0                     [2955,0]        {0:33}
 SNS        Duplicate top (0)          [2955,0,0]      {0:33}
 TNTS       Read STDIN as character    [2955,0]        {0:1}    ␁
 TTT        Retrieve at address (297)  [2955,1]        {0:1}
 SNS        Duplicate top (1)          [2955,1,1]      {0:1}
 SSSTN      Push 1                     [2955,1,1,1]    {0:1}
 TSST       Subtract top two (1-1)     [2955,1,0]      {0:1}
 NTSSN      If 0: Jump to Label EXIT   [2955,1]        {0:1}
NSSSN       Create Label EXIT          [2955,1]        {0:1}
 SNN        Discard top                [2955]          {0:1}
 TNST       Print as integer           []              {0:1}           2955
                                                                               error

```

The program stops with an error: no exit defined.
> 4 votes

# Answer
# Husk, ~~9~~ 7 bytes

*Edit: -2 bytes thanks to Razetime*

```
dmo-48c

```

Try it online!

**How?**

```
d           # interpret digits as base-10 number:
 m          # map function over each element of list (each character of string)
  o         # combine 2 functions into one
      c     # convert character to Utf8 value
   -48      # subtract 48

```
> 3 votes

# Answer
# mlochbaum/BQN, 21 bytes

```
10{+⟜(⊸×)´⌽}'0'-˜¨

```

Try it!

The online BQN REPL does not have a method of taking input( in APL), so append the string to the end of the program.
> 3 votes

# Answer
# Charcoal, 10 bytes

```
Ｉ↨ＥＳ⁻℅ι⁴⁸χ

```

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

```
   Ｓ        Input string
  Ｅ         Map over characters
      ι     Current character
     ℅      Ordinal
       ⁴⁸   Literal 48
    ⁻       Subtract
         χ  Literal 10
 ↨          Base conversion
Ｉ           Cast to string
            Implicitly print

```
> 3 votes

# Answer
# Keg, `-hr`, 15 bytes

```
0&?⑷86*-⑸(
⑾⑼)⑻

```

Try it online!

Keg is very special. Like *very* special.
> 3 votes

# Answer
# Gol\>\<\>, 10 bytes

```
iEh$a*+`0-

```

Try it online!

```
i           Read one char from the input
 Eh         If last char read was EOF halt and output current sum as number
   $a*      Else swap new input and current sum, then multiply sum by 10
      +     Add the new char value to current sum
       `0-  Subtract 48 (value of '0') and wrap around implicitly to loop

```
> 3 votes

# Answer
# Elixir, 36 bytes

```
&List.foldl&1,0,fn x,y->y*10+x-48end

```

Try it online!

Anonymous function that performs a simple left fold over its argument (`&1`) using the specified accumulating function. Relies on the fact that Elixir charlists are the same thing as the lists of integer codepoints, so that the transformation can be applied directly without any conversions.
> 3 votes

# Answer
# SNOBOL4 (CSNOBOL4), 84 bytes

```
	I =INPUT
N	I LEN(1) . C REM . I	:F(O)
	O =O * 10 + ORD(C) - 48	:(N)
O	OUTPUT =O
END

```

Try it online!
> 3 votes

# Answer
# Rust macro, 121 bytes

```
macro_rules!f{($a:expr;)=>{$a};($a:expr;$c:tt$(,$r:tt)*)=>{f!($a*10+$c as i64-48;$($r),*)};($($c:tt)*)=>{f!(0;$($c),*)};}

```

Try it online!

This is a macro that takes a sequence of characters and returns an expression like `((0 * 10 + '1' as i64 - 48) * 10 + '0' as i64 - 48) * 10 + '9' as i64 - 48`. The expression `$a` is used as an accumulator: The macro expands to `$a` if all characters are consumed.
> 3 votes

# Answer
# Lua, 55 bytes

```
i=0(...):gsub('.',load'i=i*10+(...):byte()-48')print(i)

```

Try it online!

Fairly simple: executes given algorithm for every character in given string, then prints the result. TIO includes test suite.

Note: input is taken as an argument. This doesn't conform to question as currently written, but is an input method allowed by default I/O rules.
> 2 votes

# Answer
# Haskell, 23 bytes

```
foldl(\a x->10*a+x-48)0

```

Try it online!

A simple fold.
> 2 votes

# Answer
# jq, 35 bytes

```
explode|reduce.[]as$x(0;.*10+$x-48)

```

Try it online!

This is pretty much a direct translation of the rules to `jq` syntax...

```
explode

```

Splits the input string into a list of codepoints.

```
reduce.[]as$x(0;.*10+$x-48)

```

Initializes the accumulator variable `$x` to 0, the for each codepoint computes 10 times the current accumulator value and adds the current codepoint value less 48. The result is a single number with is displayed to STDOUT by default.
> 2 votes

# Answer
# Alice, ~~75~~ 48 bytes

```
wi.hn$}'0-!]K@ O Q \{
      {;e(w]?. h n ${~a*+K

```

Try it online!

```
w .hn$      K                While there is characters left in the input
 i    '0-!]                  Read one char - 48 and put it on the tape
      }                      Otherwise go south
      {;e(                   Go east and rewind the tape
          w]?. h n $     K   While there is more to read on the tape
                     ~a*+    Multiply the current stack value by 10 and sum the tape value
                    {        Then go north
                   \{        Go west, switch to ordinal mode
             @ O Q           Convert the stack to string, print it, bye

```
> 2 votes

# Answer
# Factor \+ `project-euler.common`, 31 bytes

Thanks to @chunes for pointing out that there actually *is* a function to convert a list of digits to a number, it's just hidden under an extension of the standard library.

```
[ >array 48 v-n digits>number ]

```
* `[ … ]` Quotation (anonymous function) taking a string on the stack
* `>array` Convert string to list of code points
* `48 v-n` Subtract 48 from each
* `digits>number` Convert list of numbers to base-10 number

The `>array` is necessary because if you subtract a number greater than a character's codepoint from a character, it goes around to some really big number instead of being negative.

---

Without using extra vocabularies, the program is only 2 bytes longer:

# Factor, 33 bytes

```
[ 0 [ 48 - swap 10 * + ] reduce ]

```

Try it online!

~~I feel like there’s probably a built in to convert a list of digits to a number, but if it exists I can’t find it.~~ @chunes pointed out that such a function exists under an extension of the standard library, thus the above solution. I decided to keep this one since it's almost as short with a different approach and doesn't use any extra vocabularies.

### Explanation

| Code | Explanation | Stack |
| --- | --- | --- |
| `[ … ]` | Quotation (anonymous function) taking a string (equivalent to list of code points) | `"-12345"` |
| `0 [ … ] reduce` | Reduce body, taking previous then current, with 0 as initial | `0 "-"` |
| `48 -` | Subtract 48 from char | `0 -3` |
| `swap` | Swap so accumulator is on top of the stack | `-3 0` |
| `10 *` | Multiply by 10 | `-3 0` |
| `+` | Add | `-3` |
| This repeats until string ends | -3 → -29 → -288 → -2877 → … | `-287655` |
> 2 votes

# Answer
# MMIX, 36 bytes (9 instrs)

```
00000000: e3010000 83ff0000 e7000001 42ff0005  ẉ¢¡¡³”¡¡ḃ¡¡¢B”¡¦
00000010: 2a010101 280101ff 21010130 f1fffffa  *¢¢¢(¢¢”!¢¢0ȯ””«
00000020: f8020000                             ẏ£¡¡

```

Disassembly:

```
atoi    SET   $1,0          // n = 0
0H      LDBU  $255,$0
        INCL  $0,1          // loop: v = *a++
        BZ    $255,0F       // if(!v) goto end
        4ADDU $1,$1,$1      // n = (n << 2) + n
        2ADDU $1,$1,$255    // n = (n << 1) + v
        SUBU  $1,$1,'0'     // n -= '0'
        JMP   0B            // goto loop
0H      POP   2,0           // end: return n

```

Note the one trick I used: `4ADDU x,x,x; 2ADDU x,x,y` takes no more space than the obvious `MULU x,x,10; ADDU x,x,y` and executes faster (multiplication is much more expensive than addition or shifting).
> 1 votes

# Answer
# BQN, 14 bytes

```
10⊸×⊸+˜´'0'-˜⌽

```

Anonymous tacit function that takes a string and returns a number. Try it at BQN online!

### Explanation

```
10⊸×⊸+˜´'0'-˜⌽
              ⌽  Reverse the argument
         '0'-˜    Subtract character 0 from each character
        ´         Right fold on this function:
       ˜           Apply this function with arguments swapped:
     ⊸+            Add the right argument to
10⊸×               10 times the left argument

```

For example, with an argument of `"109"`, `'0'-˜⌽` gives `⟨9,0,1⟩`. Then the fold proceeds as follows:

```
0 (10⊸×⊸+)˜ 1  →  1 (10⊸×⊸+) 0  →  10 + 0  →  10
9 (10⊸×⊸+)˜ 10  →  10 (10⊸×⊸+) 9  →  100 + 9  →  109

```
> 1 votes

# Answer
# Julia

## 36 bytes

an `evalpoly` version:

```
!s=evalpoly(10,[reverse(s)...].-'0')
```

Attempt This Online!

and a `fold` based:

## 35 bytes

```
!s=foldl((x,c)->c-'0'+10x,s,init=0)
```

Attempt This Online!

and here are two more variants:

## 36 bytes

`foreach`:

```
!s=(x=0;foreach(c->x=c-'0'+10x,s);x)

```

## 34 bytes

```
!s=(x=0;[s...].|>c->x=c-'0'+10x;x)

```
> 1 votes

# Answer
# Thunno, \\$ 6 \log\_{256}(96) \approx \\$ 4.94 bytes

```
O48-ZD

```

Attempt This Online! or verify all test cases.

Port of caird coinheringaahing's Jelly answer.

#### Explanation

```
O48-ZD  # Implicit input
O       # Ordinals of input
 48-    # -48 to each
    ZD  # Convert to base-10
        # (from a list of digits)
        # Implicit output

```
> 1 votes

# Answer
# Opcode (x64, Linux), 17 bytes

```
f:	xor eax, eax
f0:	imul rdx, rax, 10
	xor eax, eax
	lodsb
	lea rax, [rax+rdx-48]
	loop f0
	ret

```

Try it online!
> 1 votes

# Answer
# Nibbles, 4 bytes

```
`@~+-48

```

Attempt This Online!

```
`@~ Convert from base 10
+    add [vectorized]
-48   -48
      input

```
> 1 votes

# Answer
# Pip, 14 bytes

```
FiaYy*t+Ai-48y

```

How?

```
FiaYy*t+Ai-48y  : One arg; String
Fia             : For each character in a
        Ai        : ASCII value for char
          -48     : Subtract 48
    y             : Previous result
     *t           : Multiply by ten
       +          : Add together
   Y              : Yank
             y  : Return result

```

Try It Online!
> 0 votes

# Answer
# C++ (gcc), 48 bytes

```
int f(char*s,int r=0){r=*s?f(s+1,r*10+*s-48):r;}

```

Try it online!

**Edit #1:** -4 bytes by removing `return`
> 0 votes

# Answer
# C#, 34 bytes

```
x=>x.Aggregate(0,(y,z)=>10*y+z-48)

```

Try it online!
> 0 votes

# Answer
# Thunno 2 `B`, 5 bytes

```
48-Tḋ

```

Attempt This Online!

#### Explanation

```
48-Tḋ  # Implicit input
       # Cast to codepoints
48-    # Subtract 48 from each
    ḋ  # Convert from a list
   T   # of digits in base ten
       # Implicit output

```
> 0 votes

---
Tags: code-golf, string, integer, conversion
---


# Question
Title: Minimum partition with non-empty intersections
Given a set of intervals \\$\mathcal{I} = \\{I\_1, \ldots, I\_m\\}\\$, where each interval \\$I\_j\\$ is represented by its bounds \\$(a\_j, b\_j)\\$, find a partition \\$\mathcal{T}\\$ of \\$\mathcal{I}\\$ of minimal cardinality such that for each set \\$T\_i \in \mathcal{T}\\$ it holds \\$\bigcap T\_i \ne \emptyset\\$. In other words, find a partition of minimal cardinality where all the intervals inserted in the same set have a common element.

Elements \\$\\{a\_j, b\_j\\}\\$ can be integers, floats, chars, strings, or any other data type that has a **total** order and at least \\$16\\$ elements * (boolean is not admissible). Your solution must support at least one such data type of your choice.

<sub>\*: why \\$16\\$ and not any other number? It's an arbitrary limit, I want to give freedom to use any strange data type, but I do not want loopholish solutions. </sub>

You can either output:

1. partition \\$\mathcal{T} = \\{T\_1, \ldots, T\_k\\}\\$, or alternatively
2. a set of numbers \\$S = \\{s\_1, \ldots, s\_k \\}\\$ such that \\$s\_i \in \bigcap T\_i\\$ for each \\$i\\$.

### Testcases

```
input                        output (format 1)                  output (format 2)
{}:                          [],                                [],
{(0, 1)}:                    [{(0, 1)}],                        [0],
{(0, 1), (2, 3)}:            [{(0, 1)}, {(2, 3)}],              [0, 2],
{(1, 2), (0, 3)}:            [{(1, 2), (0, 3)}],                [1],
{(0, 2), (1, 3)}:            [{(0, 2), (1, 3)}],                [1],
{(1, 2), (3, 4), (0, 5)}:    [{(1, 2), (0, 5)}, {(3, 4)}],      [1, 3],
{(0, 1), (4, 5), (2, 3)}:    [{(0, 1)}, {(2, 3)}, {(4, 5)}],    [0, 2, 4],
{(4, 5), (1, 2), (0, 3)}:    [{(1, 2), (0, 3)}, {(4, 5)}],      [1, 4],
{(0, 1), (2, 5), (3, 4)}:    [{(0, 1)}, {(2, 5), (3, 4)}],      [0, 3],
{(0, 2), (3, 5), (1, 4)}:    [{(0, 2), (1, 4)}, {(3, 5)}],      [1, 3],

```

### Rules

* you can use any reasonable I/O format, for example:
    + the input can be a list/set of tuples, or two lists;
    + in case 1., the output can be a list/set of lists/sets of intervals; each interval can be represented as a tuple, or the index of its position in the input;
    + in case 2., the output can be a list/set of numbers;
* you can take the cardinality \\$m\\$ of the input set as an additional input;
* the input set \\$\mathcal{I}\\$ may be empty (in this case you have to output an empty list/set);
* you can assume each interval is not empty nor degenerate, i.e. \\$a\_j \< b\_j\\$;
* you can assume intervals are left-closed or left-open, and if they are right-closed or right-open, as long as it's consistent for all intervals;
* you cannot assume the intervals in the input are sorted according to any particular criteria.

This is codegolf, so the shortest code wins. Bonus \\$-i\\$ bytes if your solution works in less than exponential time.

---

#### Tips

* I think using closed intervals is the easiest way. I would have put it as a rule, but I prefer to leave freedom.
* > by lexicographically sorting the intervals, a minimal solution can be computed using a greedy algorithm.

# Answer
# 05AB1E, 11 bytes

```
˜æ.ΔI€Ÿ¢€àP

```

Try it online! or try all test cases.

Finds the smallest subset of the ranges' bounds such that each of the ranges contains one of the values in set.

## Explanation

```
˜      flatten the input ranges, to get a list of all bounds
æ      push all subsets, sorted by size
.Δ     find the first (and smallest) one such that:
 I      push the input again
 €      map each interval in the input
  Ÿ      to the list of integers it contains
 ¢      count how many times each of these values appear in the subset. Because the minimum subset doesn't contain duplicates, each of these is 0 or 1.
 €à     for each of the intervals, find the maximum
 P      and take the product, check if all of them are 1

```
> 5 votes

# Answer
# Python 3.8 (pre-release), 59 bytes

```
f=lambda a:a and(z:=max(a)[0],*f([p for p in a if p[1]<z]))

```

Try it online!

Takes a sequence of pairs representing left-closed, right-open intervals and returns a tuple of points.

Same algorithm as earlier but upside down.

### Retired Python, 62 bytes (-4 thanks @Jonathan Allan)

```
f=lambda*a:a and(z:=min(map(max,a)),*f(*filter([z].__le__,a)))

```

Attempt This Online!

### Retired Python, 66 bytes

```
f=lambda*a:a and(z:=min(y for x,y in a),*f(*filter([z].__le__,a)))

```

Attempt This Online!

Takes a splatted sequence of lists representing left-open, right-closed intervals and returns a tuple of points.

Time-complexity is quadratic I believe.

### How?

At each iteration finds the smallest right boundary. This point is used to define the next cluster. All intervals with smaller left boundary contain the point and are filtered out before the next iteration.
> 4 votes

# Answer
# Jelly, 12 bytes (\\$-i\\$)

```
>Ạ¥ƇṀ€Ṃ$$ƬḟƝ

```

A monadic Link that accepts the intervals as a list of pairs and yields a minimal cardinality partition with self-intersecting parts as a list of lists of pairs.

**Try it online!** Or see the test-suite.

### How?

```
>Ạ¥ƇṀ€Ṃ$$ƬḟƝ - Link: Intervals
         Ƭ   - collect up while distinct, applying:
        $    -   last two links as a monad - f(CurrentIntervals):
       $     -     last two links as a monad - f(CurrentIntervals):
    Ṁ€       -       maximum of each
      Ṃ      -       minimum -> "M"
   Ƈ         -     keep those (I in CurrentIntervals) for which:
  ¥          -       last two links as a dyad - f(I, M):
>            -         {I} greater than {M}? (vectorises)
 Ạ           -         all?
           Ɲ - for neighbouring pairs - f(L, R):
          ḟ  -   {L} filter discard {R}

```
> 2 votes

# Answer
# Charcoal, 16 bytes

```
Ｗ⌊⌈θ«≔Φθ‹⌈κιθ⟦Ｉι

```

Try it online! Link is to verbose version of code. Explanation: Port of @Albert.Lang's upside-down answer.

```
Ｗ⌊⌈θ«

```

While intervals remain, find the beginning of the rightmost interval. (This depends on underhanded behaviour of the version of Charcoal on TIO which returns `None` if it can't work out whether  is supposed to be `Minimum` or `Floor`.)

```
≔Φθ‹⌈κιθ

```

Remove the intervals that contain that point.

```
⟦Ｉι

```

Output the point.
> 2 votes

# Answer
# Nekomata, 11 bytes

```
Oᵖᵐ{Ťđṁ<}aş

```

Attempt This Online!

```
Oᵖᵐ{Ťđṁ<}aş
O               Find a set partition of the input
 ᵖ              such that
  ᵐ{    }       for each subset in the partition
    Ťđ          transpose to get a list of heads and a list of tails
      ṁ<        check that all heads are less than the smallest tail
         aş     Find the shortest such partition

```

By default, Nekomata outputs all possible solutions. If you want only one solution, you can add the `-1` flag.
> 2 votes

# Answer
# Pyth, 12 bytes

```
hlDm{.nd*FrM

```

Try it online!

Uses half inclusive range. Looks at all lists where one element is from each range, deduplicates this and then finds the shortest.

### Explanation

```
hlDm{.nd*FrMQ    # implicitly add Q
                 # implicitly assign Q = eval(input())
          rMQ    # map elements of Q to their ranges
        *F       # fold over cartesian product
   m             # map over lambda d
     .nd         #   flatten d to an unnested list
    {            #   deduplicate
 lD              # sort by length
h                # take the first element

```
> 0 votes

---
Tags: code-golf, set-partitions
---


title: Print the missing characters

text:
# Question
Title: Print the missing characters
Simple challenge inspired by the popularity of my previous print invisible text and print real invisible text challenges, and the same length different string challenge.

Given a string consisting of only printable characters (`0x20 to 0x7E`), print every printable character not present in the string.

## Input

A string, or array of characters, consisting of only printable ASCII characters

## Output

Every printable ASCII character not present in the input string, in any order.

## Testcases

```
Input:  "Hello, World!"
Output: ""#$%&'()*+-./0123456789:;<=>?@ABCDEFGIJKLMNOPQRSTUVXYZ[\]^_`abcfghijkmnpqstuvwxyz{|}~"
========
Input:  "Hi!"
Output: " "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghjklmnopqrstuvwxyz{|}~"
========
Input:  ""
Output: " !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
========
Input:  " !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
Output: ""

```

## Scoring

This is code-golf so fewest bytes **in each language** wins

# Answer
# GS2, 2 bytes

```
ç7

```

Try it online!

### How it works

```
    (implicit) Push the sting of all characters in STDIN on the stack.
ç   Push the string of all printable ASCII characters.
 7  Perform symmetric set difference.
    (implicit) Print the result to STDOUT.

```
> 13 votes

# Answer
# Python 3.5, 39 bytes

```
lambda n:{*map(chr,range(32,127))}-{*n}

```

Try it online!
Turns input into a set, and remove it from the set containing all ascii characters
> 7 votes

# Answer
# Perl 6, 29 bytes

```
{[~] keys (' '..'~')∖.comb}

```

Note that the result is random because Sets are unordered.

Test it

## Expanded:

```
{
  [~]        # reduce using string concatenation
             # (shorter than ｢join '',｣)

  keys       # get the keys from the Set object resulting from the following

  (' '..'~') # Range of printable characters
  ∖          # Set minus (this is not \ )
  .comb      # split the input into individual characters
}

```

There is also an ASCII version of  `(-)`, but it would require a space before it so that it isn't parsed as a subroutine call.
> 6 votes

# Answer
# Japt, 14 bytes

```
Ho#_dÃf@bX ¥J

```

Try it online!

Saved 4 bytes thanks to Shaggy and obarakon
> 5 votes

# Answer
## Haskell, 32 bytes

```
f x=[y|y<-[' '..'~'],all(/=y)x]

```

Try it online!

Boring library function for set difference:

### Haskell, 31 bytes

```
import Data.List
([' '..'~']\\)

```
> 4 votes

# Answer
# MATL, 5 bytes

```
6Y2X~

```

Try it online!

Thanks to Luis Mendo for golfing 8 bytes off!

Explanation:

```
   X~   % The symmetric set difference
6Y2     % Between all printable ASCII
        % And the input string (implicit)
        % Implicitly display

```

*Symmetric set difference* will give every element that is present in exactly one of the two input sets. (but not both) This will always give the right answer, since the input set will always be a subset of the second set (all printable ASCII).

Original version:

```
32:126tGom~)c

```

Explanation:

```
32:126          % Push the range 32-126
      t         % Duplicate it on the stack
       G        % Push the input
        o       % Convert it to character points
         m      % Is member (0 for each char that isn't in input, 1 for each char that is)
          ~     % Logical NOT
           )    % Take the truthy elements of this array from the previous array (All Printable ASCII)
            c   % Display as a string

```
> 4 votes

# Answer
# Brachylog, 5 bytes

```
ẹ;Ṭ↔x

```

Try it online!

### Explanation

```
ẹ          Split the input string into a list of chars
 ;Ṭ↔x      Exterminate the chars from the string Ṭ of printable ASCII chars

```
> 3 votes

# Answer
# Octave, ~~22~~ 20 bytes

Thanks to @Luis Mendo saved 2 bytes.

```
@(s)setxor(32:'~',s)

```

Try it online!

Other answer:

```
@(s)setdiff(' ':'~',s)

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 74 bytes

I'm sure there's a shorter way to do this!

```
s=>[...Array(95)].map((_,y)=>s.includes(c=String.fromCharCode(y+32))?"":c)

```

---

## Try it

```
let f=
s=>[...Array(95)].map((_,y)=>s.includes(c=String.fromCharCode(y+32))?"":c)
oninput=_=>o.innerText=f(i.value).join``
o.innerText=f(i.value="Hello, World!").join``
```

```
<input id=i><pre id=o>
```
> 3 votes

# Answer
## Perl, 39 bytes

```
s!.*!"pack(c95,32..126)=~y/$_//dr"!ee

```

Run with `perl -pe`.
> 3 votes

# Answer
# Bash, ~~47 43~~ 40 bytes

```
printf %x {32..126}|xxd -r -p|tr -d "$1"

```

Try it online!

Generates hexa range, inverts hex dump to char an removes characters present in first parameter.
> 3 votes

# Answer
# APL, 13 bytes

```
⍞~⍨⎕UCS31+⍳95

```

Straightforward:

```
       31+⍳95  ⍝ A vector 32 .. 126
   ⎕UCS        ⍝ as characters
 ~⍨            ⍝ without
⍞              ⍝ those read from character input.

```
> 3 votes

# Answer
# 05AB1E, 4 bytes

```
žQsм

```

Try it online!

```
žQsм  # full program
   м  # remove...
  s   # implicit input...
   м  # from...
žQ    # all ASCII characters
      # implicit output

```
> 3 votes

# Answer
# PHP, 42 Bytes

Input as array

Output as string

```
<?=join(array_diff(range(" ","~"),$_GET));

```

Try it online!

# PHP, 53 Bytes

Input as string

Output as string

```
<?=join(array_diff(range(" ","~"),str_split($argn)));

```

replace `<?=join` with `print_r` for an output as array

Try it online!
> 2 votes

# Answer
# Jelly, 8 bytes

*Really, 8 bytes? Please, tell me I missed something!*

```
32r126Ọḟ

```

**Try it online!**

### How?

```
32r126Ọḟ - Main link: list of characters s
32r126   - inclusive range from 32 to 126 = [32,33,...,125,126]
      Ọ  - cast ordinals to characters = list of printable characters
       ḟ - filter discard if in s

```

---

Alternatively

```
“ ~‘r/Ọḟ - Main link
“ ~‘     - code-page indexes = [32,126]
    r/   - reduce by inclusive range = [32,33,...,125,126]
      Ọ  - cast from ordinals to characters = list of printable characters
       ḟ - filter discard if in s

```

---

Since this challenge a new atom which yields all printable ASCII characters, `ØṖ`, has been introduced making the following work for 3 bytes:

```
ØṖḟ

```
> 2 votes

# Answer
# CJam, 8 bytes

```
'␡,32>q^

```

Where  is a literal delete character.

Try it online!

```
'␡,       e# The range of all characters up to ~.
   32>    e# Slice it to be the range of all characters from space to ~.
      q^  e# Symmetric set difference with the input.

```
> 2 votes

# Answer
# Ruby, 23 18 17 bytes

```
->s{[*' '..?~]-s}

```

Uses a lambda function as per @sethrin's comments.

Previous versions:

```
[*' '..?~]-s.chars

(' '..'~').to_a-s.chars

```
> 2 votes

# Answer
# brainfuck, 120 bytes

```
+[+[>+<+<]>]>-[[>>]+[<<]>>-],[<+++++[>------<-]>-[>[>>]+[<<]>-]>[>>]<[-]<[-<<]>,]++++++++[->++++<]>[>[-<.>]<[->>+<<]>>+]

```

Try it online!

Wrapped:

```
+[+[>+<+<]>]>-[[>>]+[<<]>>-],[<+++++[>--
----<-]>-[>[>>]+[<<]>-]>[>>]<[-]<[-<<]>,
]++++++++[->++++<]>[>[-<.>]<[->>+<<]>>+]

```

Explained:

```
+[+[>+<+<]>]>-         initialize what we will now consider cell 0 to 95
[[>>]+[<<]>>-]         initialize cells 2 4 etc 95*2 to 1; end on cell 0 at 0
,[                     main input loop (for each char of input)
  <+++++[>------<-]>-  subtract 31 from the input
  [>[>>]+[<<]>-]       lay a trail of (input minus 31) ones in the empty spaces
  >[>>]<[-]<[-<<]>     use the trail to clear the appropriate "print" flag
,]                     keep reading input until it ends
++++++++[->++++<]>     initialize the cell directly before flag 1 to 32
[                      we'll let the accumulator overflow; no harm done
  >[-<.>]              print the accumulator if the flag is still set
  <[->>+<<]>>+         shift over the accumulator and increment it
]

```
> 2 votes

# Answer
# Ohm, 3 bytes

```
α@─

```

Try it online!

Note: you can also enter your input as a string (example), but it fails for the empty input case.
> 2 votes

# Answer
## Julia, 21 bytes

```
s->setdiff(' ':'~',s)

```
> 2 votes

# Answer
# Pip, 5 bytes

```
PADCa

```

Removes all chacracters in the input from a predefined variable.

Try it online!

# Pip, 9 bytes

```
PARM(X^a)

```

Converts the characters of the input to regex, and removes the characters from the printable ASCII builtin.

Try it online!
> 2 votes

# Answer
# APL (Dyalog Extended), <sup>~~14~~</sup> 10 bytes

```
⍞~⍨' '…'~'

```

Try it online!

-4 bytes from Adám!(inclusive range)

## Explanation

```
   ' '…'~'     range of chars in visible ASCII range
  ⍨            flip the arguments of the function on the left
⍞~             Get all characters not in input

```
> 2 votes

# Answer
# Pyth, 7 6 bytes

```
`.-srd\`
-srd\
```

`.-` `-` Subtract the second string from the first:

1. `srd\` Create a range from space char to the delete char
2. *implicitly read input*

Try it online!
> 2 votes

# Answer
# MUMPS, 35 bytes

```
r r,! f i=32:1:126 w:r'[$c(i) $c(i)

```

**Explanation**

* Assign input to `r` and write a newline (`!`)
* Loop from 32 to 126 and if r doesn't contain (`'[`) the character representation of the ASCII value (`$char()`, can be shortened to `$c()`), write the that character representation.
* You can attach conditionals to commands with a colon. So `w:1>0 "True"` is the same as `if 1>0 write "True"`

Try the code here
> 2 votes

# Answer
# PowerShell Core, ~~39~~ 32 bytes

```
$a=$args
' '..'~'|?{$_-cnotin$a}

```

Added splatting and case sensitivity

Try it online!

Inspired by `colsw`'s answer
> 2 votes

# Answer
# Thunno 2, 3 bytes

```
kcḍ

```

Attempt This Online!

#### Explanation

```
kcḍ  # Implicit input
  ḍ  # Symmetric set difference with...
kc   # ...all printable ASCII characters
     # Implicit output

```
> 2 votes

# Answer
# Factor, ~~26~~ 25 bytes

-1 byte by using  from `math.unicode` instead of `diff`, as suggested by @chunes

```
[ 32 126 [a,b] swap ∖ ]

```

Try it online!

TIO uses an old build of Factor; on the latest version, `[a,b]` from `math.ranges` has moved to `[a..b]` from `ranges`.

### Explanation

| Code | Explanation | Stack |
| --- | --- | --- |
| `[ ... ]` | Quotation (anonymous function) | `"Hello!"` |
| `32 126 [a,b]` | Inclusive range from 32 to 126 | `"Hello!" T{ range f 32 95 1 }` |
| `swap` | Swap so range is below input | `T{ range f 32 95 1 } "Hello!"` |
|  | Set difference | `" \"#$%&'()*+,-./012..."` |

This works because in Factor, a string is basically a list of codepoints, and all sequences are `set`s.
> 2 votes

# Answer
# , 50 bytes

```
function(s)intToUtf8(setdiff(32:126,utf8ToInt(s)))

```

returns an anonymous function. Converts the input string to integers, computes the set difference between the printable range and the input values, and then converts them back to a string and returns it.

Try it online!
> 1 votes

# Answer
# 05AB1E, ~~5~~ 4 bytes

-1 thanks to Emigna

```
žQsK

```

Try it online!

```
žQ   # Push all printable characters
  s  # Swap input to the top
   K # Push a with no b's (remove input characters from all printable character)

```
> 1 votes

# Answer
# C#, ~~74~~ 71 bytes

```
using System.Linq;s=>new int[95].Select((n,i)=>(char)(i+32)).Except(s);

```

Old version with creating a range for 74 bytes:

```
using System.Linq;s=>Enumerable.Range(32,95).Select(n=>(char)n).Except(s);

```
> 1 votes

# Answer
# C (gcc), ~~75~~ ~~72~~ ~~70~~ ~~68~~ ~~50~~ 49 bytes

Thanks to Peter -1 byte

```
i;f(s){for(i=31;++i<127;index(s,i)?:putchar(i));}

```

Try it online!
> 1 votes

# Answer
# PHP, 53 bytes

```
for($k=31;$k++<126;)~strstr($argn,$k)?:print chr($k);
# or
for($k=31;$k++<126;)echo~strstr($argn,$k)?"":chr($k);

```

Run as pipe with `-r`.
> 1 votes

# Answer
# , 20 bytes

```
òiÎflax
òcH ¬ ~@"<

```

Try it online!

Hexdump:

```
00000000: f269 ce66 1b6c 6178 0af2 6348 20ac 207e  .i.f.lax..cH . ~
00000010: 1b40 223c                                .@"<

```
> 1 votes

# Answer
# Charcoal, ~~18~~ ~~15~~ ~~10~~ 8 bytes

```
Ｆγ¿¬№θιι

```

Try it online! Link is to verbose version of code. Edit: Saved 3 bytes by ranging over characters instead of integers. Saved a further 5 bytes when I discovered the undocumented `γ` variable which holds the printable ASCII characters. Saved a further 2 bytes when @ASCII-only fixed predefined inputs in verbose mode (the answer is still valid as it stands, it's only the try it online link that wouldn't have worked at the time).
> 1 votes

# Answer
# , ~~20~~ 12 bytes

-8 bytes thanks to coltim.

```
^[`c$32+!94]

```

Try it online!

Explanation:

```
     32+!94  /list of int values of all printable characters
  `c$        /turn into characters
^[         ] /partial function application of "except"

```

What except `^` does is remove all instances of each of element in the right/second argument from the left/first argument.
> 1 votes

# Answer
# Husk, 6 bytes

```
-⁰…" ~

```

Try it online!
> 1 votes

# Answer
# Nim, 66 bytes

```
let s=stdin.readAll
for c in' '..'~':
 if c notin s:stdout.write c

```

Try it online!
> 1 votes

# Answer
# Vyxal, 4 bytes

```
kQ?F

```

Try it Online!

#### Explanation

```
kQ   # Printable ASCII
  ?F # Without the input

```
> 1 votes

# Answer
# Nibbles, 2.5 bytes

```
--_"\n"

```

Attempt This Online!

Unfortunately, the printable characters built-in in Nibbles also includes the newline, so we have to explicitly exclude it.

## Explanation

```
--_"\n"
-       List subtract
 -       list subtract
  _       printable characters
   "\n"   newline
         input

```
> 1 votes

# Answer
# Flip, 21 bytes

```
'  |D '+1<D:|g DX: #

```

Attempt This Online!

ATO is not working right now, but I tested this locally. Contains a raw `\x7F` byte.

This would have been easier if I hadn't removed the `J` builtin, which generates an inclusive range.

## Explanation

```
                             Push printable ASCII onto stack:

'                            Push space character
                             Loop body:
    D                            Duplicate the current char
      ' \x7f                     Push 127
          <                      Less than?
            :                    If so, mirror & do the following:
           D                         Duplicate TOS
         1
       +                             Add by 1
   |                                 Mirror the IP

                             Setwise difference w/ input:

              g              Read 1 char from the input
                D            Duplicate
                  :          Pop, is it nonzero? (i.e. not at EOF)
                             If so, mirror:
                 X               Remove all occurences of
                                 this char in the stack.
             |                   Mirror the IP back

                    #        When loop done, print entire stack as a string.
                             Terminate program.

```
> 1 votes

# Answer
# Arturo, 17 bytes

```
$=>[--@` `..`~`&]

```

Try it!

Takes and returns a list of characters.

```
$=>[         ; a function where input is assigned to &
    --       ; set difference
    @        ; reify range
    ` `..`~` ; the range of printable ascii characters
    &        ; input
]            ; end function

```
> 1 votes

# Answer
# T-SQL (SQL Server 2016), 519 bytes

```
with X as(select 32a,char(32)b union all select a+1,char(a+1)from X where a<126),E AS(SELECT n FROM(VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0))E(n)),F AS(SELECT a.n FROM E a,E b),G AS(SELECT a.n FROM F a,F b),T AS(SELECT ROW_NUMBER()OVER(ORDER BY(SELECT NULL))n FROM G),I as(SELECT ASCII(SUBSTRING(t,n,1))a FROM T JOIN(select @i as t)S on T.n<=LEN(S.t)where n=0),R as(select b from X where a not in(select a from I))select STUFF((SELECT''+b FROM R FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)'),1,1,'')

```

... but this assumes the input string is in `@i`, therefore a runnable script will look like:

```
declare @i varchar(101) = 'Test';

with X as(select 32a,char(32)b union all select a+1,char(a+1)from X where a<126),E AS(SELECT n FROM(VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0))E(n)),F AS(SELECT a.n FROM E a,E b),G AS(SELECT a.n FROM F a,F b),T AS(SELECT ROW_NUMBER()OVER(ORDER BY(SELECT NULL))n FROM G),I as(SELECT ASCII(SUBSTRING(t,n,1))a FROM T JOIN(select @i as t)S on T.n<=LEN(S.t)where n=0),R as(select b from X where a not in(select a from I))select STUFF((SELECT''+b FROM R FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)'),1,1,'')

```

Try it online!

### How it works

Use CTEs to split the input string into individual characters on separate rows in a result set; use a recursive CTE to generate a result set having individual characters on separate rows for all characters between ASCII values 32 and 126; select all rows from the latter where characters are not found in the former; use `STUFF` with `FOR XML PATH` to aggregate those characters (in lieu of the `STRING_AGG` function, which only arrived in SQL Server 2017).

### Legible version

```
declare @input varchar(101) = 'Test';

with X as (
    select 32a, char(32)b
    union all
    select a+1, char(a+1) from X where a < 126
),
E(n) AS(
    SELECT n FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0))E(n)
),
E2(n) AS(
    SELECT a.n FROM E a, E b
),
E4(n) AS(
    SELECT a.n FROM E2 a, E2 b
),
cteTally(n) AS(
    SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) n
    FROM E4
),
INPUT_STRING as (
    SELECT ASCII( SUBSTRING(term, n, 1)) as [ASCII Code]
    FROM cteTally t
    JOIN (select @input as term) S on t.n <= LEN(S.term)
    where n = 0
),
DATA_RESULTS as (
     select b from X where a not in (select [ASCII Code] from INPUT_STRING)
 )

 select STUFF( (SELECT '' + b FROM DATA_RESULTS FOR XML PATH (''),TYPE).value('(./text())[1]','VARCHAR(MAX)'), 1, 1, '' )
 ;

```

### Why?

Because I can.

### Can it be shorter?

Almost certainly!
> 1 votes

# Answer
# Mathematica, 35 bytes

```
20~CharacterRange~126~Complement~#&

```

Anonymous function. Takes a list of characters as input and returns a list of characters as output.
> 0 votes

# Answer
# JavaScript (ES6), ~~73~~ 72 bytes

```
f=(s,i=95)=>i?f(s,i-1)+(s.includes(c=String.fromCharCode(i+31))?'':c):''

```

This builds the string recursively, excluding characters found in the input.

**Snippet:**

```
f=(s,i=95)=>i?f(s,i-1)+(s.includes(c=String.fromCharCode(i+31))?'':c):''

console.log(f('Hello, World!'));
console.log(f('Hi'));
console.log(f(''));
console.log(f(' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'));
```
> 0 votes

# Answer
# Lua, 78 bytes

```
s=io.read()for i=32,126 do c=string.char(i)io.write(s:find(c,1,1)and""or c)end

```
> 0 votes

# Answer
# Aceto, 38 bytes

```
cC|d
dXpc
=`I&
LM-1I
d@7F&
€92-
r4*2

```

### Explanation

We first `r`ead the input string and explode it (, put the characters on the stack). Next, we push the numbers 34 (`94*2-`) and 127 (`27F1-`). The second value is then removed from the stack and memorized (`M`):

```
 M-1
  7F
€92-
r4*2

```

We then first set a catch mark so we can jump back to this place, and then `d`uplicate the number on the stack (the 34). We load the 126 from the quick memory and test for equality, in which case we exit:

```
 X
=`
L
d@

```

Otherwise, we duplicate the value again, convert it to a character of that number and check whether that character is already on the stack (`dcC`). If it is, we mirror to the right side:

```
cC|
d

```

Otherwise, we duplicate the value and convert it to a character again, print that character, increment the value and raise an exception, jumping back to the catch mark.

```
   d
  pc
  I&

```

If we mirrored, we just increment and raise an exception, too (`I&`).
> 0 votes

# Answer
# C, 57 bytes

```
i=32;f(char*s){for(;i<127;i++)!strchr(s,i)?putchar(i):0;}

```

How it works:

* Initially sets `i` to 32, the ASCII character code for the space (the first printable ASCII character).
* The function `f` takes a string `s`, the "input".
* Loops, incrementing `i` until it reaches `~` (126), the last printable ASCII character.
* `!strchr(s,i)` checks if `i` is *not* in `s`. If `i` is not in `s`, print `i`. Otherwise, do nothing.

I'm sure this can be golfed.
> 0 votes

# Answer
# Retina, ~~48~~ 45 bytes

```
^
95$*~¶
+T`p`_p`(.)(?=\1)
s`(.)(?=.*\1)|¶.*

```

Try it online! Includes test cases. Works by prepending a line of 95 `~`s, translating them into the printable ASCII characters, then deleting duplicate characters and the original input. Edit: Saved 3 bytes by matching the characters to be translated individually.
> 0 votes

# Answer
# shortC, 33 bytes

```
i;AOi=31;++i<'~';strchr(*@,i)?:Pi

```

Conversions made in this program:

* `A` -\> `int main(int argc, char **argv) {`
* `O` -\> `for(`
* `@` -\> `argv`
* `P` -\> `putchar`
* Auto-inserted closing `));}`

The resulting program looks like:

```
i;int main(int argc, char **argv){for(i=31;++i<'~';strchr(*argv,i)?:putchar(i));}

```

Try it online!
> 0 votes

# Answer
# Pyth, 17 bytes

```
Vr32 127I!}CNzpCN

```

The naive approach.

## Explanation:

```
Vr32 127I!}CNzpCN
Vr32 127             For N in [32, 127[
           CN        Get the ASCII character for the code N
        I!}  z       If it is in the input string...
              pCN    ...then print it

```

Test it online!
> 0 votes

# Answer
## Clojure, 60 or 49 bytes

```
#(apply str(sort(apply disj(set(map char(range 32 127)))%)))

```

These "apply"s are killing me :/ Oh, if returning a list is fine then this is a bit shorter.

```
#(sort(apply disj(set(map char(range 32 127)))%))

```
> 0 votes

# Answer
## QBIC, 32 bytes

```
[32,126|X=chr$(a)~instr(;,X)|\?X

```

Time to implement `chr$` and `instr` in QBIC...

```
[32,126|    Loop from 32 to 126
X=chr$(a)   Make X$ to be the character with Ascii value a (a is our loop counter)
~instr(;,X) If our input string (read from cmd line) contains cjar X$
|           THEN (empty, no-op)
\?X         ELSE, print char X$

```
> 0 votes

# Answer
# Java 8, 68 bytes

```
s->{for(char c=31;++c<127;System.out.print(s.contains(c+"")?"":c));}

```

Try it here.
> 0 votes

# Answer
## Pyke, 4 bytes

```
~KR-

```

Try it here!
> 0 votes

# Answer
## Python 3, 52 bytes

I feel like there ought to be a shorter way to grab all the unicode characters than this set comprehension, but I haven't found it yet.

```
lambda s:''.join({chr(i+34)for i in range(93)}-set(s))

```
> 0 votes

# Answer
# PowerShell, 44 Bytes

```
[char[]](32..126|?{$_-notin[char[]]"$args"})

```

creates an array of the numbers `32` through `126` (printable char codes)

finds the char codes not present in the input `$args` and then converts them back to a `char` array.

apparently the `1..5 -gt 3` trick doesn't work for `-in` or `-notin`, which would save a few bytes.
> 0 votes

# Answer
# Common Lisp, 79 bytes

```
(defun f(s)(dotimes(x 95)(let((y(code-char(+ 32 x))))(or(find y s)(princ y)))))

```

Very straightforward code.
> 0 votes

# Answer
# Japt, 5 bytes

```
;EkU1

```

Try it \- includes all test cases

Note that quotation marks in input strings cannot be escaped in Japt and `%`s must be escaped with `%%`.
> 0 votes

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


title: Blue duck, red duck, gray duck

text:
# Question
Title: Blue duck, red duck, gray duck
So, last week I posted a challenge to play Duck, Duck, Goose. This lead to a number of Minnesotans commenting about their regional 'Gray duck' variation.

So here's the rules:

Using this list of colours:

```
Red
Orange
Yellow
Green
Blue
Indigo
Violet
Gray

```

Write a program to follow these rules:

1. Select one of these colours, and prepend it to the word 'duck' and print the result to a new line.
2. If the colour was not 'Gray', repeat step 1.
3. If the colour was 'Gray', end your program.

Rules which must be followed:

* The program should not consistently print the same number of lines.
* It can begin on 'Gray duck', but should not do consistently.
* There should be exactly one duck on each line and no empty lines are output.
* There should be at least one space between a colour and a duck.
* White space before and after the significant output does not matter.
* The case of the output doesn't matter.
* Colours can be repeated.
* The output doesn't have to contain every colour every time, but it must be possible that your code will output every colour.
* No colours outside the above array can be included.
* Either grey or gray are acceptable in your answer.
* Colours should not consistently be in the same order.
* Aim for the shortest program. Smallest number of bytes wins.

Example output:

```
Green duck
Orange duck
Yellow duck
Indigo duck
Yellow duck
Gray duck

```

Thanks to @Mike Hill for first alerting me to this variation.

# Answer
# Thunno 2, 41 bytes

```
(’Red ṆỴ »Ẹ Ɓ# Ñɦ ƲỤ ṡʂ Ɓ~’OɼD‘ _*‘+£`Ɓ~Q

```

Attempt This Online!

#### Explanation

```
(                     # While loop
 ’...’                # (condition)  Push compressed string of colours
      O               #              Split it on spaces
       ɼ              #              Pick a random item from this list
        D             #              Duplicate the item
         ‘ _*‘+       #              Append compressed string " duck"
               £      #              Pop and print with a newline
                `Ɓ~   #              Push compressed string "Grey"
                   Q  #              Check for inequality
                      # (body)  Do nothing

```
> 2 votes

# Answer
## LuaLaTeX, 220 211 characters

command:

```
lualatex -interaction nonstopmode

```

Not the shortest, but the fanciest. Based on @skillmon's solution

```
\RequirePackage{tikzducks}\newcount\b\let~\def~\0{red}~\1{orange}~\2{yellow}~\3{green}~\4{blue}~\5{cyan}~\6{violet}~\7{gray}\loop\b\uniformdeviate8\tikz\duck[body=\csname\the\b\endcsname]; \ifnum\b<7\repeat\stop

```
> 51 votes

# Answer
# 6502 machine code (C64), 124 bytes

```
00 C0 AD 12 D0 85 02 A2 17 8E 18 D0 A5 02 F0 03 0A 90 02 49 1D 85 02 A8 CA 10
02 A2 2F BD 42 C0 D0 F6 88 D0 F3 86 FB E8 BD 42 C0 F0 06 20 16 E7 E8 D0 F5 AA
BD 73 C0 F0 06 20 16 E7 E8 D0 F5 A6 FB D0 C9 60 00 C7 52 45 59 00 D2 45 44 00
CF 52 41 4E 47 45 00 D9 45 4C 4C 4F 57 00 C7 52 45 45 4E 00 C2 4C 55 45 00 C9
4E 44 49 47 4F 00 D6 49 4F 4C 45 54 00 20 44 55 43 4B 0D 00

```

**Online demo** -- Usage: `SYS49152`.

---

### Explanation (commented disassembly):

```
         00 C0       .WORD $C000        ; load address
.C:c000  AD 12 D0    LDA $D012          ; current rasterline as seed
.C:c003  85 02       STA $02            ; to "random" value
.C:c005  A2 17       LDX #$17           ; cfg for upper/lower, also use as
.C:c007  8E 18 D0    STX $D018          ;    initial index into colors array
.C:c00a   .loop:
.C:c00a  A5 02       LDA $02            ; load current random val
.C:c00c  F0 03       BEQ .doEor         ; zero -> feedback
.C:c00e  0A          ASL A              ; shift left
.C:c00f  90 02       BCC .noEor         ; bit was shifted out -> no feedback
.C:c011   .doEor:
.C:c011  49 1D       EOR #$1D
.C:c013   .noEor:
.C:c013  85 02       STA $02            ; store new random val
.C:c015  A8          TAY                ; use as counter for next color string
.C:c016   .findloop:
.C:c016  CA          DEX                ; next char pos in colors (backwards)
.C:c017  10 02       BPL .xok           ; if negative ...
.C:c019  A2 2F       LDX #$2F           ;    load length of colors - 1
.C:c01b   .xok:
.C:c01b  BD 42 C0    LDA .colors,X      ; load character from colors
.C:c01e  D0 F6       BNE .findloop      ; not zero, try next character
.C:c020  88          DEY                ; decrement random counter
.C:c021  D0 F3       BNE .findloop      ; not zero, continue searching
.C:c023  86 FB       STX $FB            ; save character position
.C:c025  E8          INX                ; increment to start of color
.C:c026   .outloop:
.C:c026  BD 42 C0    LDA .colors,X      ; output loop for color string
.C:c029  F0 06       BEQ .duckout
.C:c02b  20 16 E7    JSR $E716
.C:c02e  E8          INX
.C:c02f  D0 F5       BNE .outloop
.C:c031   .duckout:
.C:c031  AA          TAX                ; A is now 0, use as char pos for duck
.C:c032   .duckoutloop:
.C:c032  BD 73 C0    LDA .duck,X        ; output loop for duck string
.C:c035  F0 06       BEQ .outdone
.C:c037  20 16 E7    JSR $E716
.C:c03a  E8          INX
.C:c03b  D0 F5       BNE .duckoutloop
.C:c03d   .outdone:
.C:c03d  A6 FB       LDX $FB            ; load saved character position
.C:c03f  D0 C9       BNE .loop          ; not zero -> continue main loop
.C:c041  60          RTS                ; zero was start of "Grey" -> done
.C:c042   .colors:
.C:c042  00 c7 52 45    .BYTE 0, "Gre"
.C:c046  59 00 d2 45    .BYTE "y", 0, "Re"
.C:c04a  44 00 cf 52    .BYTE "d", 0, "Or"
.C:c04e  41 4e 47 45    .BYTE "ange"
.C:c052  00 d9 45 4c    .BYTE 0, "Yel"
.C:c056  4c 4f 57 00    .BYTE "low", 0
.C:c05a  c7 52 45 45    .BYTE "Gree"
.C:c05e  4e 00 c2 4c    .BYTE "n", 0, "Bl"
.C:c062  55 45 00 c9    .BYTE "ue", 0, "I"
.C:c066  4e 44 49 47    .BYTE "ndig"
.C:c06a  4f 00 d6 49    .BYTE "o", 0, "Vi"
.C:c06e  4f 4c 45 54    .BYTE "olet"
.C:c072  00             .BYTE 0
.C:c073   .duck:
.C:c073  20 44 55 43    .BYTE " duc"
.C:c077  4b 0d 00       .BYTE "k", $d, 0

```
> 27 votes

# Answer
## Perl 5, 79 bytes

```
say$_=(Grey,Red,Orange,Yellow,Green,Blue,Indigo,Violet)[rand 8]." duck"until/y/

```

Try it online!
> 12 votes

# Answer
# Taxi, 1995 bytes

```
Go to Heisenberg's:w 1 r 3 r 1 l.[a]Pickup a passenger going to Divide and Conquer.8 is waiting at Starchild Numerology.8 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 3 l 1 l 3 l.Pickup a passenger going to Divide and Conquer.Pickup a passenger going to Multiplication Station.Go to Divide and Conquer:w 1 r 3 r 1 r 2 r 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 l 1 l 2 l.Pickup a passenger going to What's The Difference.Pickup a passenger going to Trunkers.Go to Zoom Zoom:n.Go to Trunkers:w 3 l.Pickup a passenger going to What's The Difference.Go to What's The Difference:w 2 r 1 l.Pickup a passenger going to Multiplication Station.1 is waiting at Starchild Numerology.Go to Starchild Numerology:e 1 r 1 l 3 l.Pickup a passenger going to Addition Alley.Go to Multiplication Station:w 1 r 2 r 1 r 4 l.Pickup a passenger going to Addition Alley.Go to Addition Alley:n 2 l 1 r 3 l 1 l.Pickup a passenger going to The Underground.'Red duck\n' is waiting at Writer's Depot.'Orange duck\n' is waiting at Writer's Depot.'Yellow duck\n' is waiting at Writer's Depot.'Green duck\n' is waiting at Writer's Depot.'Blue duck\n' is waiting at Writer's Depot.'Indigo duck\n' is waiting at Writer's Depot.'Violet duck\n' is waiting at Writer's Depot.'Grey duck' is waiting at Writer's Depot.Go to Writer's Depot:n 1 l 1 l.[b]Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 3 r 1 l 1 r.Go to The Underground:e 1 r.Switch to plan "c" if no one is waiting.Pickup a passenger going to The Underground.Go to Writer's Depot:s 2 r 1 l 2 l.Switch to plan "b".[c]Go to Narrow Path Park:n 4 l.Pickup a passenger going to Post Office.Go to Post Office:e 1 r 4 r 1 l.Go to Writer's Depot:s 1 r 1 l 2 l.Switch to plan "a" if no one is waiting.[d]Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 2 r.Go to Writer's Depot:n 1 l.Switch to plan "e" if no one is waiting.Switch to plan "d".[e]Go to Heisenberg's:n 3 r 3 r.Switch to plan "a".

```

Try it online!

I think it's worth noting that 47% of this code is just picking a random integer from 1 to 8.
Also, Taxi is so verbose that it is way shorter to hard code the `duck\n` after each color rather than concatenating it later.
Here's the un-golfed version:

```
Go to Heisenberg's: west 1st right 3rd right 1st left.

[Pick up a random INT 1-8 going to The Underground]
[a]
Pickup a passenger going to Divide and Conquer.
8 is waiting at Starchild Numerology.
8 is waiting at Starchild Numerology.
Go to Starchild Numerology: north 1st left 3rd left 1st left 3rd left.
Pickup a passenger going to Divide and Conquer.
Pickup a passenger going to Multiplication Station.
Go to Divide and Conquer: west 1st right 3rd right 1st right 2nd right 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: east 1st left 1st left 2nd left.
Pickup a passenger going to What's The Difference.
Pickup a passenger going to Trunkers.
Go to Zoom Zoom: north.
Go to Trunkers: west 3rd left.
Pickup a passenger going to What's The Difference.
Go to What's The Difference: west 2nd right 1st left.
Pickup a passenger going to Multiplication Station.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: east 1st right 1st left 3rd left.
Pickup a passenger going to Addition Alley.
Go to Multiplication Station: west 1st right 2nd right 1st right 4th left.
Pickup a passenger going to Addition Alley.
Go to Addition Alley: north 2nd left 1st right 3rd left 1st left.
Pickup a passenger going to The Underground.

[Use the random INT to select a color]
'Red duck\n' is waiting at Writer's Depot.
'Orange duck\n' is waiting at Writer's Depot.
'Yellow duck\n' is waiting at Writer's Depot.
'Green duck\n' is waiting at Writer's Depot.
'Blue duck\n' is waiting at Writer's Depot.
'Indigo duck\n' is waiting at Writer's Depot.
'Violet duck\n' is waiting at Writer's Depot.
'Grey duck' is waiting at Writer's Depot.
Go to Writer's Depot: north 1st left 1st left.
[b]
Pickup a passenger going to Narrow Path Park.
Go to Narrow Path Park: north 3rd right 1st left 1st right.
Go to The Underground: east 1st right.
Switch to plan "c" if no one is waiting.
Pickup a passenger going to The Underground.
Go to Writer's Depot: south 2nd right 1st left 2nd left.
Switch to plan "b".

[Output the selected color]
[c]
Go to Narrow Path Park: north 4th left.
Pickup a passenger going to Post Office.
Go to Post Office: east 1st right 4th right 1st left.

[If the color was grey, exit by error]
Go to Writer's Depot: south 1st right 1st left 2nd left.
Switch to plan "a" if no one is waiting.

[Get rid of the rest of the colors]
[You could throw them off a bridge but you won't get paid]
[d]
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park: north 2nd right.
Go to Writer's Depot: north 1st left.
Switch to plan "e" if no one is waiting.
Switch to plan "d".

[Start over from the beginning]
[e]
Go to Heisenberg's: north 3rd right 3rd right.
Switch to plan "a".

```
> 11 votes

# Answer
# Java (OpenJDK 9), 133 bytes

```
v->{for(int x=9;x>0;)System.out.println("Grey,Red,Orange,Yellow,Green,Blue,Indigo,Violet".split(",")[x+=Math.random()*8-x]+" duck");}

```

Try it online!

## Explanations

```
v->{                              // Void-accepting void lambda function
  for(int x=9;x>0;)               //  Loop until x is zero
    System.out.println(           //   Print...
        "Grey,Red,Orange,         //       colors, "Grey" first
         Yellow,Green,Blue,       //          more colors
         Indigo,Violet"           //          more colors
        .split(",")               //       as an array
          [x+=Math.random()*8-x]  //       pick one randomly, use implicit double to int cast with "x+=<double>-x" trick
        +" duck");                //      Oh, and append " duck" to the color.
}

```
> 9 votes

# Answer
# Ruby, ~~93 91 90 89 87 86~~ 85 bytes

Thanks to Dom Hastings for saving 2 bytes, Kirill L. 1 byte and Asone Tuhid 1 byte!

```
puts %w(Red Orange Yellow Green Blue Indigo Violet Grey)[$.=rand(8)]+" duck"while$.<7

```

Try it online!
> 8 votes

# Answer
# Operation Flashpoint scripting language, 133 bytes

```
f={s="";v=s;while{v!="grey"}do{v=["Red","Orange","Yellow","Green","Blue","Indigo","Violet","Grey"]select random 7;s=s+v+" duck\n"};s}

```

**Call with:**

```
hint call f

```

**Example output:**

At first I somehow misread the challenge as if the goal was to just output a varying amount of lines, not necessarily ending at the "Grey duck" -line. Following that incorrect interpretation produced a slightly more interesting piece of code:

```
f={s="";c=[1];c set[random 9,0];{s=s+(["Red","Orange","Yellow","Green","Blue","Indigo","Violet","Grey"]select random 7)+" duck\n"}count c;s}

```
> 8 votes

# Answer
# pdfTeX, 231 220 219 209 207 bytes

```
\newcount\b\let~\def~\0{Red}~\1{Orange}~\2{Yellow}~\3{Green}~\4{Blue}~\5{Indigo}~\6{Violet}~\7{Gray}~\9{ }\newlinechar`z\loop\b\pdfuniformdeviate8\message{z\csname\the\b\endcsname\9duck}\ifnum\b<7\repeat\bye

```

# LuaTeX, 216 ~~206~~ 204 bytes

```
\newcount\b\let~\def~\0{Red}~\1{Orange}~\2{Yellow}~\3{Green}~\4{Blue}~\5{Indigo}~\6{Violet}~\7{Gray}~\9{ }\newlinechar`z\loop\b\uniformdeviate8\message{z\csname\the\b\endcsname\9duck}\ifnum\b<7\repeat\bye

```
> 7 votes

# Answer
# 05AB1E, ~~42~~ 40 bytes

Saved 2 bytes thanks to *Erik the Outgolfer*

```
[“ëßigo°¯†¾›ÈŠÛˆ¨‡—°Íolet“#7ÝΩ©è'Ðœðý,®#

```

Try it online!
> 6 votes

# Answer
# Brachylog, 68 bytes

```
"Grey","
Red
Orange
Yellow
Green
Blue
Indigo
Violet"ṇṛS," duck"ẉS¬?↰

```

Try it online!
> 5 votes

# Answer
# Ruby, ~~84~~ 81 bytes

Thanks to Dom Hastings for -3 bytes.

```
puts$_=%w[Red Orange Yellow Green Blue Indigo Violet Grey].sample+" duck"until/y/

```

Try it online!
> 5 votes

# Answer
# Bash + GNU utilities, 72

```
shuf -e {Red,Orange,Yellow,Green,Blue,Indigo,Violet,Grey}\ Duck|sed /y/q

```

Try it online.
> 5 votes

# Answer
# PHP, 89 bytes

```
do echo[Grey,Red,Orange,Yellow,Green,Blue,Indigo,Violet][$i=rand()%8]," Duck
";while($i);

```

Run with `-nr` or try it online.
> 5 votes

# Answer
# \>\<\>, 107 bytes

```
x<>" duck"a>
x<^"deR"
x<^"egnarO"
x<^"wolleY"
x<^"neerG"
x<^"eulB"
x<^"ogidnI"
x<^"teloiV"
x"Grey duck"r>o|

```

Try it online!
> 4 votes

# Answer
# JavaScript, 104 bytes

```
f=_=>`grey,red,orange,yellow,green,blue,indigo,violet`.split`,`[n=Math.random()*8|0]+` duck
${n?f():``}`

```

Try it online
> 4 votes

# Answer
# Python 3, 130, 128, 127, 126, 125 bytes

```
from random import*
d,c=1,'Grey Red Orange Yellow Green Blue Indigo Violet'.split()
while d!=c[0]:d=choice(c);print(d,'duck')

```

-1 by @ElPedro!
-1 by me
-1 by @Bubbler!

Try it online!
> 4 votes

# Answer
# Python 2, ~~138~~ ~~133~~ ~~120~~ ~~117~~ 116 bytes

```
import os
while id:id=ord(os.urandom(1))%8;print"Grey Red Orange Yellow Green Blue Indigo Violet".split()[id],'duck'

```

Try it online!

Much better with some ideas from @EriktheOutgolfer. Thanks!

-3 more with thanks to @ovs

-1 with thanks to @Rod for a cool new trick learned :-)
> 4 votes

# Answer
# Octave, ~~114~~ 112 bytes

```
do disp([strsplit('Red Orange Yellow Green Blue Indigo Violet'){i=randi(7)},' duck'])until i>6
disp('Grey duck')

```

Try it online!

There are a bunch of different options that are all between 112 and 118 bytes... Some initialize an index in the start and decrements it by a random number for each loop, and waits until it's **0**. Others use `printf` instead of `disp` to avoid some brackets and so on.
> 4 votes

# Answer
# PHP, ~~133~~ ~~125~~ ~~111~~ ~~108~~ ~~97~~ 92 bytes

```
<?for(;$b=[Red,Orange,Yellow,Green,Blue,Indigo,Violet][rand(0,7)];)echo"$b duck
"?>Grey duck

```

Try it online!

-8 bytes thanks to @Olivier Grégoire

-3 bytes thanks to @manatwork

-11 bytes thanks to @Dom Hastings
> 4 votes

# Answer
## bash, 96 bytes

```
a=(Grey Red Orange Yellow Green Blue Indigo Violet);for((i=1;i;));{ echo ${a[i=RANDOM%8]} duck;}

```

Thanks to @DigitalTrauma.
> 4 votes

# Answer
## Retina, ~~69~~ 68 bytes

*Thanks to Leo for saving 1 byte.*

```
.^/y/{K`Red¶Orange¶Yellow¶Green¶Blue¶Indigo¶Violet¶Grey
" duck¶">?G`

```

Try it online!

### Explanation

```
./y/^{K`Red¶Orange¶Yellow¶Green¶Blue¶Indigo¶Violet¶Grey

```

`.` suppresses implicit output at the end of the program (otherwise, we'd get two grey ducks). `/y/^{` wraps the entire program in a loop which continues as long as the working string doesn't contain a `y`. The rest of that line sets the working string to a linefeed-separated list of all the colours.

```
" duck¶">G?`

```

We grep a random line from the working string (and therefore a random colour). And we print the result with a trailing  `duck` and a linefeed.
> 3 votes

# Answer
# AWK, 114 bytes

```
{srand();for(split("Red9Orange9Yellow9Green9Blue9Indigo9Violet9Grey",A,9);r<8;print A[r]" duck")r=int(8*rand()+1)}

```

Try it online!

**Explanation**

```
{srand();                  # Seed rand to obtain different sequence each run
for(
     split("Red9Orange9Yellow9Green9Blue9Indigo9Violet9Grey",
            A,9);          # Split on 9 to avoid using '"'s
     r<8;
     print A[r]" duck")    # Print the colored ducks
     r=int(8*rand()+1)     # AWK uses 1-indexing not 0-indexing when splitting strings into arrays
}

```

Note that this requires "some" input. The input can be empty. To avoid the need for input prepend the first line with `BEGIN`
> 3 votes

# Answer
# PowerShell, 94 bytes

```
for(;$r-ne'Grey'){$r=-split"Red
Orange
Yellow
Green
Blue
Indigo
Violet
Grey"|Random;"$r Duck"}

```

Try it online!

Loops until `$r` is equal to `Grey`. Inside the loop, `-split`s the literal string on newlines, chooses a `Random` one thereof, then prints out the color plus `Duck` (technically, it's left on the pipeline and pipeline cleanup on the next loop iteration causes a `Write-Output` to happen). Note that it's theoretically possible for `Grey` to never be chosen, and the loop to continue infinitely, but this almost never (in the probability sense) will happen.
> 3 votes

# Answer
# , 101 bytes

```
cat(paste(c(sample(scan(,""),rexp(1),T),"gray"),"duck\n"))
Red
Orange
Yellow
Green
Blue
Indigo
Violet

```

Try it online!

Heavily inspired by @user2390246's answer to the related challenge. We need two sources of randomness: Changing the order of the colors and sampling the non-gray duck colors. The `sample` will take a random sample of random size given by an exponential distribution with rate parameter `1`, truncated to an integer. Using an exponential distrubtion unfortunately means that there is a probability of `exp(-8)` or around `0.0003354` that the sample will be at least `8`, so we have to sample with `replace=T`.
> 3 votes

# Answer
# MATL, ~~68~~ 64 bytes

```
`'DYCIXMSQ(qm#Q$4{#is,Gh1(=lAjUSId;&'F2Y232hZaYb8YrX)' duck'h7Mq

```

Try it online!

# Explanation

```
`                         % Do...while
  'DYCI···Id;&'           %   Push this string (to be decompressed by base conversion)
  F                       %   Push false
  2Y2                     %   Push string 'abc...xyz'
  32                      %   Push 32 (ASCII for space)
  h                       %   Concatenate horizontally. Gives 'abc...xyz '
  Za                      %   Base-convert from alphabet of all printable ASCII
                          %   characters except single quote (represented by input
                          %   false) to alphabet 'abc...xyz '. Produces the string
                          %   'grey red ··· violet'
  Yb                      %   Split on space. Gives a cell array of strings
  8Yr                     %   Random integer from 1 to 8, say k
  X)                      %   Get the content of the k-th cell
  ' duck'                 %   Push this string
  h                       %   Concatenate horizontally
  7M                      %   Push k again
  q                       %   Subtract 1
                          % Implicit end. Run a new iteration if top of the stack
                          % is non-zero
                          % Implicit display

```
> 3 votes

# Answer
# Python 2, 98 bytes

**Look ma no imports!**

```
v=0
while 1:x=id(v)%97%8;print"GVIYORGBrinererleodladeuyliln ee egog n  towe"[x::8],"duck";v=1/x,v

```

(Prints extra spaces between the colours and `duck` as allowed in the question)

**Try it online!**

A pretty poor pseudo-random number generator seeded with the object id of **0** (but it seems to fit the spec) which repeatedly yields an integer, `x`, in **\[0,7\]** which is used to slice a list of characters from that index in steps of **8** to get the colour name which is printed along with `duck` as a tuple, forcing a space in-between. When `x` becomes zero `Grey` is printed and the evaluation of the next input to the modulo based random number generator errors attempting to divide by zero (`v=1/x,v` tries to make a new tuple with the first element `1/x` = `1/0`)

---

Same way is 100 in Python 3 with

```
v=0
while 1:x=id(v)%17%8;print("GVIYORGBrinererleodladeuyliln ee egog n  towe"[x::8],"duck");v=1/x,v

```
> 3 votes

# Answer
# Java (JDK 10), 287 bytes

```
Random r=new Random();int i;String c;do{i=r.nextInt(8);switch(i){case 0:c="Red";break;case 1:c="Orange";break;case 2:c="Yellow";break;case 3:c="Green";break;case 4:c="Blue";break;case 5:c="Indigo";break;case 6:c="Violet";break;default:c="Gray";}System.out.println(c+" duck");}while(i!=7)

```

Try it online!

My very first codegolf! Obviously not competitive, just happy to have learned enough Java (currently in CS200) to be able to participate.
> 3 votes

# Answer
# Japt, ~~54~~ ~~53~~ 52 bytes

Could probably be shorter but my tool for finding the optimal permutation of the string to compress is crapping out on this, for some reason.

```
_èSiy}a@P±` Ýõ
`i`gÎ9h½uehéHÃÎÁeâ¸©ºÄgohgyËB`qh ö

```

Test it

1 byte saved thanks to Oliver
> 2 votes

# Answer
# APL (Dyalog Unicode), 86 bytes

```
{×⍵:∇r⊣⎕←'Grey' 'Red' 'Orange' 'Yellow' 'Green' 'Blue' 'Indigo' 'Violet'[r←?8]'duck'}1

```

Try it online!

Assumes `⎕IO←0`.
> 2 votes

# Answer
# Kotlin, 122 bytes

```
while({x:Any->println("$x duck");x!="Grey"}("Red,Orange,Yellow,Green,Blue,Indigo,Violet,Grey".split(",").shuffled()[0])){}

```

Try it online!
> 2 votes

# Answer
# T-SQL, ~~195~~ ~~185~~ 184 bytes

```
DECLARE @ VARCHAR(9)=''WHILE @<>'Grey'BEGIN SELECT @=c FROM(VALUES('Red'),('Orange'),('Yellow'),('Green'),('Blue'),('Indigo'),('Violet'),('Grey'))v(c)ORDER BY NEWID()PRINT @+' Duck'END

```
> 2 votes

# Answer
# MS-SQL, 158 bytes

```
DECLARE @ VARCHAR(6)a:SELECT @=value FROM STRING_SPLIT('Red,Orange,Yellow,Green,Blue,Indigo,Violet,Grey',',')ORDER BY NEWID()PRINT @+' duck'IF @<>'Grey'GOTO a

```

Based largely on Razvan's excellent answer, but using the `STRING_SPLIT` function that is specific to MS-SQL 2016 and later. Also uses a `GOTO` instead of a `WHILE` loop.

Formatted:

```
DECLARE @ VARCHAR(6)
a:
    SELECT @=value FROM
        STRING_SPLIT('Red,Orange,Yellow,Green,Blue,Indigo,Violet,Grey',',')
        ORDER BY NEWID()
    PRINT @+' duck'
IF @<>'Grey'GOTO a

```
> 2 votes

# Answer
x86\_64 machine code, 120 bytes.

I got inspired by the 6502 machine code and implemented the same in x86\_64 machine code.

```
0x603000: 0x47    0x72    0x61    0x79    0x20    0x00    0x00    0x00
0x603008: 0x52    0x65    0x64    0x20    0x00    0x00    0x00    0x00
0x603010: 0x4f    0x72    0x61    0x6e    0x67    0x65    0x20    0x00
0x603018: 0x59    0x65    0x6c    0x6c    0x6f    0x77    0x20    0x00
0x603020: 0x47    0x72    0x65    0x65    0x6e    0x20    0x00    0x00
0x603028: 0x42    0x6c    0x75    0x65    0x20    0x00    0x00    0x00
0x603030: 0x49    0x6e    0x64    0x69    0x67    0x6f    0x20    0x00
0x603038: 0x56    0x69    0x6f    0x6c    0x65    0x74    0x20    0x00
0x603040: 0x64    0x75    0x63    0x6b    0x0a    0x00    0x0f    0x31
0x603048: 0xc1    0xe8    0x03    0x33    0xdb    0x83    0xc3    0x07
0x603050: 0x23    0xd8    0x8b    0xfb    0xc1    0xe7    0x03    0x48
0x603058: 0x81    0xc7    0x00    0x30    0x60    0x00    0xe8    0x73
0x603060: 0xd5    0xdf    0xff    0x48    0xc7    0xc7    0x40    0x30
0x603068: 0x60    0x00    0xe8    0x67    0xd5    0xdf    0xff    0x85
0x603070: 0xdb    0x0f    0x85    0xcf    0xff    0xff    0xff    0xc3

```

Or the disassembly:

```
   0x603046:  rdtsc
   0x603048:  shr    eax,0x3
   0x60304b:  xor    ebx,ebx
   0x60304d:  add    ebx,0x7
   0x603050:  and    ebx,eax
   0x603052:  mov    edi,ebx
   0x603054:  shl    edi,0x3
   0x603057:  add    rdi,0x603000
   0x60305e:  call   0x4005d6 <printf>
   0x603063:  mov    rdi,0x603040
   0x60306a:  call   0x4005d6 <printf>
   0x60306f:  test   ebx,ebx
   0x603071:  jne    0x603046
   0x603077:  ret

```

The first 70 bytes is a string table that looks like:

```
Gray\0\0\0\0
Red\0\0\0\0\0
Yellow\0\0
...
 duck\0

```

There is certainly room for optimizations and it might not be the shortest implementation in terms of bytes but it probably competes for least amount of bytes executed :)
> 2 votes

# Answer
# Vyxal, 49 bytes

```
λ`⟇∴ ɾ⟩ °√ ×ŀ ⟇↵ ¯Ǔ⋏ġ Vio⟇» ←√`⌈℅:` ¦ø`+,‛←√≠[x|¤

```

Try it Online!
> 2 votes

# Answer
# Red, 96 91 bytes

```
until[n: random 8 print[pick[Red Orange Yellow Green Blue Indigo Violet Grey]n"duck"]n = 8]

```

Try it online!
> 1 votes

# Answer
# APL+WIN, 106 bytes

```
⊃('red' 'orange' 'yellow' 'green' 'blue' 'indigo' 'violet' 'grey')[(↑(m=8)/⍳⍴m)↑m←1+8|n←1E3?1E3],¨⊂' duck'

```

Generates a vector of random integers between 1 and 8 and takes the series up to and including the first occurance of an 8 as indices into the colour vector and then concatenates the duck.
> 1 votes

# Answer
# C (gcc), ~~138~~ ~~133~~ ~~123~~ 122 bytes

Saved a byte thanks to @ceilingcat

```
*c[]={"Grey","Red","Orange","Yellow","Green","Blue","Violet"};main(i){for(;printf("%s duck\n",c[i=time(sleep(1))%6])*i;);}

```

Try it online!
> 1 votes

# Answer
## PHP, 166, 148, 142 98 Bytes

Down to 98 bytes thanks to Shaggy and Titus.

I tried a recursive solution.

```
function f(){echo[grey,red,orange,yellow,green,blue,indigo,violet][$n=rand()&7]." duck
 ";$n&&f();}

```

**Explanation**

```
function f(){
  echo[grey,red,orange,yellow,green,blue,indigo,violet][$n=rand()&7]
  //a line break goes here, thats why it skips a line after duck
  //saves one byte over \n
        ." duck
         ";
  $n&&f();
}

```

For real it does not need much, the function will stop when `$n == false` or as php asumes `$n == 0` as a `false` then it leaves the method.

Try it online

Don't really know how to "golf code", but i found this forum really, really fascinating.
> 1 votes

# Answer
# SOGL V0.12, ~~40~~ ~~39~~ 38 bytes

```
]"sω2a⁄Ξ┌┼0⁾    a║EΣ?GΘƨ+}‘θJ;7ψ:≥w⁽OX@oo

```

Try it Here!
> 1 votes

# Answer
## Pyth, 72 bytes(SBCS)

```
K" Duck"#=kOc." y9Fª¹Ú¹«·.Û»õx¾jL[`ýõ?;ß¼<|9ü"\ +kKIqk"Gray"B

```

Try it online!

Python 3 translation:
```
import random
K=" Duck"
while True:
    k=random.choice("Red Orange Yellow Green Blue Indigo Violet Gray".split())
    print(k+K)
    if k=="Gray":
        break

```
> 1 votes

# Answer
# T-SQL, ~~211~~ 178 bytes

```
SELECT c+' Duck'FROM(SELECT TOP(CAST(RAND()*9AS INT))c FROM(VALUES('Red'),('Orange'),('Yellow'),('Green'),('Blue'),('Indigo'),('Violet'))v(c)ORDER BY NEWID()UNION SELECT'Grey'c)q

```

SQLFiddle
> 1 votes

# Answer
# Swift, 161 143 bytes

```
import Foundation;var x=9;while x>0{x=time(nil)%7;print(["Grey","Red","Orange","Yellow","Green","Blue","Indigo","Violet"][x]+" duck");sleep(1)}

```

Thanks to @cleblanc, whom I got the idea of the shorter code from.

**Explanation**

```
import Foundation                   //we need Foundation for time

var x = 9

while x > 0 {
    x = time(nil)%7
    print(["Grey",
           "Red",
           "Orange",
           "Yellow",
           "Green",
           "Blue",
           "Indigo",
           "Violet"][x] + " duck") //subscripting color array, appending "duck"
            sleep(1)
}

```

Try it online!
> 1 votes

# Answer
# Python 3, 127 bytes

```
from random import *;x=''
while'Grey'!=x:x=choice('Red,Orange,Yellow,Green,Blue,Indigo,Violet,Grey'.split(','));print(x,'duck')

```

Try it online!
> 1 votes

# Answer
# Perl 6/Rakudo 78 bytes

```
say $_=<Grey Red Orange Yellow Green Blue Indigo Violet>.roll~" duck"until /y/

```

Stealing directly from Dom Hastings' Perl 5 answer

Perl 6 wins slightly with `.roll`
> 1 votes

# Answer
# SmileBASIC, ~~134~~ 116 bytes

```
DIM C$[8]C=RND(8)COPY C$,@L@L?C$[C];" duck
EXEC!C
DATA"Gray","Red","Orange","Yellow","Green","Blue","Indigo","Violet

```
> 1 votes

# Answer
# Python 3, 124 bytes

```
import random
b=1
while b>0:b=random.randint(0,7);print('Gray Red Orange Yellow Green Blue Indigo Violet'.split()[b],'duck')

```

Try it online!

I almost always accompany my posts with explanations, but this one seems simple enough that I feel confident going without one...
> 1 votes

# Answer
# F#, 171 bytes

```
let r=System.Random()
let mutable i=r.Next(8)
while i<>7 do
 printfn"%s duck"["Red";"Orange";"Yellow";"Green";"Blue";"Indigo";"Violet"].[i]
 i<-r.Next(8)
printf"Grey duck"

```

Try it online!

That flipping "mutable" keyword! I thought that F#'s lack of a do/while loop (it only has while/do) would hurt me, but on retrospect it worked out, since "Grey duck" is always printed without a line separator (printfn versus printf), so there's no trailing empty line.
> 1 votes

# Answer
# Visual Basic for Applications, ~~110~~ 102 bytes

Edit: saved eight more bytes by using `split()` instead of `array()`

```
while rnd>.3:?split("Red,Orange,Yellow,Green,Blue,Indigo,Violet",",")(rnd*6)+" duck":wend:?"Gray duck"

```

Type in the immediate window.
> 1 votes

# Answer
# C (gcc), 104 bytes

```
f(n){for(;printf("%.6s duck\n","Gray\0 OrangeYellowIndigoVioletGreen\0Blue\0 Red"+(n=time(0)%7)*6),n;);}

```

Try it online!
> 1 votes

# Answer
# TI-BASIC, 80 bytes

```
Repeat not(I
int(8rand→I
Disp sub("GRAY  RED   ORANGEYELLOWGREEN BLUE  INDIGOVIOLET",6I+1,6)+" DUCK
End

```
> 1 votes

# Answer
# Bash + Coreutils, 100 Bytes

```
B=`shuf -en1 Red Orange Yellow Green Blue Indigo Violet Gray`;echo $B duck;[[ $B = Gray ]]||bash $0

```
> 1 votes

# Answer
# ink, ~~78~~ 87 bytes

```
-(e){RANDOM(0,1):{~Red|Orange|Yellow|Green|Blue|Indigo|Violet} duck|Gray duck->END}
->e

```

Try it online!

### Explanation

```
-(e){RANDOM(0,1):{~Red|Orange|Yellow|Green|Blue|Indigo|Violet} duck|Gray duck->END}  // With a 50% chance of each, either pick a colour that hasn't been picked already (unless all others have also been picked) and print it followed by "duck", or print "Gray duck" and terminate.
->e   // if we haven't terminated we get here and go back to the line above

```

`+9 bytes`: Apparently shuffles in ink will not repeat an option until all options have been visited. This means the previous version of my program was not valid, since it would always encounter "gray" before it could encounter any other colour for the second time, and thus broke the "Colours can be repeated" rule. The new answer will print each non-gray colour once until all have been printed, then shuffle again and restart - except every time it's about to pick a colour there's a 50% chance it instead prints gray and terminates.
> 1 votes

---
Tags: code-golf
---