# Question
Title: Build a typing speed test / measuring CPM
## The Rules

It's time to build a typing speed test in your language of choice!

**1**. You provide a file with a dictionary of choice (every 'word' in it must be newline delimited). Pipe it in via `stdin` or provide it's name as a command line argument.

```
a
able
about
above
absence
...

```

**2**. Pick 10 random words from the file (no duplicates must be allowed) and print them out in the following manner:

```
-> direct
-> ground
-> next
-> five
...

```

**3**. Start measuring the time spent from now on!

**4**. Let the user type all of the ten words as fast as possible (ended with a carriage return). Print `OK` when you have a match, print `WRONG` when we have a typing mistake (or the word was already succesfully typed in this run).

**5**. Stop the clocks! Now print the *CPM* (Characters per minute) benchmark, which is calculated as follows: `(sum of the characters of the chosen words / time spent typing (seconds)) * 60`. Round to the nearest integer and reproduce the following (sample) output:

```
--> You have scored 344 CPM!

```

## A sample run

```
-> settle
-> side
-> open
-> minister
-> risk
-> color
-> ship
-> same
-> size
-> sword
settle
OK
side
OK
open
OK
# ...................... some lines snipped ......................
word
WRONG
sword
OK
--> You have scored 298 CPM!

```

## The winner

This is code colf, the shortest entry (in source code character count) wins, have fun!

# Answer
# K, 146

Assumes a dictionary file called 'd' in the current working directory.

