# 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.
• Could you define indeterminate? Could it mean either zero or one? – recursive Mar 12 '18 at 15:51
• Please define how randomly this should be generated. Uniform in range or with exponential decline? – HyperNeutrino Mar 12 '18 at 15:52
• @recursive Nope, but let's go with a working definition... The program does not consistently present the same number of ducks. – AJFaraday Mar 12 '18 at 15:52
• Speaking as a Minnesotan, what if mine prints "duck, duck, gray duck" instead? :) – Mike Hill Mar 14 '18 at 19:13
• @jpmc26 I’m sure there are others. You’d have had to play it with others, for a start. – AJFaraday Mar 15 '18 at 23:13

# 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.

• Congrats! I have literally no idea how this works! – AJFaraday Mar 16 '18 at 10:19
• @AJFaraday I went ahead and added an explanation for you – PunPun1000 Mar 16 '18 at 13:07
• @PunPun1000 Sorry, but what's the stack? Jelly is a tacit programming language. – user202729 Mar 16 '18 at 13:51
• @user202729 Oops, I got Jelly and 05AB1E messed up in my head, could you please edit it to fix that error? Sorry about that – PunPun1000 Mar 16 '18 at 14:02
• There's an implicit concatenation in Jelly? Yay! – MilkyWay90 Mar 21 '19 at 23:38

# 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]}

• It always makes me glad when someone uses this on PCG. – Etheryte Mar 13 '18 at 20:03
• Well i forgot this game existed. – Caimen Mar 16 '18 at 19:33

## 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")

• Oh my lord... Why have I never thought of this. – Magic Octopus Urn Mar 13 '18 at 19:03
• PVCG (Programming Videogames and Code Golf). Operation Flashpoint was a thing, but WoW? I am waiting the Minecraft and Factorio solutions of this. – Brain Guider Mar 14 '18 at 10:59
• @AnderBiguri I suspect the Minecraft one would do a little worse than 81 bytes (blocks?) ;) – Chris Mar 14 '18 at 19:24
• This should work and get you down to 58 bytes: /run for x=1,random(1,9)do print("Duck")end print("Goose") – gastropner Mar 15 '18 at 10:33

# 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")

• Beautiful. We need more Minecraft in PPCG. – BradC Mar 15 '18 at 19:23
• Worth mentioning that you (the player) are an entity in the world, so the number of ducks can never be 0 (even if there were no hostile or passive mobs). – BradC Mar 15 '18 at 21:56
• @BradC there should be entire challenges based around Minecraft. – tox123 Mar 18 '18 at 17:47

# JavaScript, 45444239 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>

# 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.

• disp(['duck '+~pwd';'goose'])? Not sure if this is "indeterminate" enough – Luis Mendo Mar 12 '18 at 19:53

# 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.

• If you change 1+$^T%9 to just $^T, it still works, and you save 4 bytes. – Chris Mar 13 '18 at 1:47
• @chris You obviously have more memory than I do. Still, I'll take your suggestion since there are reasonable computers on which it will work. Thanks. – Ton Hospel Mar 13 '18 at 6:03

# 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"

• Welcome to the site, and nice first answer! – caird coinheringaahing Mar 12 '18 at 20:30
• Welcome to PPCG! You can golf two bytes by changing ((id(id)%5)+1) to -~(id(id)%5) to get rid of the parenthesis. Tips for golfing in <all languages> and Tips for golfing in Python might be interesting to read through. Enjoy your stay! – Kevin Cruijssen Mar 13 '18 at 11:50
• Can id(id) not be id(0) or am I missing something? – Jonathan Frech Mar 14 '18 at 11:18
• @Johnathan, looking at id(0) on a couple different computers suggests it's a constant. – user2699 Mar 14 '18 at 18:21
• Slightly more intuitive and no more bytes would be to call id([]). This should initialize a distinct list each time the program runs, which in theory should consistently result in different memory addresses. – jpmc26 Mar 15 '18 at 23:17

# Z Shell (+ wget & Netpbm), 168160150148145135 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:

• This has totally made my day! – AJFaraday Mar 23 '18 at 8:46
• I've just realized that you're the same person who proposed that other challenge I linked to. xD Well, I'm glad you liked this! =D – lucasb Mar 23 '18 at 16:47
• Yep, there's some themes in my code golf challenges :) I should definitely give bonus points for pictoral answers. – AJFaraday Mar 23 '18 at 16:48
• Isn't this a standard loophole, to get external resources? – MilkyWay90 Jan 12 '19 at 16:56

# R, 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.

• The probability of outputting more than one duck is exp(-1) or around 36.8%. – Giuseppe Mar 12 '18 at 16:50
• It asks to print it on each line. I think you should add " \n" to your "duck" – stuart stevenson Mar 13 '18 at 10:54
• @stuartstevenson Here I have used a literal newline rather than \n as it is one byte shorter. If you visit the "Try it online!" link you can see that the effect is the same. – user2390246 Mar 13 '18 at 11:02
• On a DOS/Windows box, that newline would still be two (2) bytes. 0x0d0a – lit Mar 17 '18 at 19:16

# Bash, 3938 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. • Welcome to PPCG! – Steadybox Mar 12 '18 at 19:31 • You can save one byte by getting rid of the single quotes as long as you replace \n with \\n. – Chris Mar 13 '18 at 1:55 • Nice idea. You can do something similar with just bash constructs and no sed for 30 bytes. – Digital Trauma Mar 13 '18 at 6:27 • sed s/[0-9]/duck\\n/g<<<$RANDOM\goose can shave off one byte – sch Mar 13 '18 at 16:49
• The sed isn't entirely portable. On some platforms you might get away with a single backslash in \n. On others you won't get a newline no matter what you do. – tripleee Mar 13 '18 at 19:33

# 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  • if we assume you launch a program, it will get a different pid every time. a lot of the time it will be 5 digits long, but not always. hence: change RANDOM to $ to shave 5 bytes?And one could also do a very long string of ducks: yes duck|head -n $$;echo goose – Olivier Dulac Mar 14 '18 at 16:28 • @OlivierDulac yes, I think using $$ is acceptable - thanks! – Digital Trauma Mar 14 '18 at 17:03
• you are welcome! I posted my other version (yes duck | head -n $$;echo goose) as an alternative (longer than yours, but one gets a LOT of ducks for 5 extra chars ^^) – Olivier Dulac Mar 14 '18 at 17:29 # Ruby, 30 bytes puts"duck "*rand(1..9)+"goose"  Try it online! Note: really 31 bytes without the \n cheat. • I’m not sure it’s a cheat, strictly speaking. – AJFaraday Mar 14 '18 at 6:44 # 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.

• Bash has modulo, though that will increase the size. Try head -n $((1+(RANDOM % 5))) – tripleee Mar 13 '18 at 20:12 • @tripleee Since this is code golf, increasing the size of the output is preferable to increasing that size of the code. And 132767 ducks is downright reasonable compared to the billion or more you see elsewhere ;) – Chris Mar 13 '18 at 20:16 • Sure, just hoping to be helpful in case somebody actually wants to apply this groundbreaking research in practice one day. Like, TIO. 44 bytes with some spaces taken out. – tripleee Mar 14 '18 at 5:18 • @OlivierDulac suggested using $$ instead of RANDOM for my answer. I think you could use the same to save you 5 bytes. Oh and try sed too: yes duck|sed 1$$q;echo goose – Digital Trauma Mar 14 '18 at 17:10 • In fact yes duck|sed$$q;echo goose is fine - I don't think your script would ever get a PID < 1. – Digital Trauma Mar 14 '18 at 17:17 # PowerShell, 3530 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 -maximum flag of 5 so you can see the program works as expected (the modified version will print 1, 2, 3, or 4 ducks 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" ... • That variant sounds pretty fun, and definitely worth a code challenge... I recommend you wait a couple of days and post it as a challenge of your own :) – AJFaraday Mar 12 '18 at 16:12 • @AdmBorkBork, this Minnesotan joined this group to just +1 your gray duck. – Milwrdfan Mar 12 '18 at 17:06 • 0..(random)|%{'duck'};'goose' looks like a 29, and will also generate somewhere up to [int]::MaxValue (2.1 billion) ducks before a goose. (And 0..0 does print a duck) – TessellatingHeckler Mar 16 '18 at 8:17 • @TessellatingHeckler Thanks, but I just-now came up with a 28-byte version. :) – AdmBorkBork Mar 16 '18 at 12:32 # Python 2, 54 bytes from random import* print"duck\n"*randint(1,9)+"goose"  Try It Online! • @JonathanAllan thanks :) – Quintec Mar 12 '18 at 19:09 # C# (Visual C# Interactive Compiler), 55 bytes Write("{"+new Random().Next(2)+"}{0}goose","duck\n","")  Try it online! • Really clever use of string formatting! – Embodiment of Ignorance Apr 30 '19 at 2:46 # 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  • So, if I’m reading this right, it reads from left-to-right, bottom-to-top? – AJFaraday Mar 13 '18 at 21:33 • The language attempts to find a logical truth using just the first line of the program. My program says "Validate the second line, then print goose". Then the second line says "print duck, then validate either a random number 0 to 4 is 0, or validate this line again", so technically left to right just the top line, then any predicates you call from there – PunPun1000 Mar 13 '18 at 21:36 • Cool, it’s so interesting finding out how new languages work. It did reach my inbox, but I’m not sure if it’s because I posed the question or because I’d already commented here. – AJFaraday Mar 13 '18 at 21:49 • You can merge the two predicates like this and tie me. – Erik the Outgolfer Mar 13 '18 at 23:10 ## 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. • I sense a theme for this challenge – Benjamin Urquhart Mar 18 '19 at 23:09 • @BenjaminUrquhart What? – MilkyWay90 Mar 18 '19 at 23:10 • There are submissions for Word of Warcraft, Minecraft, and some other game as well. – Benjamin Urquhart Mar 18 '19 at 23:11 • @BenjaminUrquhart Better find more games to answer in – MilkyWay90 Mar 18 '19 at 23:12 # 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) • You can use 'Ðœ since duck is a single word. – Emigna Mar 12 '18 at 16:39 • Beats mine: ['ÐœTΩ#].•zíΘ•» – Magic Octopus Urn Mar 13 '18 at 13:20 • @MagicOctopusUrn I really like your infinite loop approach. Your answer is definitely more in the spirit of the challenge (or what it should have been ?) since it can output an infinite amount of ducks. – Kaldo Mar 13 '18 at 13:37 • @Kaldo still, 15 bytes loses to yours ;) – Magic Octopus Urn Mar 13 '18 at 14:56 • Alternate 14-byter: 'Ðœ₁Ω.D.•zíΘ•» – Magic Octopus Urn Mar 13 '18 at 16:08 # APL (Dyalog), 22 bytes 1 byte saved thanks to @EriktheOutgolfer 'Goose'⍪⍨(?9)5⍴'Duck '  Try it online! • Alternative: 'Goose'⊣⎕←⍣(?9)⊢'Duck' – Erik the Outgolfer Mar 12 '18 at 17:08 ## Retina, 17 bytes ?\\Kduck Kgoose  Try it online! Try it online! Prints 1 or 2 ducks, with equal probability. ### Explanation ?\\Kduck  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%. Kgoose  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%...: \Kduck ?+\G Kgoose  # 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. • Welcome to PPCG! You should be able to use \d over [0-9]. Also, it looks like vim doesn't require the trailing newline, so this can be 45 bytes :) – H.PWiz Mar 12 '18 at 21:19 • Welcome to PPCG! – Steadybox Mar 12 '18 at 21:22 # ><>, 31 22 bytes "duck"a>x r"esoog"<>o<  Try it online! -9 bytes based on Not a tree's revision • You could remove l?!; and exit with an error. – Emigna Mar 12 '18 at 20:59 • And you could save some more like this – Emigna Mar 12 '18 at 21:04 • Or like this. – Not a tree Mar 13 '18 at 1:38 • @Notatree I get that one to sometimes print "\nkcud\nkcud...". It rarely behaves correctly – Suppen Mar 13 '18 at 7:50 • @Suppen Just using an arrow instead of a mirror fixes it; see edit. – KSmarts Mar 13 '18 at 13:41 # Befunge 98, 3830 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 • You don't need the # on the second line – Jo King Mar 14 '18 at 2:11 • And "technically", whitespace within a line is fine so you can cut out a couple of quotes (even if the output looks weird) – Jo King Mar 14 '18 at 2:16 • @JoKing Thanks, see my edit. – Vincent Mar 14 '18 at 9:26 # 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 • Nice. Down to 61 if you change select to print and replace the final 'duck'select'goose' with 'duck(linebreak)goose' (with a literal linebreak, of course) – BradC Mar 13 '18 at 18:17 • Actually, you can just do while rand()<.5print'duck'print'duck(linebreak)goose' for 43. – BradC Mar 13 '18 at 18:29 • Nice, thanks @BradC. Is there another way to represent a line break in a string other than adding a char(13)? – Probably Mar 13 '18 at 18:51 • Yep, just literally put a return inside the quotes, I'll edit your post to show you (comments don't show returns). – BradC Mar 13 '18 at 19:33 • Save 3 more bytes: change the first while to if. Prints (randomly) either one duck or two, which (I believe) still satisfies the challenge. – BradC Mar 13 '18 at 20:02 # 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"  • You shouldn't need the $ in front of (Random). Try it online! – AdmBorkBork Mar 19 '18 at 13:07
• @AdmBorkBork thanks for the catch! – SomeShinyObject Mar 19 '18 at 13:44

# Fission, 24 19 bytes

R"duck"N#
"goose"*[


Try it online!

-5 bytes thanks to Martin Ender

# Brachylog, 21 bytes

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


Try it online!

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

# 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.

• If a 50% chance to goose is acceptable, 55+"kcud",,,,,#v?(linebreak here) @,,,,,"goose"<  would cut your code down to 35 bytes – karhell Mar 13 '18 at 15:54
• Ah the sweet wrap-around. You're right, thanks, I'll post an update later! – rael_kid Mar 14 '18 at 5:50