```
{b:+/#:'a:10?_0:`:d;-1"-> ",/:a;s:.z.t;while[#a;$[(,/0:0)~*a;[a:1_a;-1"OK"];-1"WRONG"]];-1"--> You have scored ",($(60000*b)%"i"$.z.t-s)," CPM!";}

```
> 5 votes

# Answer
## Bash - 217 212 199 196 chars

Not gonna win but it was fun

```
declare -A W
for w in `shuf -n10`;do C+=$w;echo -\> $w;W[$w]=OK;done
SECONDS=0
for((;${#W[*]};));do read r;echo ${W[$r]-WRONG};unset W[$r];done
echo --\> You have scored $((60*${#C}/SECONDS)) CPM!

```

Under 200 chars now!

Takes wordlist file as an argument Now takes word list on standard input. Paste it in the terminal and press ^D

Implemented suggestion from manatwork
> 11 votes

# Answer
## Ruby (~~189~~ ~~178~~ ~~171~~ 168)

```
$><<t=['',d=[*$<.lines].sample(10)]*'-> '
s=Time.now
puts d.delete($stdin.gets)?:OK:'WRONG'while d[0]
puts'--> You have scored %i CPM!'%((t.size-40)/(Time.now-s)*60)

```

Pretty basic, I'm sure there are improvements to be made. Takes the filename of the dictionary as a command-line argument.

**EDIT**: A few minor tweaks, mainly around retaining the newlines from the dictionary. As a result the file will need a trailing newline to work correctly.
> 4 votes

# Answer
## C, 305 309 347 chars

```
char*stdin,w[11][99];long i,t;main(int n,char**v){v=fopen(v[1],"r");
for(srand(time(&t));fgets(w[i++>9?(n=rand()%i)>10?0:n:i],99,v););
for(i=n=0;i<10;n+=printf("-> %s",w[++i])-4);
for(;i;puts(!strcmp(*w,w[11-i])?--i,"OK":"WRONG"))fgets(*w,99,stdin);
printf("--> You have scored %ld CPM!\n",n*60/(time(0)-t));}

```

Thanks to @ugoren for the improvement hints. Using an "11th word" to discard incoming dictionary entries was a big win over my previous strcpy-if-chosen approach.

Here's the ungolfed source:

```
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

static char words[11][99];
static long i, t;

int main(int argc, char *argv[])
{
    FILE *fp;
    int n;

    fp = fopen(argv[1], "r");
    srand(time(0));
    for (i = 0 ; fgets(words[0], sizeof words[0], fp) ; ++i) {
        n = i < 10 ? i : rand() % i;
        if (n < 10)
            strcpy(words[n + 1], words[0]);
    }
    fclose(fp);

    n = 0;
    for (i = 1 ; i <= 10 ; ++i)
        n += printf("-> %s", words[i]) - 4;
    t = time(0);
    i = 1;
    while (i <= 10 && fgets(words[0], sizeof words[0], stdin)) {
        if (strcmp(words[0], words[i])) {
            puts("WRONG");
        } else {
            puts("OK");
            ++i;
        }
    }
    if (i > 9)
        printf("-> You have scored %ld CPM!\n", n * 60 / (time(0) - t));

    return argc - argc;
}

```
> 4 votes

# Answer
# Scala(319 306 ~~304~~ 302)

```
var s=util.Random.shuffle(io.Source.fromFile(args(0)).getLines.toSet)take 10
def?(a:Any)=println(a)
var l=(0/:s){_+_.size}
s map{"-> "+_}map?
def n=System.nanoTime
val t=n
while(s.size!=0){val m=readLine
if(s contains m)?("OK")else?("WRONG");s-=m}
?("--> You have scored "+l*60000000000L/(n-t)+" CPM!")

```
> 3 votes

# Answer
## C# 401

```
void T(){
Action<string>C=Console.WriteLine;Func<string>R=Console.ReadLine;
var w=new List<string>();
for(var l=R();l!="";l=R())w.Add(l);
var s=w.OrderBy(_=>Guid.NewGuid()).Take(10).ToList();
s.ForEach(x=>C("=> "+x));
var t=s.Select(x=>x.Length).Sum();
var c=Stopwatch.StartNew();
while(s.Any()){C(s.Remove(R())?"OK":"WRONG");}
c.Stop();
C("--> You have scored "+c.Elapsed.TotalSeconds*60/t+" CPM!");}

```

Running version here: http://ideone.com/Nt6Id
> 2 votes

# Answer
## PHP 187 bytes

Newlines have been added for clarity:

```
<?$s=file($argv[1]);
for(shuffle($s);$i++<10;$l+=strlen($$i))echo~ÒÁß,$$i=$s[$i];
for($t=time();$j++<10;)echo$$j==fgets(STDIN)?OK:WRONG,~õ?>
--> You have scored <?=0|$l/(time()-$t)*60?> CPM!

```

Accepts the dictionary filename as a command line argument. The dictionary file must end with a newline.
> 2 votes

# Answer
## Python (~~256~~ 235)

```
import time as t,random as r
def p(x):print x
c=r.sample(input().split("\n"),10)
z=lambda x:p(("WRONG","OK")[raw_input()==x])or len(x)
p("--> "+"\n--> ".join(c))
_=t.time()
p("--> You have scored %d CPM!"%(sum(map(z,c))/(t.time()-_)*60))

```

This is in python 2.x, in 3.x I can shave off 4 more characters by using the print function.

Newlines included
> 2 votes

# Answer
# \[Wolfram Language (Mathematica)\], 212 bytes

```
n=10;Print["-> "<>#]&/@(w=RandomWord@n);c=1;t=First@AbsoluteTiming[While[c<=n,Print@If[Echo@InputString[]==w[[c]],c++;"OK","WRONG"]]];Print["--> You have scored "<>ToString@⌊60Total@StringLength@w/t⌋<>" CPM!"]

```

Interesting challenge for WM.
Works only on desktop!
Using internal dictionary of common words instead of file.
Ungolfed version:

```
num = 10; Print["-> " <> #] & /@ (words = RandomWord@num);
size = Total@StringLength@words;
count = 1;
timing = First@AbsoluteTiming[
    While[count <= num,
     Print[
      If[Echo@InputString[] == words[[count]],
       count++; "OK",
       "WRONG"]
      ]
     ]];
result = ToString@⌊60 size/timing⌋;
Print["--> You have scored " <> result <> " CPM!"]

```
> 0 votes

---
Tags: code-golf
---


# Question
Title: cadaddadadaddddaddddddr - linked list accessing
Create a function (or closest equivalent, or full program) that takes an list of some datatype (your choice) that may be nested and a string (in either order), and generalizes the lisp c\[ad\]+r functions.

> Functions are provided which perform compositions of up to four car and cdr operations. Their names consist of a C, followed by ~~two, three, or four~~any positive number occurrences of A or D, and finally an R. The series of A's and D's in each function's name is chosen to identify the series of `car` and `cdr` operations that is performed by the function. The order in which the A's and D's appear is the inverse of the order in which the corresponding operations are performed.

(source: common lisp hyperspec)

The `car` and `cdr` operations will return the first element and all the other elements, respectively, for the purposes of this challenge. The string will hold the operation you should perform.

## Examples:

```
   Array    ,  Accessor  =>  Result
===================================
     [0,1,2],      'cdr' => [1,2]
 [0,[1,2],3],     'cadr' => [1,2]
 [[[[[0]]]]],   'caaaar' => [0]
          [],      'cdr' => do not need to handle (no cdr)
          [],      'car' => do not need to handle (no car)
    anything, 'cr'/'asd' => do not need to handle (invalid command)
         [0],      'car' => 0
         [0],      'cdr' => []

```

## Reference Implementation

```
{

  const inp = document.getElementById("inp");
  const out = document.getElementById("out");
  inp.onchange = () => {
    const data = JSON.parse(inp.value);
    var list = data.list;
    data.cmd.match(/^c([ad]+)r$/)[1]
      .split("").reverse().forEach(letter =>
        list = letter === "a" ? list[0] : list.slice(1));
    out.value = JSON.stringify(list);
  };
  inp.onchange();

}
```

```
<textarea id="inp" rows="2" cols="50">
{ "cmd": "cadadr",
  "list": [0,[1,[2,3],4],5] }
</textarea>
<br>
<textarea readonly id="out" rows="1" cols="50">
waiting, there seems to be a problem
</textarea>
```

*This is , shortest solution in bytes per language wins.*

# Answer
> 12 votes
# JavaScript (V8), 48 bytes

```
a=>f=b=>b[2]?b[[x,...r]=f(b.slice(1)),1]<f?x:r:a

```

Try it online!

*-2 bytes thanks to @Arnauld!*

# Answer
> 11 votes
# Python 3, ~~68~~ ~~66~~ 54 bytes

```
lambda r,s:eval(s[:0:-1].translate(["[1:]","[0]"]*51))

```

Try it online!

Alt, similar idea (which works in Python 2):

# Python 3, ~~68~~ 66 bytes

```
lambda l,c:eval(l+''.join("[[10:]]"[x<'d'::2]for x in c[-2:0:-1]))

```

Try it online!

Both create an eval string which just appends the desired sequence of subscripts/slices directly to the list, with the first one using the added trick of keeping the "r" as the list name. The first one takes an actual list as input and the second takes a string representation of a list.

Credit to xnor for pointing me at `translate()` and the idea of using `r` as the list name for -12 bytes!

# Answer
> 7 votes
# Jelly, ~~11~~ 9 bytes

```
Oị⁾ḢḊḊṖUv

```

Try it online!

-2 bytes thanks to Unrelated String!

Takes the accessor on the left and the array on the right

```
Oị⁾ḢḊḊṖUv - Main link. Accessor A on left, Array L on right
O         - Convert A to ordinals. Note that 'a' is odd and 'd' is even
 ị⁾ḢḊ     - Index into "ḢḊ". Odd characters yield "Ḣ" and even "Ḋ"
     ḊṖ   - Remove first and last values from A
       U  - Reverse
        v - Evaluate as Jelly code, with L as the argument

```

is the *head* command, which returns the first element of a list.  is the *dequeue* command, which removes the first element of a list. The code executed by `v` is just a series of  and  atoms, which perform one after another.

# Answer
> 6 votes
# Factor, ~~61~~ 57 bytes

```
[ rest reverse rest [ 97 = [ first ] [ rest ] if ] each ]

```

Try it online!

*-4 bytes thanks to @Neil!*

## Explanation:

This is a quotation (anonymous function) that takes two sequences from the data stack and leaves one sequence on the data stack. In Factor, strings are just sequences of unicode code points and can be manipulated like any other sequence.

* Given input `{ 0 { 1 2 } 3 } "cadr"`...
* `rest` take everything but the first element of a sequence `{ 0 { 1 2 } 3 } "adr"`
* `reverse` reverse a sequence `{ 0 { 1 2 } 3 } "rda"`
* `rest` take everything but the first element of a sequence `{ 0 { 1 2 } 3 } "da"`
* `[ ... ] each` for each element in the sequence...
* At the beginning of the first iteration, the data stack looks like this: `{ 0 { 1 2 } 3 } 100`
* `97` push `97` on the data stack `{ 0 { 1 2 } 3 } 100 97`
* `=` test top two objects on the data stack for equality `{ 0 { 1 2 } 3 } f`
* `[ first ] [ rest ] if` run first quotation if TOS is `t`, otherwise run the second `{ { 1 2 } 3 }`
* Now the next iteration of `each` will kick in and put the next command on the data stack `{ { 1 2 } 3 } 97`
* Etc.

# Answer
> 5 votes
# Racket, 86 bytes

```
(λ(a c)(foldr(λ(c a)(case c[(#\a)(car a)][(#\d)(cdr a)][else a]))a(string->list c)))

```

Try it online!

-3 bytes thanks to Wezl
-73 bytes thanks to ASCII-only
-8 bytes thanks to MLavrentyev

Input in the format `(f <data> <string>)`

Of course there has to be a lisp/scheme/racket/whatever answer :P

This is probably pretty bad because it's my first time golfing in Racket. I just know what I was taught in my basic first-year CS courses :P

# Answer
> 4 votes
# Python 3, 86 bytes

```
lambda l,c,a=lambda x:x[0],d=lambda x:x[1:]:eval("(".join(d(c))[:-1]+l+")"*(len(c)-2))

```

Try it online!

-1 byte thanks to @Stephen

# Answer
> 4 votes
# Scala, 60 bytes

```
_.tail.init.:\(_){case(x,m:Seq[_])=>if(x<98)m(0)else m.tail}

```

Try it in Scastie!

I hate nested lists. Because of them, we need a pattern matching function (or casts, which are longer).

```
_                            //The command ("caadddaddaar")
  .tail                      //Drop the 'c'
  .init                      //Drop the 'r'
.:\                          //Fold right the "aadddada"
  (_)                        //Starting with the inputted list
  {                          //Pattern matching function literal
    case (x, m: Seq[_]) =>   //The command is x, the list is m (must be a Seq)
    if (x < 98) m(0)         //If the command is 'a', return the first element
    else m.tail              //Else, drop the first element
  }

```

# Answer
> 4 votes
# , 35 bytes

```
4 :0
".'y',~(}.}:x)rplc;:'a{.d}.'
)

```

Try it online!

Note: -3 off TIO count for `f=:`

* Drop the first and last element from the `c[ad]+r` directive with `}.}:x`, leaving us with a string of `a`s and `d`s.
* Replace every `a` with `{.` and every `d` with `}.`, J's version of car and cdr: `rplc;:'a{.d}.'`
* Append the nested array we want to evaluate `'y',~`.
* And evaluate it `".`.

# Answer
> 3 votes
# JavaScript (V8), ~~77~~ 72 bytes

```
c=>d=>[...c.slice(1)].reverse(d=[d]).map(n=>d=n=="d"?d.slice(1):d[0])&&d

```

Turns out the boring solution wins

# JavaScript (V8), ~~91~~ ~~90~~ ~~87~~ 84 bytes

```
c=>d=>[...c.slice(1)].map(n=>x=>n=="d"?x.slice(1):x[0]).reduceRight((a,f)=>f(a),[d])

```

Can't add a TIO link on school WiFi :/

**Explanation:**

This is a cool approach, using functional stuff. It `slice`s the command name to remove the `c`, splits it into characters, then maps them to functions:

* `d` becomes `x=>x.slice(1)`
* `a` and `r` become `x=>x[0]`

My current approach actually returns one function, which can still access the `n` variable, which saves three bytes. I don't really know how to explain it but it works :p

It then uses `reduceRight` to apply those functions in reverse order, on `[d]`. This saves a byte over my old approach, which also sliced off the `r`.

# Answer
> 3 votes
# Pyth, 17 bytes

```
.v+PtXQ"da""th"\E

```

Test suite

Uses pretty much the same approach as ChartZ Belatedly's Jelly answer.

---

As an aside, this answer could shed 3/4 bytes if Pyth had an 'evaluate with argument' builtin, and an additional 1/2 if it had Jelly's 'transliterate' (Pyth builtins can be one or two bytes). This would put it at 11/12/13 bytes, which *at best* ties the 11 bytes Jelly takes. This is especially impressive since Jelly has to reverse the accessor, while Pyth doesn't (Pyth uses reverse Polish notation).

# Answer
> 3 votes
# Jq, 69 bytes

Takes an object with keys `"c"` for the accessor and `"l"` for the list.

```
reduce((.c/"")[1:-1]|reverse[])as$c(.l;if$c=="d"then.[1:]else.[0]end)

```

## Explanation

```
reduce        $0               as$c($1;             $2              )
  # the accumulator starts at $1. For each $0 (stored as the variable $c),
  # it becomes the result of $2 applied to it.
      ((.c/"")[1:-1]|reverse[])
  # the command (.c), split (/""), with the ends snapped ([1:-1])
  # reversed (reverse), every value inside this array  ([])
                                    .l;if$c=="d"then.[1:]else.[0]end
  # starting with the list (.l), if the character is "d" then the list
  # becomes its tail (.[1:]), otherwise its head (.[0]).

```

Jq play it!

Run test cases

# Answer
> 3 votes
# Japt `-h`, 20 bytes

```
VÔkric)¬£=X¥'a?UÎ:UÅ

```

Try it

* saved 2 thanks to @Shaggy

```
    1st input U = data
    2nd input V = command

    VÔk"cr" - reverse and remove 'cr'
    £ ... Ã - pass each remaining letters to :
    =         - reassign 1st input(U)
    X¥'a?UÎ   - 1st item if 'a'
    :UÅÃ      - else the rest
    -h flag to output result

```

# Answer
> 2 votes
# Stax, 10 bytes

```
Ç≈≡ø*fáì☺○

```

Run and debug it

Returns a string of codepoints if array, and number if it's a number. The code can be verified here: Try it

## Explanation

```
"ahdD"|trDl
"ahdD"|t    translate 'a' to 'h' and 'd'  to 'D'
        r   reverse
         D  delete first element
          l eval

checking code:
cc|4{|u}a?
cc         dup twice
  |4     ? if it's an array:
    {|u}   convert to JSON
        a  otherwise leave as is

```

# Answer
> 2 votes
# Charcoal, 20 bytes

```
Ｆ⮌η≡ιa≔§θ⁰θd≔ΦθλθcＩθ

```

Try it online! Link is to verbose version of code. Outputs using Charcoal's default format, which is each array element on its own line and each subarray double-spaced from the next (+1 byte to output in Python `str` format). Explanation:

```
Ｆ⮌η≡ι

```

Loop over the command characters in reverse order and switch on them.

```
a≔§θ⁰θ

```

For `a` replace the input with its first element.

```
d≔Φθλθ

```

For `d` filter the first element from the input.

```
cＩθ

```

For `c` print the result.

# Answer
> 2 votes
# Retina 0.8.2, 73 bytes

```
+`(a|(d))r.(((\[)|(?<-5>])|\d|(?(5),))+),?(?(2)(?<3>.*)|.*)
r$#2$*[$3
cr

```

Try it online! Link includes test cases. Explanation:

```
+`

```

Repeat until a match cannot be made.

```
(a|(d))r.(((\[)|(?<-5>])|\d|(?(5),))+),?(?(2)(?<3>.*)|.*)

```

Match either an `a` or `d` (remembering which), then an implied `[`, then a sequence of `[`s, `]`s, `,`s and digits, except no more `]`s than `[`s and only matching `,`s between `[`s and `]`s, then an optional `,`, then if it was a `d` that matched then replace the match of the first term with the tail of the list otherwise just delete the tail.

```
r$#2$*[$3

```

Keep the `r`, re-insert the `[` if the `d` was matched, and insert the first term or tail as matched above.

```
cr

```

Finally delete the remaining `cr`.

# Answer
> 2 votes
# Lua, 100 bytes

```
load[[t,c=...c:reverse():gsub('[ad]',load"if...=='a'then t=t[1]else table.remove(t,1)end")return t]]

```

Try it online!

Function that accepts a nested table structure and a string. I sure would be impressed to see this golfed further. Please note that original table structure *will* be modified when using `d` command, so don't pass it there if it have value to you (or, better yet, never use this code outside of TIO sandbox).

TIO link also includes a test suite.

# Answer
> 2 votes
# Common Lisp, ~~106~~ 104 bytes

```
(lambda(a c)(reduce(lambda(a c)(if(eq c #\a)(car a)(if(eq c #\d)(cdr a)a)))(reverse c):initial-value a))

```

Try it online!

Direct port of the racket answer.

# Answer
> 2 votes
# Vyxal, 17 bytes

```
£ḢṪṘƛ\a=[&h|&Ḣ];¥

```

Try it Online!

A mess :P

# Answer
> 1 votes
# Python 3, ~~80~~ ~~79~~ 75 bytes

```
f=lambda s,x:eval(['%s[1:]','%s[0]','x#%s','%s'][ord(s[0])%4]%'f(s[1:],x)')

```

Try it online!

By sheer luck, `ord(s[0])%4` is able to distinguish between `a`, `c`, `d`, `r`.

# Answer
> 1 votes
# Vyxal, 71 bitsv2, 8.875 bytes

```
ḢṪṘ(₍ḢhnAi

```

Try it Online!

## Explained

```
ḢṪṘ(₍ḢhnAi
ḢṪ         # Remove the c and r from the input
  Ṙ        # and reverse it
   (       # for each char
    ₍Ḣh    #   [top_of_stack[1:], top_of_stack[0]]
         i #   indexed by
       nA  #   is char a vowel?

```

---
Tags: code-golf, array, subsequence, lisp, ragged-list
---


title: Iterative Quine

text:
# Question
Title: Iterative Quine
Create a program which prints itself, followed by an additional program. This additional program should print the first program, itself, and then a third program. This continues until the nth program, which prints every program in order up to itself, but fails to print a successor.

All programs output by your code should be delimited in the same way across all iterations.

## Example:

Program 1

```
Print(Me,MyEvilTwin)

```

Prints

```
Print(Me,MyEvilTwin)

Print(Me,MyEvilTwin,MyEvilTwin'sEvilTwin)

```

The generated program 2

```
Print(Me,MyEvilTwin,MyEvilTwin'sEvilTwin)

```

Prints

```
Print(Me,MyEvilTwin)

Print(Me,MyEvilTwin,MyEvilTwin'sEvilTwin)

Print(Me,MyEvilTwin,MyEvilTwin'sEvilTwin), And How!

```

The final generated program 3,

```
Print(Me,MyEvilTwin,MyEvilTwin'sEvilTwin), And How!

```

Prints

```
Print(Me,MyEvilTwin)

Print(Me,MyEvilTwin,MyEvilTwin'sEvilTwin)

Print(Me,MyEvilTwin,MyEvilTwin'sEvilTwin), And How!

```

Which fails to include a 4th program, making this 3 iterations.

### Scoring

Your score is the number of iterations your program achieves before failing to print a successor. If no iteration of your program fails to print a successor, your score is infinity. For programs with the same number of iterations, shortest code wins.

# Answer
> 4 votes
# Vyxal `D`, Infinite score, 25 bytes

```
`:L$ȧ$17-ʁ꘍(nq\`:Ė\`+,`:Ė

```

Try it Online!

While creating this, I discovered that Vyxal is not very good at most things involving eval. It adds a space before the last backtick each time.

Note: The `D` flag is to allow non-ASCII characters in strings, and is necessary for this to work.

```
`                     `:Ė # Execute using self as argument...
 :L                       # Duplicate and get length
   $ȧ$                    # Remove whitespace from the other copy
      17-ʁ                # 0...n-17
          ꘍               # (For each of that range) append that many spaces to the string
           (n             # Map... (Proper map is buggy)
             q            # Uneval
              \`:Ė\`+     # Append ':Ė' to make quinish
                     ,    # Print

```

# Answer
> 8 votes
# Stacked, \\$N\\$ iterations

```
1:>:#',N take[1 + tostr ':>:#'',N take' + f tostr ':@f map' + + out]:@f map

```

Try it online!

\\$N\\$ appears twice in the code. Linked is the example for \\$N=9999\\$, but this theoretically works for any number \\$N\\$. The only change from each iteration is the number at the beginning, which is incremented with each iteration. We map a quine writing function over the range `K:>`, that is, the numbers from `0` to `K-1` inclusive.

The length of the initial code is \\$74+2D\\$, where \\$D\\$ is the number of digits in the chosen \\$N\\$; that is, \\$76+2\lfloor\log\_{10} N\rfloor\\$. Again for the example \\$N=9999\\$, the code length is 82.

Better solutions will either decrease the boilerplate or the number of instances of \\$N\\$.

# Answer
> 4 votes
# ECMAScript 6, Infinite score, 58 bytes

```
($=n=>{for(i=0;i<n+2;)console.log(`($=${$})(${i++})`)})(0)

```

Try online

Based on this quine: https://twitter.com/cowboy/status/232587756486938624, I only added a counter and switched it to ECMAScript 6

# Answer
> 3 votes
# Pari/GP, Infinite score, 47 bytes

PARI/GP uses arbitrary-precision integers by default.

```
(f=(n)->for(i=0,n+1,print("(f="f")("i")")))(0)

```

Try it online!

# Answer
> 3 votes
# , infinite score, 105 bytes

```
1 ->x;while(F<=x)cat(F<-F+1,sprintf(a<-"->x;while(F<=x)cat(F<-F+1,sprintf(a<-%s,dQuote(a)))
",dQuote(a)))

```

Try it online!

Proper Quine that encodes itself and does not access its own source code.

Outputted programs are delimited by a newline character (which also occurs once in the program itself). Add 8 bytes to delimit output with a double newline, which does not occur in the program itself.

# Answer
> 3 votes
# Python 2, infinite score, 48 bytes

```
s="c=2;print's=%r;exec s*'%s,c;c+=1;c";exec s* 2

```

Try it online!

# Python 3, infinite score, 53 bytes

```
s="c=2;print(f's=%r;exec(s*{c})'%s);c+=1;c";exec(s*2)

```

Try it online!

# Answer
> 3 votes
## Ruby, infinite, 59 bytes

**Updated:**

```
eval$a=%q[2.times{|i|puts"eval$a=%q[#{i+2}#{$a[-46..]}]"}]

```

**Previous (66 bytes):**

```
eval$a=%q[2.times{|i|puts"eval$a=%q[#{$a.sub /^\d+/,"#{i+2}"}]"}]

```

# Answer
> 1 votes
# Julia 1.0, infinite score, 69 bytes

```
(c=1;a=:(println.("(c=$(i);a=:($(a)))|>eval" for i = 1:c + 1)))|>eval

```

Try it online!

---
Tags: code-challenge, quine, code-generation
---


title: Duck, duck, goose!

text:
# Question
Title: Duck, duck, goose!
Remember the kids game, 'Duck, Duck, Goose'? No? Me neither.

### The challenge

* Print the word 'duck' on individual lines an indeterminate amount of times.
* Print the word 'goose'.
* Your program ends.

### The rules

* Attempt to play the game in the fewest bytes.
* There must be at least one duck.
* There must be exactly one goose, at the end of the list.
* There must be exactly one bird on each line. No empty lines.
* The case of the outputted strings is irrelevant.
* White-space within a line is fine.
* Your program must finish.
* Your program must not consistently produce the same number of ducks.

Have fun!

---

Please note: This question is not a duplicate of Shortest code to produce non-deterministic output

Reasons include:

* The association to a childrens' game
* The defined start and end requirements of the result string. There is no specified output in the other challenge.
* Answers For the other, non-duplicate challenge are in a single-digit number of bytes. The average for this one is around 30, or there about.
* By the amount of overlap between this challenge and that one, any code-golf question including the 'random' tag is a duplicate. Should we delete them all?
* The code answers for this challenge would match the other challenge (in a ridiculously bloated way), but the answers to that challenge would not match this one.

# Answer
> 9 votes
# Jelly, 13 bytes

```
2X“¢;ÆS»ẋ“ʋ¢»

```

Try it online!

Explanation:

```
2X“¢;ÆS»ẋ“ʋ¢»

2X             Random number (1 or 2)
  “¢;ÆS»       Compressed string equivalent to "duck\n"
        ẋ      Repeat the "duck\n" that random number of times
         “ʋ¢»  Compresses string equivalent to "goose"
               Implicitly concatenated and returned

```

---

More readable version: Try it online!

Will always return 1 or 2 ducks.

# Answer
> 48 votes
# Operation Flashpoint scripting language, 48 bytes

```
f={s="duck\n";s+([s,""]select random 1)+"goose"}

```

Always prints either one or two ducks.

`random 1` returns a (floating point) number between 0 and 1. That number is passed as an argument to `select` along with the array `[s,""]`. The random number is then rounded to the nearest integer (either 0 or 1), and the array element at that index is selected from the array.

**Call with:**

```
hint call f

```

**Output:**

**Alternative 56 bytes version:**

```
f={s="duck\n";format[s+"%1goose",[s,""]select random 1]}

```

# Answer
> 42 votes
## World of Warcraft 81 Bytes

Here's a macro that you can run in World of Warcraft.

```
/run for x=1,random(1,9) do SendChatMessage("Duck") end; SendChatMessage("Goose")

```

# Answer
> 42 votes
# Minecraft \<1.13, ~~72~~ 54 bytes

Sorry, I had to.

## Instructions:

* Create a new Minecraft world in Creative Mode
* Find the save folder for that world, and place the following code in `data/functions/minecraft/ddg.mcfunction`
* Run `/function ddg` in the game console

## How it works:

Outputs the word "duck" for every entity in the world, then outputs the word "goose". Since entities are constantly spawning and despawning, the number of "duck"s will not be consistent. I used `tellraw` instead of the much shorter `say` because `say` outputs the name of the entity, while `tellraw` outputs exactly what it is told.

```
execute @e ~ ~ ~ tellraw @a "duck"
tellraw @a "goose"

```

## Screenshot

Edit: Changed {"text":"duck"} to just "duck" (and the same with "goose")

# Answer
> 17 votes
# JavaScript, ~~45~~ ~~44~~ ~~42~~ ~~39~~ 37 bytes

Has the potential to produce an overflow error.

```
f=_=>`duck
${new Date%2?f():`goose`}`

```

---

## Test it

```
o.innerText=(
f=_=>`duck
${new Date%2?f():`goose`}`
)()
```

```
<pre id=o></pre>
```

# Answer
> 14 votes
# Octave, ~~38~~ 33 bytes

This is not the shortest (it's 36 bytes), but it's my favorite. The explanation is in the bottom.

```
disp(['duck '+~(1:1/rand)';'goose'])

```

Try it online!

---

Some shorter variations:

This works in principle (33 bytes), but the online interpreters times out:

```
disp(['duck '+~(1:now)';'goose'])

```

Adding some bytes to make the output shorter makes it 35 or 36 bytes:

```
disp(['duck '+~(7e5:now)';'goose'])   % Works on octave-online.net
disp(['duck '+~(7.3e5:now)';'goose']) % Works on tio.run

```

### Explanation:

I'll just explain the last random one. The others are similar, but uses the number of days since **January 1st, 0000** until today.

`rand` returns a random number on the interval **(0, 1)**. Thus, `1/rand` returns a number larger than **1**. Since a range `1:f`, where `f` is a random float larger than **1** is identical to `1:floor(f)`, `1:1/rand` creates a range **1 .. x**, where **x \>= 1**.

I'll try to explain this as if Octave was a stack based language.

```
      'duck '                           % Push the string 'duck ' to the stack
               (1:1/rand)               % Push a vector 1... floor(1/rand)
              ~(1:1/rand)'              % Negate the vector (making it all zeros)
                                        % and transpose it.
             +                          % Add 'duck ' with the vertical vector of zeros
                                        % to implicitly duplicate the string r times
     [                    ;'goose']     % Push the string 'goose' and concatenate
                                        % vertically with the rest
disp(                              )    % Display it all.

```

# Answer
> 14 votes
# Z Shell (+ wget & Netpbm), ~~168~~ ~~160~~ ~~150~~ ~~148~~ ~~145~~ ~~135~~ 120 bytes

```
d(){wget -O- bit.ly/$1|jpegtopnm|pamscale -w 64 -h 64};d DckDkGo|pnmtile 64 $[(RANDOM&7+1)*64]|pnmcat -tb - <(d g005eGG)

```

Not the shortest solution, but I felt like giving a twist of sorts to this challenge (inspired by @AlexG's solution to this other problem).

This script generates a PPM image containing between 1-8 pictures of ducks and a picture of a goose at the bottom on standard output. It downloads the two source pictures from Wikipedia, so internet access is necessary for it to work.

Sample output converted to JPEG through *pnmtojpeg*:

# Answer
> 13 votes
# Python 2, 36 34 bytes

```
print"duck\n"*((id(id)%5)+1),"goose"

```

Try It Online!

Suggestion by Kevin Cruijssen gets us to 34 bytes:

```
print"duck\n"*-~(id(id)%5),"goose"

```

# Answer
> 12 votes
# Perl 5, 20 bytes

First a practical 26 bytes:

Ducks 1 to 9 times before being goosed.

```
say"Duck
"x(1+$^T%9),Goose

```

Try it online!

But if you have lots of memory and time this 20 byte version (as suggested by Chris) works too:

```
say"Duck
"x$^T,Goose

```

This also assumes the Year 2038 Problem will be solved for Perl 5, otherwise it will be invalid for 1 second 20 years hence.

# Answer
> 11 votes
# Bash, 39 38 37 bytes

```
sed s/[0-9]/duck\\n/g<<<$RANDOM\goose

```

Try it online!

Prints a number of ducks equal to the number of digits in an integer uniformly distributed on \[0,32767\] (so, more often than not, five ducks (a good number of ducks)).

-1 byte each thanks to @Chris and @sch pointing out pairs of quotes that weren't pulling their weight.

# Answer
> 10 votes
# , 35 bytes

```
cat(rep("duck
",rexp(1)+1),"goose")

```

Try it online!

`rexp()` produces a random number from an exponential decay function. `+1` to ensure at least one duck. All lines after the first include a leading space (which is the default separator for `cat`) but this is allowed.

# Answer
> 10 votes
# Pure Bash (no external utilities), 25

Based on @SophiaLechner's answer, this also prints *a good number of ducks*.

@OlivierDulac's idea to use the script shell PID as stored in the `$` parameter saves 5 bytes.

```
echo "${$//?/duck
}"goose

```

Try it online.

# Answer
> 9 votes
# Bash + Coreutils, ~~36~~ 27 bytes

```
yes duck|sed $$q;echo goose

```

Prints too many ducks (between 2 and `cat /proc/sys/kernel/pid_max`), then one goose.

Saved nine bytes thanks to Digital Trauma and Olivier Dulac.

Try it online! (but keep in mind that it may get truncated occasionally)

Same length, but with no `echo`:

```
yes duck|sed $${agoose'
q}'

```

Try it online!

`a` is the append command in `sed`, and `q` quits. Both only run on the line `$$`, which corresponds to the PID.

# Answer
> 9 votes
# Ruby, 30 bytes

```
puts"duck
"*rand(1..9)+"goose"

```

Try it online!

Note: really 31 bytes without the `\n` cheat.

# Answer
> 8 votes
# PowerShell, ~~35~~ ~~30~~ 28 bytes

```
,"duck"*((Random)+1)
"goose"

```

Try it online! (modified version)

Generates an array of `Get-Random` number of items. It might take a while. This adds a `+1` to ensure we get at least one `duck`. The modified version also includes a `-ma`ximum flag of `5` so you can see the program works as expected (the modified version will print 1, 2, 3, or 4 `duck`s before the `goose`).

The array and the solitary `goose` string is left on the pipeline, and the implicit `Write-Output` gives us newline-separated values for free.

You don't know how difficult it was for me to not change the last line to "gray duck" ...

# Answer
> 7 votes
# Python 2, 54 bytes

```
from random import*
print"duck\n"*randint(1,9)+"goose"

```

**Try It Online!**

# Answer
> 6 votes
# Brachylog, ~~24~~ 21 bytes

-3 bytes thanks to Erik the Outgolfer

```
"duck"ẉ4ṙ0∧"goose"w∨↰

```

Try it online!

In celebration of the Language of the month, my first brachylog post. The control flow in this language is cool.

How it works:

```
"duck"ẉ4ṙ0∧"goose"w∨↰
"duck"ẉ                 print duck with a new line
       4ṙ               choose a random number in the range is [0, 4]
         0              verify it equals zero
          ∧             and (short circuits)
           "goose"w     print goose without a newline
                   ∨    or (if it did not equal zero)
                    ↰   repeat the procedure

```

# Answer
> 6 votes
# C# (Visual C# Interactive Compiler), 55 bytes

```
Write("{"+new Random().Next(2)+"}{0}goose","duck\n","")

```

Try it online!

# Answer
> 6 votes
## Geometry Dash World 2.2 Editor \- 4 objects

**Explanation:**

The BG trigger is the current 2.2's random trigger, so it either toggles the Group ID 1 or 2.

The first "DUCK" has a group id of 1, which makes it have a 50% chance of being removed or not (toggled).

There is no object with the Group ID 2 in this level, so there is a 50% chance of 2 "DUCK"s being displayed.

**How to Reproduce this:**

The first "DUCK" has a Group ID of 1.

Goose and 2nd duck don't have a Group ID

Inside the random trigger.

# Answer
> 5 votes
# 05AB1E, ~~15~~ 14 bytes

```
'Ðœ₁Ωи`.•zíΘ•»

```

Try it online!

Will print 2, 5 or 6 ducks and then goose.

-1 byte thanks to @Emigna using ' for a single compressed word (duck)

# Answer
> 5 votes
# APL (Dyalog), 22 bytes

*1 byte saved thanks to @EriktheOutgolfer*

```
'Goose'⍪⍨(?9)5⍴'Duck '

```

Try it online!

# Answer
> 5 votes
# \>\<\>, ~~31~~ 22 bytes

```
"duck"a>x
r"esoog"<>o<

```

Try it online!

-9 bytes based on Not a tree's revision

# Answer
> 5 votes
## Retina, 17 bytes

```
?\\K`duck
K`goose

```

Try it online!

Try it online!

Prints 1 or 2 ducks, with equal probability.

### Explanation

```
?\\K`duck

```

Set the working string to `duck` and print it with a trailing linefeed (`\`). Then this is wrapped in another output stage, but this one has the random flag (`?`) applied to it, so it only prints with a probability of 50%.

```
K`goose

```

Replace the `duck` with `goose`, which is printed implicitly at the end of the program.

Here's a fun alternative which prints 1 duck with 50% probability, 2 ducks with 25%, 3 ducks with 12.5%...:

```
\K`duck
?+\G`
K`goose

```

# Answer
> 5 votes
# Vim (script) on Linux, ~~46~~ 43 bytes (~~49~~ 46 with `:` at start of line)

```
.!date +0\%N\%s6
s/6.*/goose
s/\d/duck\r/g

```

Executed as `vim -S filename` or pasted into running `vim` with `:` before each line.

# Answer
> 5 votes
# Befunge 98, ~~38~~ ~~30~~ 25 bytes

```
"esooG"v>:#,_@
"Duck"a<?<

```

Try it online!

* Thanks @JoKing for stripping the useless trampoline
* Switching to Befunge 98 for shorter new line - now `Duck` fits within a single string

# Answer
> 5 votes
# T-SQL, ~~70 44~~ 43 bytes (Many ducks)

```
while rand()<.9print'duck'print'duck
goose'

```

Thanks @Zac Faragher!

## Revised Version, ~~54 43~~ 40 bytes (1 or 2 ducks)

Thanks @BradC!

```
if rand()<.5print'duck'print'duck
goose'

```

I can't seem to get this to run properly in SQL Fiddle, but it works just fine in LINQPad and SSMS.

Not sure if this is a known limitation of SQL Fiddle or I'm just doing something wrong

# Answer
> 5 votes
# Powershell - ~~31~~ 30 bytes

**Warning**: You're most likely going to end up with a lot of ducks. `Random` includes the values of 0 to `Int32.MaxValue` so, depending on how random you're number is, this could be a lot of quacking.

```
1..(Random)|%{"Duck"};"Goose"

```

# Answer
> 4 votes
# Fission, ~~24~~ 19 bytes

```
R"duck"N#
"goose"*[

```

Try it online!

-5 bytes thanks to Martin Ender

# Answer
> 4 votes
## Javascript ~~79~~ ~~69~~ ~~62~~ 60 bytes

*-10 bits thanks to @Herman Lauenstein*

*-7 bits thanks to @binarymax*

*-2 bits thanks to @Shaggy*

```
_=>{for(_=0;_++<=new Date%9;)(l=console.log)`Duck`;l`goose`}

```

```
a=_=>{for(_=0;_++<=new Date%9;)(l=console.log)`Duck`;l`goose`}
a()
```

# Answer
> 4 votes
# Befunge

~~57~~ 35 bytes (perimeter of the entire field is ~~19x3~~ 17x2 charachters) Thanks to karhell for the improvement.

```
55+"kcud",,,,,#v?
  @,,,,,"goose"<

```

The second line puts duck and a newline on the stack (backwards) and outputs it as a string. After that 75% chance of going back to the start and printing duck again, 25% (when question mark decides to go down) to print goose and stop.

# Answer
> 4 votes
# Brachylog, 21 bytes

```
1ṙ+₁;"Duck
"j₍,"Goose

```

Try it online!

Hey, language of the month going inactive, let's kick things up a little!

# Answer
> 4 votes
# Minecraft Functions (18w11a, 1.13 snapshots), ~~402~~ 382 bytes

Uses three functions in the `minecraft` namespace

a:

```
scoreboard objectives add r custom:play_one_minute
scoreboard objectives add t dummy
scoreboard objectives add x dummy
scoreboard players set @s t 9
scoreboard players operation @s x = @s r
scoreboard players operation @s x %= @s t
function b

```

b:

```
execute if score @s x = @s t run say Goose
execute unless score @s x = @s t run function c

```

c:

```
say Duck
scoreboard players add @s x 1
function b

```

Datapack with the functions

-20 bytes by removing unnecessary namespaces

# Explanation

Function `a` creates three scoreboard objectives (variables). Objectives with the criteria `dummy` are like conventional variables, however, `r` has the criteria `custom:play_one_minute`. This means it will increase each in game minute. By using modulus it becomes a pseudorandom number between 0 and 9. The `t` objective is used because there is no way to do math with literal values, so we need a "constant" objective.

The function `b` is the main loop, calling the `c` function until the counter objective `x` is equal to 9 at which point it prints "Goose".

The `c` function prints "Duck", increments the counter objective and then calls the `b` function again

# Answer
> 3 votes
# , 45 bytes

```
while({cat("duck
");rt(1,1)>0})0;cat('goose')

```

Try it online!

Outgolfed by @user2390246

Prints a single `duck`, then with probability `1/2`, prints another duck and repeats, or prints `goose` and terminates.

This could also be without the `>0` part, since the Student's `t`-distribution might eventually return a `0` but that is highly improbable, so I prefer this.

# Answer
> 3 votes
# SmileBASIC, ~~31~~ 25 bytes

```
?"duck
EXEC!RND(9)?"goose

```

Has a 1/9 chance of ending after each iteration.

## Explanation:

```
PRINT "duck"
EXEC !RND(9)
PRINT "goose"

```

SmileBasic has 4 "slots" that you can run code in. Normally programs run in slot 0, but you can load things like libraries into the others. `EXEC <slot>` is used to run code in a different slot.

`RND(9)` generates a random number from 0 to 8. If this is 0, `!RND(9)` is 1, otherwise it's 0.

`EXEC 0` will run the current slot from the beginning (creating a loop), but `EXEC 1` runs slot 1 (which is empty)

After running slot 1, execution returns to slot 0, and the program prints "goose" and ends.

# Answer
> 3 votes
# DOS .BAT, 54 Bytes

```
@for /l %%d in (0,9,%random%)do @echo duck
@echo goose

```

# 43 Bytes

```
[main.bat]
  @0&echo goose
[0.bat]
  @echo duck&%random% 2>nul

```

# Answer
> 3 votes
# Python 3, 52 bytes

prints `1` to `256` ducks.

```
import os
print("duck\n"*-~os.urandom(1)[0]+"goose")

```

Try it online!

# Answer
> 3 votes
# Japt, ~~18~~ ~~17~~ 16 bytes

Prints 1 or 2 ducks

```
`goo `i`Ýõ
`pM¬Ä

```

Try it online!

Saved 1 byte thanks to Shaggy & 1 byte thanks to Oliver

### Explanation

```
`goo `     // compressed string "goose"
      i    // prepend string
       `Ýõ // compressed string "duck\n"
`          // ...
 p         // repeat n times
  M¬       // random int 0 or 1
    Ä      // add 1

```

# Answer
> 3 votes
# Dirty, 20 bytes

*Warning: May produce up to 2^63 "duck"s*

```
#.⇖('duck'‼)'goose'‼

```

Try it online!

**Explained:**

```
#.⇖       generate a range up to a random number, put into left stack
('duck'‼) while left stack isn't empty, print "duck" and a newline
'goose'‼  print "goose" and a newline

```

# Answer
> 3 votes
# Vim + `date`, ~~33~~ 29 bytes

```
:r!date +1\%SO␊D@"duck␛ogoose

```

Prints 100 to 159 ducks

## Explanation

```
:r!date +1\%SO␊        Get the current date in seconds, prepend it with and postpend an O
D@"aduck␛             Take the current line, cut it and use as code to insert duck the
                       specified amount of times
ogoose                 insert goose

```

# Answer
> 3 votes
# PHP, 35 bytes

```
duck
<?=time()%2?'duck
':''?>
goose

```

Or rand() if you prefer.

Try it online!

# Answer
> 3 votes
# Julia 0.6, 33 bytes

```
print("duck\n"^rand(1:9),"goose")

```

This will print `duck` up to 9 times before `goose`!

Try it online!

# Answer
> 3 votes
# F#, 74 bytes

```
let c=System.Random().Next()
for i=0 to c do
 printfn"duck"
printfn"goose"

```

Try it online! \- but note that the sample is limited to at most 20 ducks.

Setting i=0 means that if c is 0, then at least one "duck" will still be printed.

# Answer
> 3 votes
# T-SQL, 44 bytes

```
a:PRINT'duck'IF RAND()<.5GOTO a PRINT'goose'

```

Different method than Alex' excellent answer.

# Answer
> 3 votes
# *Pure* Bash, ~~41~~ 37 bytes

```
printf %s\\n ${RANDOM//[0-9]/duck } goose

```

This uses the same trick as in Sophia Lechner's answer to obtain a random number in the range 0-32767 with `$RANDOM` but does not require `sed` or *any* other external utilities to be installed to transform it into the desired result.

The Bash parameter expansion `${variable//pattern/replacement}` obtains the value of `variable` with any match on `pattern` replaced by `replacement`. The shell then expands and tokenizes the arguments to `printf`, which applies the format string to each resulting argument.

I'm not a good golfer. Digital Trauma's answer has a much more lenient `pattern` which gets me down to 37 bytes.

```
printf %s\\n ${RANDOM//?/duck } goose

```

Try it online!

# Answer
> 3 votes
# PHP, 36 bytes:

```
<?do{?>duck
<?}while(date(s))?>goose

```

Run with `-n` (no config file)

# Answer
> 3 votes
# **Forth, 91 BYTES**

```
: DUCKDUCKGOOSE BEGIN 0 100 RANDOM 0 = IF ." GOOSE " LEAVE ELSE ." DUCK " THEN CR UNTIL ;

```

\**OUTPUT: \**

```
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
DUCK
GOOSE  ok....

```

# Answer
> 3 votes
# Befunge-93, 23 bytes

```
25*"kcud"#@,,,,,"goose?

```

Try it online!

Starts by printing "duck\n". The only way to generate randomness is with the `?` instruction, which sets the PC's direction to one of the 4 possible directions, chosen at random. Up/down will wrap around vertically right back to the `?` instruction, right will wrap around and print "duck\n" again, and left will print "goose" and terminate the program. The worst-case runtime is infinite, but the probability of the program exiting is 1.

With this code layout, we can reuse `,,,,,` to print either string - luckily they are both of length 5. We can also omit the `"` after `goose`, which makes the stack leak with stringified code, but otherwise leaves it in a workable state, and all of the letters from the strings are practically no-ops when executed as code.

# Answer
> 2 votes
# Python 2, 65 bytes

```
from random import*
while random():print"duck"
print"duck\ngoose"

```

Try it online!

-6 bytes thanks to Rod

theoretically finishes. practically will probably never finish but eventually `random.random()` will spit out a 0

# Answer
> 2 votes
# C (gcc), ~~66~~ ~~65~~ ~~53~~ 50 bytes

```
main(){for(;puts("duck")&time(0););puts("goose");}

```

Try it online!

# Answer
> 2 votes
# Python 2, 54 bytes

<sup>Turns out thecoder16 ninja'd this Python 2 version...</sup>

```
from random import*
print"duck\n"*randint(1,9)+"goose"

```

Prints 1-9 `duck`s then a `goose`.

**Try it online!**

---

Originally...

Python 3,  ~~61~~  56 bytes

```
from random import*
print("duck\n"*randint(1,9)+"goose")

```

Try it online!

# Answer
> 2 votes
# FORTRAN 77, ~~121~~ 120 bytes

```
      PROGRAM D
      CALL RANDOM_NUMBER(A)
      DO1WHILE I=1,A*9+1
1     PRINT*,'DUCK'
      PRINT*,'GOOSE'
      END

```

Prints up to ~~ten~~ nine ducks (thanks AdmBorkBork!).

Unfortunately, there is no syntax highlighting for Fortran. I can't understand why, since it is so popular and useful!

(Saved 11 bytes changing the Do-While syntax. Oh, such versatility!)

This program could have 92 bytes changing all the spaces in the indentation for tabs; it works using compiler `gfortran`, but I'm not sure it would work in older compilers. Since *original* FORTRAN 77 only accept spaces (because the punched card thing), I decided to not use tabs. Anyway, thanks Pavel for the suggestion!

---

# FORTRAN 77, 132 bytes

```
      PROGRAM D
      CALL RANDOM_NUMBER(A)
      DO 1,I=1,A*10+1
      PRINT*,'DUCK'
1     CONTINUE
      PRINT*,'GOOSE'
      END

```

# Answer
> 2 votes
I don't have the rep to comment on the other PowerShell answer, so I have to post it separately:

# PowerShell, 36 bytes

```
,'duck'*(random -mi 1 -ma 9);'goose'

```

Try it online!

My answer is longer, because the maximum flag is required. Omitting it often leads to an OutOfMemoryException: Array dimensions exceeded supported range. In this case the program does not output anything besides the error.

# Answer
> 2 votes
# Java 8, ~~83~~ ~~82~~ ~~72~~ ~~68~~ ~~51~~ 47 bytes

```
v->(Math.random()<.5?"duck\n":"")+"duck\ngoose"

```

Returns either one or two `"duck"` before `"goose"`.

-1 byte thanks to *@l4m2*.
-4 bytes thanks to *@someone*.

**Explanation:**

Try it online.

```
v->                   // Method with empty unused parameter and String return-type
  (Math.random()<.5?  //  If the random boolean is true:
    "duck\n"          //   Return a "duck" + new-line
   :                  //  Else:
    "")               //   Return nothing
   +"duck\ngoose";    //  Appended with a "duck", new-line and "goose"

```

# Answer
> 2 votes
# **Golfscript, 22 bytes**

```
9rand)"duck\n"*"goose"

```

# Answer
> 2 votes
My name has never been more relevant.

**PHP, 40 bytes**

```
<?=str_repeat("duck\n",date("h"))?>goose

```

Only trick used is `date("h")` to generate a random number that will never be 0.

# Answer
> 2 votes
# PowerShell, 57 bytes

```
$r=Random @(1..9)
for($x=0;$x -lt $r;$x++){"Duck"}"Goose"

```

While $x is less than the value of $r, write "duck", else write "goose".

First code golf I've done. Had fun with the challenge, and am looking forward to getting better!

# Answer
> 2 votes
# CJam, 17 bytes

```
es"duck
"*"goose"

```

Prints around 10^12 ducks. `es` is the builtin for Unix timestamp.

For two more bytes, a version with more reasonable output:

```
9mr)"duck
"*"goose"

```

# Answer
> 2 votes
## Groovy, 42 bytes

```
print'duck\n'*(1+Math.random()*10)+'goose'

```

Try it online!

# Answer
> 2 votes
# Excel, 33 bytes

```
=REPT("duck
",9*RAND()+1)&"goose"

```

Prints `duck` between 1 and 10 times, followed by `goose`.

# Answer
> 2 votes
# T-SQL, 43 bytes

```
PRINT REPLICATE('duck
',RAND()*5+1)+'goose'

```

# Answer
> 2 votes
# Assembly (nasm, x64, Linux), ~~79~~ 55 bytes

```
global main

main:
  rdrand ecx
  jnc main
.ducks:
  mov al, 1      ; Move the syscall id into ral. Doing it using a single byte is shorter
  mov edi, eax   ; Copy the value over, which takes exactly 2 bytes.
  xor esi, esi   ; \
  or rsi, duckD  ; Move a pointer to duckD into rsi. This is shorter than the equivalent move.
  mov dl, 5      ; Move the size of the string into rdl.
  push rcx       ; Preserve rcx for use by the loop instruction
  syscall        ; Call the syscall. in this case, syscall write to file descriptor 1, aka stdout.
  pop rcx        ; Restore rcx
  loop .ducks    ; Decrement rcx and jmp back to .ducks if rcx isn't 0
  mov al, 1
  mov edi, eax
  xor esi, esi
  or rsi, gooseD
  mov dl, 6
  syscall
  ret
duckD: db 'duck', 10, 0
gooseD: db 'goose', 10, 0

```

Try it online!

A simple explanation of syscall write is sitting here. Mostly for me, because I forget it exists sometimes.

WARNING: May print up to 2^32 ducks

# Answer
> 2 votes
# Ahead, 30 bytes

There is a 25% chance after each `duck` that the loop will be broken and `goose` will be printed. This is because the `X` cell, which chooses a random cardinal direction. Every direction except right will skip over the lower segment due to how the `~` are placed.

```
>"kcud"WNojrXv
^~@W"goose"~<>~

```

Try it online!

# Answer
> 2 votes
# Python 2, ~~48~~ ~~43~~ 33 bytes

```
print"duck\n"*(id(0)%9+1)+"goose"

```

Try it online!

Takes no input. Prints a max of 9 'duck's.

**Explanation:**

```
               # Call the id() function on the integer 0.
               # This is a different, usually very large integer every time the program is executed.
               # % 9 will return 0-8, so this will return 1-9.
               id(0)%9+1
# print 1-9 'duck's, each ending in a new line, then finally 'goose'
print"duck\n"*(.........)+"goose"

```

# Answer
> 2 votes
# Ink, ~~24~~ 22 bytes

```
-(h)
duck
{~goose|->h}

```

Try it online!

# Answer
> 2 votes
# MathGolf, ~~17~~ ~~16~~ 15 bytes

```
9╒wôÿduckn'g╕3`

```

-1 byte thanks to *@maxb*.

Try it online.

**Explanation:**

Prints `[1, 9]` amount of `duck`.

```
9╒          # Push a list [1,2,3,4,5,6,7,8,9]
  w         # Pop and push a random integer from this list
   ô        # Loop that many times and execute the following six characters:
    ÿduck   #  Push the 4-character string "duck"
         n  #  Push a newline
   'g╕3`   '# After the loop: push 'g' and compressed "oose"
            # (join everything on the stack together and output it implicitly)

```

# Answer
> 2 votes
# Zsh, 25 bytes

```
repeat $ <<<duck
<<<goose

```

Try it online!

Prints `duck` {process ID} times. A PID is not really random, but it's indeterminate and never 0. On TIO, this tends to be in the region of 10,000.

# Answer
> 2 votes
# APL, 22 bytes

```
∇P
'DUCK'
→?3
'GOOSE'∇

```

# Answer
> 2 votes
# Ly, 27 bytes

```
"Duck"9`1[p&:09?]p"Goose"&o

```

Try it online!

The code pushes a random number of "Duck\n" strings onto a stack, then pushes "Goose" and prints the whole thing.

```
"Duck"                      - push "Duck" onto the stack
      9`                    - push LF (9+1) onto the stack
        1                   - push 1 to start loop
         [p     ]p          - loop until top of stack is "0"
           &:               - duplicate stack
             09?            - generate random number in 0-9 range
                  "Goose"   - push "Goose" on the stack
                         &o - print the entire stack

```

# Answer
> 1 votes
# Ruby: 33 bytes

```
puts 'duck\n'*Time.new.sec+'goose'

```

Try it online! (Note that TIO doesn't respect newline characters like a normal console)

It might take a second, but sooner or later it'll print another number of ducks...

Okay, I just like the idea, it'd be a little shorter as:

# Ruby, 30 bytes

Shortened thanks to @ovs

```
puts"duck\n"*-~rand(9)+'goose'

```

Try it online!

# Answer
> 1 votes
# J: 24 bytes

Arbitrarily limited to no more than 9 ducks:

```
'Goose',~>(>:?9)$<'Duck'

```

# Answer
> 1 votes
# Red, 38 bytes

```
loop random 9[print"duck"]print"goose"

```

Try it online!

# Answer
> 1 votes
# Python 3, ~~43~~ ~~40~~ 36 bytes

EDIT: Saved 3 bytes thanks to l4m2

EDIT: Saved 4 bytes by removing useless `end=` from print function.

```
print('Duck\n'*max(id(0),1),'Goose')

```

Python's `id` function produces an indeterminate value between runs of the program. So we call `id` on 0. `id` is not guaranteed to be `>=1`, so use `max` to ensure the value is at least 1.

# Answer
> 1 votes
# APL+WIN, 24 bytes

```
⊃((?⎕),1)/'duck' 'goose'

```

Prompts for an integer which can be between 1 and system maximum and will then select a number from 1 to that integer at random for the number of ducks. If no input is desired then the max integer can be hard coded for a few more bytes.

# Answer
> 1 votes
## PHP ~~53~~ 45 bytes

```
echo str_repeat("duck\n",rand(1,99))."goose";

```

*-8 bits thanks to @manatwork*

Try it online!

# Answer
> 1 votes
# Aceto with `-l` flag, 25 bytes

```
R99**i"duck\n"*£p"goose"p

```

Try it online!

# Answer
> 1 votes
# Chip, 68 bytes

Uses flag `-w`. (Turns out we've decided to simplify how we count flags.)

```
!
>----z/v\ZZZZZt
>ZZZZ-xL')))xc
xx)))b`? b(((
)x-x)~a   dde
c^ed^~g

```

Try it online!

After printing each `"DUCK\n"`, makes a binary choice for whether to go back to `"DUCK\n"`, or print `"GOOSE"` and terminate.

So, 1/2 of all runs will see one DUCK, 1/4 will see two, 1/8 will see three, and so on.

The left blob under the `Z`'s contains the encoding for `"DUCK\n"`, and the right blob under the `Z`'s contains `"GOOSE"`. The connecting bit between the two makes the random decision, and the rest is just infrastructure.

# Answer
> 1 votes
# Add++, 42 bytes

```
D,f,?:,@n
R9
y:duck
W,x:y,O,x:0,R9
x:goose

```

Try it online!

# Answer
> 1 votes
**Ruby, 49 Bytes**

```
(rand(9)+1).times do
puts "duck"
end
puts "goose"

```

*Explanation*

1. Generate an integer between 0 and 9 and add 1 to it
2. Each of those times print a duck
3. End the loop and print goose

# Answer
> 1 votes
# AWK, ~~59~~ 55 bytes

```
END{for(srand();i++<9*rand();)print"duck";print"goose"}

```

Try it online!

-4 bytes thanks to manatwork

# Answer
> 1 votes
# RUST, 240 bytes

```
extern crate rand;
use rand::distributions::{IndependentSample, Range};
fn main() {
  let mut rng = rand::thread_rng();
  println!("{}", std::iter::repeat("Duck\n").take(Range::new(1, 9).ind_sample(&mut rng)).collect::<String>()+"Goose");
}

```

You can try it here: https://play.rust-lang.org/?version=stable&mode=release Copy and Paste Sorry I dont have shorten link due their server error!

# Answer
> 1 votes
# mIRC v.7.51, ~~40~~ 37 bytes

Also works in most older versions, and definitely in newer versions.

```
//echo $str(Duck $crlf,$r(1,9)) Goose

```

**How It Works?**

```
$r(1,9) -> Generates a random number between 1 and 9
$crlf -> Prints the carriage return and linefeed characters (ASCII 13 and 10 respectively)
$str -> Reoeats the first argument required number of times
echo -> Prints the succeeding text in the window

```

*-3 bytes -\> Changed* `$rand` *to* `$r`

Please note that mIRC echo does not recognize the newline character, so the text is printed in the same line in the window. However, the text contains the newline character which means that if you copy paste it anywhere, then you will see the text in multiple lines. I believe this is allowed.

# Answer
> 1 votes
### Javascript - 61 bytes

```
document.write('duck<br>'.repeat(Math.random()*10+1)+'goose')

```

Live here

### Second change - 57 bytes

```
document.write('duck<br>'.repeat(new Date()%9+1)+'goose')

```

Thanks @Martin

Another way is using console.log, but it is not visual for people to see the answer

### 52 bytes

```
console.log('duck\n'.repeat(new Date()%9+1)+'goose')

```

Try it online

### 46 bytes with alert

```
alert('duck\n'.repeat(new Date()%9+1)+'goose')

```

Try it online

# Answer
> 1 votes
# Pyth, 17 bytes

```
VhOT"duck";"goose

```

Try it online!

Pretty simple. Loops between 1 and 11 times, printing `duck`, then prints `goose`.

# Answer
> 1 votes
# Elixir, 57 bytes

```
fn->String.duplicate("duck
",:rand.uniform 2)<>"goose"end

```

Returns a string either one or two ducks.

Try it online!

# Answer
> 1 votes
# Tcl, 45 characters

```
while {rand()<.9} puts\ duck
puts duck\ngoose

```

Try it online!

### Tcl, 55 characters

```
puts [string repeat duck\n [expr int(rand()*9+1)]]goose

```

Sample run:

```
bash-4.4$ tclsh <<< 'puts [string repeat duck\n [expr int(rand()*9+1)]]goose'
duck
duck
goose

```

Try it online!

# Answer
> 1 votes
# Attache, 33 bytes

```
Print=>Random[1,9]&"duck"'"goose"

```

Try it online!

## Explanation

`Print=>` prints each element of:

`Random[1,9]&"duck"`, which repeats `"duck"` a random number between `1` and `9` times, and

`"goose"`, which is appended to the end with `'`.

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 76 bytes

```
	X =TIME() * 100
S	OUTPUT ='DUCK'
	X =GT(X) X - 1	:S(S)
	OUTPUT ='GOOSE'
END

```

Try it online!

The `TIME` function counts the amount of time (in tenths of a second) elapsed since the program began, which does have a bit of randomness. Since it's so short, however, we have to scale by 100 or else the time will be nearly always zero. Then it outputs `DUCK` until `X<0`, decrementing `X` each iteration, before printing `GOOSE`.

# Answer
> 1 votes
# PHP ~~55~~ 53 Bytes (Thanks manatwork)

```
for($i=0;$i<time();$i++)echo 'duck<br>';echo 'goose';

```

Legibly

```
for($i=0;$i<time();$i++){
    echo 'duck<br>';
}
echo 'goose';

```

Now, I haven't tested this, because I don't want to melt my old computer, but it will output one duck for every second since January 1, 1970, 0000 hours. (Then a goose)

# Answer
> 1 votes
# Funky, 51 bytes

```
(p=print)"Duck"whilemath.random()>.3p"Duck"p"Goose"

```

Funky is surprisingly bad at Duck Duck Goose.

Try it online!

# Answer
> 1 votes
# Kotlin ~~71~~ 65 bytes

```
for(i in 1..(1..9).shuffled()[0])println("duck");println("goose")

```

Thanks Makotosan for the tip on how to replace the random to shave a few bytes.

# Answer
> 1 votes
## shell, 65 bytes

```
f(){ echo duck&&expr `date +%N` % 2 >/dev/null&&f||echo goose;};f

```

ideone

# Answer
> 1 votes
## Perl6/Rakudo, ~~27~~ 26 chars

```
say ｢Duck
｣x now%9~'Goose'

```

Change `now%9` to `9.rand` for sub-second nondeterminism at a cost of 1 char.

# Answer
> 1 votes
# golflua, 38 characters

```
M.rs(O.t())!@w"duck"!$M.r()<.1w"goose"

```

Sample run:

```
bash-4.4$ opt/eso/golflua-1.0/src/golflua -e 'M.rs(O.t())!@w"duck"!$M.r()<.1w"goose"'
duck
duck
goose

```

# Answer
> 1 votes
# Labyrinth, 65 bytes

```
"  ^
1  \.701
0      .
0.117.99
0
1 "
"""v
  " 103.11:1:..5.101.@

```

Try it online!

# Answer
> 1 votes
# Swift 3/4, ~~94~~ ~~74~~ 73 bytes

```
import Foundation;for _ in -1..<time(nil)%9{print("duck")};print("goose")

```

Try it online!

# Answer
> 1 votes
# PHP, 40 bytes

```
<?=str_pad(goose,5+5*date(m),"duck
",0);

```

prints one duck for every month (3 in March, 4 in April etc.)

Run with `-n` (no config file) or try it online.

# Answer
> 1 votes
# Lua, ~~50~~ 46 bytes

Giving a new language a try.

```
d="duck\n"print(d:rep(os.time()%9|1).."goose")

```

Try it online

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

Too many ducks for one goose!

```
main(){while(rand())puts("duck");puts("goose");}

```

Try it online!

# Answer
> 1 votes
# WinDBG, 39 bytes

```
.foreach(_ {#}){.echo duck};.echo goose

```

How it works:

```
.foreach(_                              $$ Loop..., using an unused variable _
           {#})                         $$ ...through each space separated "word" of the next disassembly text
               {.echo duck};            $$ Print duck on each iteration
                            .echo goose $$ Print goose at the end

```

The dissambly text will be formatted something like this. The examples on MSDN don't have the first line, so maybe that only shows if you have symbols for the code that you're currently debugging. But definitely the `assembly_details` part can contain spaces (or be empty) which will cause a different number of ducks to print.

```
dll!Function [source @ line]:
address binary_code      assembly_mnemonic     assembly_details

```

With the above example, it would print (in parenthesis is the value of `_`, not actually printed)

```
duck (dll!Function)
duck ([source)
duck (@)
duck (line]:)
duck (address)
duck (binary_code)
duck (assembly_mnemonic)
duck (assembly_details)
goose

```

# Answer
> 1 votes
# Twig, 45 bytes

Twig is a templating language written in PHP.

This uses the `random()` function up to 9.
Then, it will loop all elements in the range of `1 - random(9)`.

This causes a bug: `random(<n>)` returns values up to the `<n>` value (including 0).
However, twig allows to make a range of `1 - 0`, creating an array with 2 elements.

This ensures that there is always, at least, 1 duck.

```
{%for _ in 1..random(9)%}duck
{%endfor%}goose

```

You can try it on https://twigfiddle.com/w0m6p6

# Answer
> 1 votes
# jamal, 47 characters

```
{@format time=ss}{#for i/0..{#time}/duck
}goose

```

(No proper random, no subdivision of seconds, so the most random thing is the second.)

Sample run:

```
bash-4.4$ jamal.pl duck.jam
duck
duck
goose

```

# Answer
> 1 votes
# Python 2, ~~84~~ 82 bytes

```
from random import*
a="Duck"
print a
while randint(0,9)%2:print a
print"Goose"

```

EDIT: changed random number function

# Answer
> 1 votes
# Labyrinth, 58 bytes

```
" v03.1:1:1:..5.01.@
" ^
1;v
.  100.11
0 7     7
1.101.99.

```

Try it online!

Shorter than the previous Labyrinth solution. This is the first Labyrinth program I have written with moving code!

# Answer
> 1 votes
# Visual Basic For Applications, 37 bytes

```
do:?"duck":loop while rnd>.1:?"goose"

```

# Answer
> 1 votes
# Kotlin, 45 bytes

```
"duck\n".repeat((1..9).shuffled()[0])+"goose"

```

Try it online!

# Answer
> 1 votes
# Java (OpenJDK 8), 106 bytes

```
a->{int r = new Random().nextInt(9);while(r>0){System.out.println("duck");r--;}System.out.print("goose");}

```

Try it online!

# Answer
> 1 votes
# Julia, ~~46~~ 40 bytes

```
d="duck\n";print(d^rand(UInt)*d*"goose")

```

Upon invocation, this will print out between 1 and 2^64 instances of "duck " on the screen before printing "goose". If your computer uses a 64-bit processor like most people do, this will almost certainly blow whatever process memory allowance there is and cause an OOM error which Julia catches and returns to you gracefully.

If you want to test it, put "UInt8" instead of "UInt" to pare it down to between 1 and 256 ducks before a goose.

# Answer
> 1 votes
# C#, 97 Bytes

```
a=>{var r=new Random();var s="";do{s+="Duck\n";}while(r.Next(9)>0);s+="Goose";Console.Write(s);};

```

# Answer
> 1 votes
# Gol\>\<\>, 21 bytes

```
"esooG"fSxXFa"kcuD"|H

```

Try it online!

### How it works

```
"esooG"fSxXFa"kcuD"|H

"esooG"                Push "Goose" in reverse order
       f               Push 15
        Sx             Push a random number in [0,1)
          X            Exponentiation
           F  ...  |   Pop n and repeat the content n times
            a"kcuD"    Push "Duck\n" in reverse order
                    H  Print the content of the stack as chars
                       from top to bottom, then halt

```

The result of `fSxX` is in the range `[1,15)`, but `F` takes the ceiling of the popped value as the repeat count, so the actual result has `[2,15]` ducks. (1 duck is theoretically possible, but the chance is about `2**-52`.)

# Answer
> 1 votes
# Taxi, 567 bytes

```
Go to Heisenberg's: w 1 r, 3 r, 1 l.Pickup a passenger going to The Underground.Go to The Underground: s 1 r 1 l.[a]Switch to plan "b" if no one is waiting.Pickup a passenger going to The Underground."duck\n" is waiting at Writer's Depot.Go to Zoom Zoom: n 3 l 2 r.Go to Writer's Depot: w.Pickup a passenger going to Post Office.Go to Post Office: n 1 r 2 r 1 l.Go to The Underground: n 1 r 1 l.Switch to plan "a".[b]"duck\ngoose\n" is waiting at Writer's Depot.Go to Writer's Depot: n 3 l 2 l.Pickup a passenger going to Post Office.Go to Post Office: n 1 r 2 r 1 l.

```

Prints a very large number of ducks, almost always enough to overflow the output buffer on TIO, and then prints a goose, then terminates with an error. Note: "duck\ngoose\n" can't be shortened to just "goose\n", because Heisenberg's could return exactly zero (although the chance is miniscule).

Try it online!

# Answer
> 1 votes
## Python 3, 50 bytes

```
exec("print('duck');"*abs(id({})))
print("goose")

```

Could be shortened by 1 byte using

```
id(1)

```

But than there will be no random on the same environment.

### Explanation

id() -- returns unique id of python object, usually adress in memory, because we getting ID of freshly created hash it will different every run.

# Answer
> 1 votes
# x86-64 Machine Code (Linux), 40 bytes

```
0000000000000000 <goose>:
   0:   67 6f
   2:   6f
   3:   73 65
   5:   0a

0000000000000006 <duck>:
   6:   64 75 63
   9:   6b
   a:   0a

Disassembly of section .text:

0000000000000000 <_start>:
   0:   b0 01                   mov    $0x1,%al
   2:   40 b7 01                mov    $0x1,%dil
   5:   be 00 00 00 00          mov    $0x0,%esi
   a:   b2 06                   mov    $0x6,%dl
   c:   0f 05                   syscall
   e:   0f c7 f1                rdrand %ecx
  11:   67 e3 ec                jecxz  0 <_start>
  14:   b0 01                   mov    $0x1,%al
  16:   be 00 00 00 00          mov    $0x0,%esi
  1b:   0f 05                   syscall

```

The first 12 bytes are used to store the strings "goose\n" and "duck\n". Technically when duck is printed, it prints 6 bytes (while "duck\n" is 5 bytes), but chances are that the byte after where duck is located in the binary will be an invisible character.

The blocks that preceded the syscall are just setting up the sys\_write system call. Normally in x86-64 this looks like (in Intel syntax rather than AT&T):

```
b8 01 00 00 00                   mov    $0x1,%eax ; syscall number for sys_write
bf 01 00 00 00                   mov    $0x1,%edi ; fd number for STDOUT
48 be 00 00 00 00 00 00 00 00    movabs $0x0,%rsi ; pointer to where the "duck\n" string is located (nasm syntax)
ba 06 00 00 00                   mov    $0x6,%edx ; number of bytes to write
0f 05                            syscall

```

However we can use the lower bits addressing of the registers to produce shorter x86 opcodes.

For the second syscall, only rax gets clobbered (since it holds the return value for sys\_write), so we have to reset it.

The randomness comes from using the `rdrand` instruction, which sets a hardware random number into ecx. The next instruction then jumps back to \_start if ecx is 0. This means that "duck" will only be printed again with a chance of 1/(2^32). However small this chance is, it technically is possible and non-deterministic.

The more interesting way to print out a series of "duck" strings before "goose" is to replace the rdrand and jecxz instructions with:

```
66 0f c7 f3             rdrand %bx
66 85 db                test   %bx,%bx
75 e9                   jne    0 <_start>

```

Unfortunately this takes 2 more bytes, but the effect is that the result of rdrand is stored into bx, which is a 16 bit register. Additionally, each time this is run, the chance the code jumps back to *start* and prints "duck" again is (2^16 - 1)/(2^16). This means that after about 50000 loops there's over a 50% chance of bx being 0 in at least one of the loops. (The exact amount is 45426 loops). For a 90% chance of bx being 0 in at least one of the loops, just over 150000 loops need to occur.

Finally, with normal program behavior, this program should call sys\_exit with this code:

```
0000000000000020 <_exit>:
  20:   b8 3c 00 00 00          mov    $0x3c,%eax
  25:   31 ff                   xor    %edi,%edi
  27:   0f 05                   syscall

```

But since we can just leave this out and the program will exit with a segmentation fault, this is fine. The challenge has already been completed by this point.

For better inline comments, check out the original nasm source code in my repo.

# Answer
> 1 votes
# APL (Dyalog Unicode), 40 bytes

```
{⎕←'Duck'}⍣{1=?9}2⋄⎕←'Goose'

```

Sure there's already a shorter Dyalog solution, but it doesn't have the potential to print Duck an infinite amount of times :P

Also the 2 does absolutely nothing lol

Try it online!

# Answer
> 1 votes
# Japt `-R`, 15 bytes

```
`Ýõãµ&o `qÍtMq

```

Run it online

# Answer
> 1 votes
# TI-BASIC (TI-84), 20 bytes

```
While not(rand:Disp "DUCK:End:Disp "GOOSE

```

Prints `DUCK` on a new line until `rand` returns `1`, where it will then print `GOOSE`.
This program will take a significant amount of time to complete due to the specifications of `rand`.
If `rand`just so happens to have `196164532` as its seed, then the program won't print any `DUCK`s. This can be fixed by adding **4 bytes**:

```
0:While not(Ans:Disp "DUCK:rand:End:Disp "GOOSE

```

---

**Note:** TI-BASIC is a tokenized language. Character count does *not* equal byte count.

# Answer
> 1 votes
# Java 8, 139 bytes

OP wanted a full program, so here you go

```
interface I{static<T>void p(T t){System.out.println(t);}static void main(String[]a){for(p("duck");Math.random()>.1;p("duck"));p("goose");}}

```

Try it online!

# Answer
> 1 votes
# Trigger, 52 bytes

```
ABddduuuccckkk

AAB	 	 	 	 	 	 	 	Bgggooo ooossseee

```

Try it online!

# Answer
> 1 votes
# GolfScript, 25 bytes

```
1 9rand+{"duck"n}*"goose"

```

### Explanation

```
1 9rand+        # pick a random integer in [1, 10]
{"duck"n}       # push 'duck\n'
*               # repeat the previous code block the random number of times
"goose"         # push 'goose'

```

# Answer
> 1 votes
# Roblox Studio - 71 bytes

> @BenjaminUrquhart Better find more games to answer in

Looks like I found another game (a reasonably popular one too)!

```
print('duck')
while math.random(9)>1 do print('duck')end
print('goose')

```

Apparently 0 is a truthy value in Roblox/Lua so I had to use `>1`.
You can seed this with `math.randomseed(tick())`.

# Answer
> 1 votes
# Runic Enchantments, 22 bytes

```
"duck"akqf'RA*"goose"@

```

Try it online!

### Explanation

```
"duck"akq                Push the string "duck" with a newline on the end
         'RA             Random number 0-15
            *            Duplicate the string so that there are n copies python
                             style (bug? 0 still leaves one copy; I'm ok with this)
             "goose"     Concatenate "goose" onto the end
                    @    Print and terminate

```

# Answer
> 1 votes
## Keg, 19 bytes

```
(~2%1+|duck\
)goose

```

Explanation

```
(~2%          Repeat random number in range 0,1
    1+        Increment to range 1,2
      |       Do:
       duck   Push "duck"
           \  and a newline
)             End
goose         Push "goose"

```

TIO

# Answer
> 1 votes
# Vyxal `oH`, 12 bytes

```
℅(‛¦ø,)`go⋎Ǒ

```

Try it Online!

The `H` flag (preset stack to 100) is really useful lol

# Answer
> 1 votes
# Fortran (GFortran), 47 ~~59~~ bytes

```
print'(A)',('duck',j=0,mod(i,5)**2),'goose';end

```

Try it online! ~~<sub>59 bytes</sub>~~

Had to put this code into a subroutine otherwise the loop doesn't run. Some weird compiler stuff going on, probably because `i` wasn't initialised, to produce randomness.

# Answer
> 1 votes
# \>\<\> (Fish), 22 bytes

```
"duck"a>x
ose"r>o<>"go

```

Try it

# Answer
> 1 votes
# Thunno 2 `TO`, 10 bytes

```
ɼ{`_*£}`⁾®

```

Attempt This Online!

Or, **12 bytes** flagless:

```
Tɼ{`_*£}`⁾®£

```

Attempt This Online!

#### Explanation

```
Tɼ{`_*£}`⁾®£  # Full program
T             # Push 10. The T flag implicitly does this.
 ɼ            # Pop it and push a random number from 1 to 10.
  {    }      # Loop that many times:
   `_*        #  Push the compressed string "Duck"
      £       #  And print it with a newline
        `⁾®   # Push the compressed string "Goose"
           £  # And print it. The O flag forces the implicit output.

```

---
Tags: code-golf, random
---