Duck, duck, goose!

59

8

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.

AJFaraday

Posted 2018-03-12T15:49:36.737

Reputation: 10 466

11Could you define indeterminate? Could it mean either zero or one? – recursive – 2018-03-12T15:51:14.607

1Please define how randomly this should be generated. Uniform in range or with exponential decline? – HyperNeutrino – 2018-03-12T15:52:43.903

@recursive Nope, but let's go with a working definition... The program does not consistently present the same number of ducks. – AJFaraday – 2018-03-12T15:52:55.417

Is any leading or trailing white-space acceptable on the lines printed to STDOUT; what about leading newline(s) or excess trailing newlines (beyond the one that I assume would be allowed anyway)? – Jonathan Allan – 2018-03-12T16:33:43.193

Is there a maximum number of times one can "duck"? 1000? 100000000? – Οurous – 2018-03-12T19:55:41.407

Probably anything that's finite and produces some output – Manish Kundu – 2018-03-13T04:06:18.153

2

Speaking as a Minnesotan, what if mine prints "duck, duck, gray duck" instead? :)

– Mike Hill – 2018-03-14T19:13:59.480

@MikeHill that variant intrigued me, someone else mentioned it in an answer. It’d definitely make a fun variation... – AJFaraday – 2018-03-14T19:15:44.867

@MikeHill Was about to say the same thing! – GendoIkari – 2018-03-14T22:10:16.277

@MikeHill, Clearly, "gray duck" is the proper output – Brian – 2018-03-14T22:22:45.937

I remember it. Am I the only one? =( – jpmc26 – 2018-03-15T23:05:11.280

1@jpmc26 I’m sure there are others. You’d have had to play it with others, for a start. – AJFaraday – 2018-03-15T23:13:08.007

@MikeHill In Danish language, the species mallard is known as "gråand" which litterally means grayduck. – Jeppe Stig Nielsen – 2018-03-16T09:26:03.137

Relevant etymology question – Engineer Toast – 2018-03-22T16:34:16.310

Answers

9

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.

user202729

Posted 2018-03-12T15:49:36.737

Reputation: 14 620

Congrats! I have literally no idea how this works! – AJFaraday – 2018-03-16T10:19:18.673

@AJFaraday I went ahead and added an explanation for you – PunPun1000 – 2018-03-16T13:07:59.657

@PunPun1000 Sorry, but what's the stack? Jelly is a tacit programming language. – user202729 – 2018-03-16T13:51:22.727

@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 – 2018-03-16T14:02:08.230

There's an implicit concatenation in Jelly? Yay! – MilkyWay90 – 2019-03-21T23:38:22.067

@MilkyWay90 Just for clarification, the reason that this "concatenates" the output is because the final compressed string is an "unparseable nilad", meaning that the program outputs the previous result and then restarts with the new nilad. No implicit concatenation actually happens – caird coinheringaahing – 2019-10-20T20:59:39.543

@cairdcoinheringaahing Okay, thanks for clarifying! – MilkyWay90 – 2019-10-21T00:53:24.920

43

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

Steadybox

Posted 2018-03-12T15:49:36.737

Reputation: 15 798

3It always makes me glad when someone uses this on PCG. – Nit – 2018-03-13T20:03:08.787

Well i forgot this game existed. – Caimen – 2018-03-16T19:33:50.013

38

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

Kelly Lowder

Posted 2018-03-12T15:49:36.737

Reputation: 3 225

11Oh my lord... Why have I never thought of this. – Magic Octopus Urn – 2018-03-13T19:03:48.897

4PVCG (Programming Videogames and Code Golf). Operation Flashpoint was a thing, but WoW? I am waiting the Minecraft and Factorio solutions of this. – Brain Guider – 2018-03-14T10:59:25.000

2@AnderBiguri I suspect the Minecraft one would do a little worse than 81 bytes (blocks?) ;) – Chris – 2018-03-14T19:24:03.533

5This should work and get you down to 58 bytes: /run for x=1,random(1,9)do print("Duck")end print("Goose") – gastropner – 2018-03-15T10:33:04.333

35

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

enter image description here

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

FlyingPiMonster

Posted 2018-03-12T15:49:36.737

Reputation: 711

1Beautiful. We need more Minecraft in PPCG. – BradC – 2018-03-15T19:23:32.563

9Worth 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 – 2018-03-15T21:56:32.330

1@BradC there should be entire challenges based around Minecraft. – tox123 – 2018-03-18T17:47:33.980

17

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>

Shaggy

Posted 2018-03-12T15:49:36.737

Reputation: 24 623

14

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.

Stewie Griffin

Posted 2018-03-12T15:49:36.737

Reputation: 43 471

disp(['duck '+~pwd';'goose'])? Not sure if this is "indeterminate" enough – Luis Mendo – 2018-03-12T19:53:56.703

12

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.

Ton Hospel

Posted 2018-03-12T15:49:36.737

Reputation: 14 114

If you change 1+$^T%9 to just $^T, it still works, and you save 4 bytes. – Chris – 2018-03-13T01:47:44.757

@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 – 2018-03-13T06:03:18.167

12

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"

Greg Fuller

Posted 2018-03-12T15:49:36.737

Reputation: 121

3Welcome to the site, and nice first answer! – caird coinheringaahing – 2018-03-12T20:30:46.837

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 – 2018-03-13T11:50:27.553

1Can id(id) not be id(0) or am I missing something? – Jonathan Frech – 2018-03-14T11:18:31.260

@Johnathan, looking at id(0) on a couple different computers suggests it's a constant. – user2699 – 2018-03-14T18:21:40.707

There's no rule that a program needs to run quickly or efficiently, as long as it would finish at some point on a sufficiently powerful machine and produce the correct output. With that in mind, removing %5 and the associated parentheses would save 6 bytes. – user2699 – 2018-03-14T18:26:22.550

@user2699 I tried that, and, based on rough theoretical calculations, in about 90% of cases, you will get an OutOfMemory exception before a single character is printed. The actual number in practice is probably much higher. I am not comfortable with a solution that takes that risk. I also wanted to be able to demonstrate the functionality on TIO. – Greg Fuller – 2018-03-14T20:16:42.820

1Slightly 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 – 2018-03-15T23:17:19.763

11

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:

enter image description here

lucasb

Posted 2018-03-12T15:49:36.737

Reputation: 451

1This has totally made my day! – AJFaraday – 2018-03-23T08:46:56.500

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 – 2018-03-23T16:47:39.057

Yep, there's some themes in my code golf challenges :) I should definitely give bonus points for pictoral answers. – AJFaraday – 2018-03-23T16:48:39.910

Isn't this a standard loophole, to get external resources? – MilkyWay90 – 2019-01-12T16:56:03.543

10

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.

user2390246

Posted 2018-03-12T15:49:36.737

Reputation: 1 391

1The probability of outputting more than one duck is exp(-1) or around 36.8%. – Giuseppe – 2018-03-12T16:50:32.527

It asks to print it on each line. I think you should add " \n" to your "duck" – stuart stevenson – 2018-03-13T10:54:22.687

3@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 – 2018-03-13T11:02:30.400

On a DOS/Windows box, that newline would still be two (2) bytes. 0x0d0a – lit – 2018-03-17T19:16:21.877

10

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.

Sophia Lechner

Posted 2018-03-12T15:49:36.737

Reputation: 1 200

That’s a good number of ducks. :) – AJFaraday – 2018-03-12T19:01:11.107

1Welcome to PPCG! – Steadybox – 2018-03-12T19:31:28.530

Thanks! Been lurking for a while but this seemed like an easy one to start with. :) – Sophia Lechner – 2018-03-12T19:44:46.377

1You can save one byte by getting rid of the single quotes as long as you replace \n with \\n. – Chris – 2018-03-13T01:55:32.513

1

Nice idea. You can do something similar with just bash constructs and no sed for 30 bytes.

– Digital Trauma – 2018-03-13T06:27:17.873

1sed s/[0-9]/duck\\n/g<<<$RANDOM\goose can shave off one byte – sch – 2018-03-13T16:49:24.823

Ah! Thank you, @DigitalTrauma. I had played around with using that sort of parameter expansion, but I couldn't get it to replace globally because I didn't know about starting it with a double forward slash. I've been using Bash for about a month now so this is all very educational. Feel free to post yours as a separate answer; it deserves my upvotes! And thank you sch and Chris for the extra bytes. – Sophia Lechner – 2018-03-13T17:29:44.910

@SophiaLechner Ok, thanks, here it is

– Digital Trauma – 2018-03-13T18:50:26.507

1The 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 – 2018-03-13T19:33:38.420

@OlivierDulac suggested using $$ instead of $RANDOM for my answer. I think you could use the same to save you 5 bytes. – Digital Trauma – 2018-03-14T17:09:50.670

Have you gotten to testing @DigitalTrauma's suggestion? – MilkyWay90 – 2019-10-21T01:08:01.010

9

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.

Digital Trauma

Posted 2018-03-12T15:49:36.737

Reputation: 64 644

1if 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 – 2018-03-14T16:28:43.810

@OlivierDulac yes, I think using $$ is acceptable - thanks! – Digital Trauma – 2018-03-14T17:03:11.093

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 – 2018-03-14T17:29:58.307

8

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.

Chris

Posted 2018-03-12T15:49:36.737

Reputation: 1 313

Bash has modulo, though that will increase the size. Try head -n $((1+(RANDOM % 5))) – tripleee – 2018-03-13T20:12:49.117

@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 – 2018-03-13T20:16:58.160

1

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 – 2018-03-14T05:18:42.840

@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 – 2018-03-14T17:10:44.950

In fact yes duck|sed $$q;echo goose is fine - I don't think your script would ever get a PID < 1. – Digital Trauma – 2018-03-14T17:17:06.983

@DigitalTrauma $$ is a little iffy, since running it twice in the same shell gives the same results. Though it works on TIO, so I guess that's fine? Thanks! – Chris – 2018-03-14T18:01:22.643

oh my... I didn't knew there was another answer with the same idea I got.. I'll delete mine and give you an upvote. replace head -n $$ by sed $$q (idea is from @DigitalTrauma) – Olivier Dulac – 2018-03-14T18:23:46.637

@Chris I think for the purposes of codegolf you may assume that the script is saved in a file and run like ./duckgoose.sh. In which case it will run in its own shell (with a fresh PID) – Digital Trauma – 2018-03-14T18:47:13.837

@DigitalTrauma Ah, that is true, and makes it much less iffy. Thanks! – Chris – 2018-03-14T18:57:45.713

8

Ruby, 30 bytes

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

Try it online!

Note: really 31 bytes without the \n cheat.

Turophile

Posted 2018-03-12T15:49:36.737

Reputation: 181

I’m not sure it’s a cheat, strictly speaking. – AJFaraday – 2018-03-14T06:44:14.923

7

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

AdmBorkBork

Posted 2018-03-12T15:49:36.737

Reputation: 41 581

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 – 2018-03-12T16:12:20.593

1@AdmBorkBork, this Minnesotan joined this group to just +1 your gray duck. – Milwrdfan – 2018-03-12T17:06:29.817

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 – 2018-03-16T08:17:12.143

@TessellatingHeckler Thanks, but I just-now came up with a 28-byte version. :) – AdmBorkBork – 2018-03-16T12:32:51.117

6

Python 2, 54 bytes

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

Try It Online!

Quintec

Posted 2018-03-12T15:49:36.737

Reputation: 2 801

@JonathanAllan thanks :) – Quintec – 2018-03-12T19:09:23.983

6

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

PunPun1000

Posted 2018-03-12T15:49:36.737

Reputation: 973

So, if I’m reading this right, it reads from left-to-right, bottom-to-top? – AJFaraday – 2018-03-13T21:33:35.273

2The 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 – 2018-03-13T21:36:31.087

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 – 2018-03-13T21:49:53.540

You can merge the two predicates like this and tie me.

– Erik the Outgolfer – 2018-03-13T23:10:32.857

6

C# (Visual C# Interactive Compiler), 55 bytes

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

Try it online!

arekzyla

Posted 2018-03-12T15:49:36.737

Reputation: 201

Really clever use of string formatting! – Embodiment of Ignorance – 2019-04-30T02:46:08.833

6

Geometry Dash World 2.2 Editor - 4 objects

Picture of Geometry Dash Level

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.

enter image description here

Goose and 2nd duck don't have a Group ID enter image description here

Inside the random trigger. enter image description here

MilkyWay90

Posted 2018-03-12T15:49:36.737

Reputation: 2 264

I sense a theme for this challenge – Benjamin Urquhart – 2019-03-18T23:09:59.800

@BenjaminUrquhart What? – MilkyWay90 – 2019-03-18T23:10:51.580

There are submissions for Word of Warcraft, Minecraft, and some other game as well. – Benjamin Urquhart – 2019-03-18T23:11:28.040

2@BenjaminUrquhart Better find more games to answer in – MilkyWay90 – 2019-03-18T23:12:06.923

5

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)

Kaldo

Posted 2018-03-12T15:49:36.737

Reputation: 1 135

1You can use 'Ðœ since duck is a single word. – Emigna – 2018-03-12T16:39:20.533

1Beats mine: ['ÐœTΩ#].•zíΘ•» – Magic Octopus Urn – 2018-03-13T13:20:41.807

@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 – 2018-03-13T13:37:05.537

@Kaldo still, 15 bytes loses to yours ;) – Magic Octopus Urn – 2018-03-13T14:56:31.393

1Alternate 14-byter: 'Ðœ₁Ω.D.•zíΘ•» – Magic Octopus Urn – 2018-03-13T16:08:04.513

5

APL (Dyalog), 22 bytes

1 byte saved thanks to @EriktheOutgolfer

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

Try it online!

Uriel

Posted 2018-03-12T15:49:36.737

Reputation: 11 708

Alternative: 'Goose'⊣⎕←⍣(?9)⊢'Duck' – Erik the Outgolfer – 2018-03-12T17:08:41.000

5

><>, 31 22 bytes

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

Try it online!

-9 bytes based on Not a tree's revision

KSmarts

Posted 2018-03-12T15:49:36.737

Reputation: 1 830

1You could remove l?!; and exit with an error. – Emigna – 2018-03-12T20:59:07.680

1

And you could save some more like this

– Emigna – 2018-03-12T21:04:54.233

1

Or like this.

– Not a tree – 2018-03-13T01:38:04.237

3@Notatree I get that one to sometimes print "\nkcud\nkcud...". It rarely behaves correctly – Suppen – 2018-03-13T07:50:34.923

1@Suppen Just using an arrow instead of a mirror fixes it; see edit. – KSmarts – 2018-03-13T13:41:24.447

@KSmarts Aargh, sent the wrong link, well done for fixing it… – Not a tree – 2018-03-13T15:05:09.397

5

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

Martin Ender

Posted 2018-03-12T15:49:36.737

Reputation: 184 808

5

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.

jiwopene

Posted 2018-03-12T15:49:36.737

Reputation: 151

2Welcome 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 – 2018-03-12T21:19:36.063

Welcome to PPCG! – Steadybox – 2018-03-12T21:22:14.163

5

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

Vincent

Posted 2018-03-12T15:49:36.737

Reputation: 601

1You don't need the # on the second line – Jo King – 2018-03-14T02:11:05.120

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 – 2018-03-14T02:16:43.880

@JoKing Thanks, see my edit. – Vincent – 2018-03-14T09:26:35.090

5

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

Probably

Posted 2018-03-12T15:49:36.737

Reputation: 207

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 – 2018-03-13T18:17:40.117

Actually, you can just do while rand()<.5print'duck'print'duck(linebreak)goose' for 43. – BradC – 2018-03-13T18:29:16.953

Nice, thanks @BradC. Is there another way to represent a line break in a string other than adding a char(13)? – Probably – 2018-03-13T18:51:50.160

Yep, just literally put a return inside the quotes, I'll edit your post to show you (comments don't show returns). – BradC – 2018-03-13T19:33:59.030

1Save 3 more bytes: change the first while to if. Prints (randomly) either one duck or two, which (I believe) still satisfies the challenge. – BradC – 2018-03-13T20:02:24.587

Hmm I didn't think of it that way. 1 or 2 ducks is technically random... – Probably – 2018-03-13T20:10:19.320

you can trim out the begin/end from the original answer for 46 bytes if you use linebreaks properly. That way it can still print more than 2 ducks while(rand()<.5)[br]print'duck'[br]print'duck[br]goose' – Zac Faragher – 2018-03-13T23:29:17.773

@Alex looks like you can still trim a byte from the first answer: while rand()<.5print'duck'print'duck[br]goose' – Zac Faragher – 2018-03-15T06:15:07.383

5

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"

SomeShinyObject

Posted 2018-03-12T15:49:36.737

Reputation: 953

You shouldn't need the $ in front of (Random). Try it online!

– AdmBorkBork – 2018-03-19T13:07:54.410

@AdmBorkBork thanks for the catch! – SomeShinyObject – 2018-03-19T13:44:38.570

4

Fission, 24 19 bytes

R"duck"N#
"goose"*[

Try it online!

-5 bytes thanks to Martin Ender

KSmarts

Posted 2018-03-12T15:49:36.737

Reputation: 1 830

4

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()

Luis felipe De jesus Munoz

Posted 2018-03-12T15:49:36.737

Reputation: 9 639

169 bytes: _=>{for(_=0;_<Math.random()*9;_++)(l=console.log)('Duck');l('goose')} – Herman L – 2018-03-12T20:36:05.253

1Won't this give you no ducks if random returns zero? – Shaggy – 2018-03-13T08:00:23.877

163 Bytes: _=>{for(_=0;_<=new Date%10;_++)(l=console.log)`Duck`;l`goose`} – binarymax – 2018-03-13T15:38:08.200

1@binarymax, you can save 2 more bytes on that with _++<=new Date%9 and a few more by using alert instead of console.log. – Shaggy – 2018-03-14T17:13:17.523

Or you can use my original solution for 42 bytes: while(alert'duck',new Date%9);alert'goose' (replace single quotes with backticks). – Shaggy – 2018-03-14T17:15:46.970

@Shaggy Thanks, but i would prefer having a different answer than yours. Although yours is better – Luis felipe De jesus Munoz – 2018-03-14T17:19:39.117

You're more than welcome to it; my solution is now significantly different. – Shaggy – 2018-03-14T17:21:06.943

1One byte shorter: for(_=9;_-->new Date%9;). Another four bytes less: for(_=new Date;_--;) (no idea if that works, though) – Titus – 2018-03-14T17:27:35.807

(_=0)=>{for(l=console.log;_++<=new Date%9;)l`Duck`;l`goose`} <-- made it cleaner – Ismael Miguel – 2018-03-15T12:54:20.073

4

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.

rael_kid

Posted 2018-03-12T15:49:36.737

Reputation: 341

If a 50% chance to goose is acceptable, 55+"kcud",,,,,#v?(linebreak here) @,,,,,"goose"< would cut your code down to 35 bytes – karhell – 2018-03-13T15:54:25.077

Ah the sweet wrap-around. You're right, thanks, I'll post an update later! – rael_kid – 2018-03-14T05:50:34.807

4

Brachylog, 21 bytes

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

Try it online!

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

Erik the Outgolfer

Posted 2018-03-12T15:49:36.737

Reputation: 38 134

4

Minecraft Functions (18w11a, 1.13 snapshots), 402 382 bytes

duck duck goose in minecraft

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

Noskcaj

Posted 2018-03-12T15:49:36.737

Reputation: 421

Nice work, I approve of Minecraft submissions. Can you explain how this generates a variable number of ducks?

– BradC – 2018-03-15T20:40:41.667

3

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

Giuseppe

Posted 2018-03-12T15:49:36.737

Reputation: 21 077

35 bytes – user2390246 – 2018-03-12T16:38:15.473

1@user2390246 I think that's sufficiently different from mine as to warrant its own answer, especially since every answer is bound to be a variant of "generate a random number of ducks one goose"; yours is a quite distinct approach. – Giuseppe – 2018-03-12T16:42:34.570

2

Fair enough, thanks for your sportsmanship! Added as a separate answer

– user2390246 – 2018-03-12T16:50:33.747

3

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.

12Me21

Posted 2018-03-12T15:49:36.737

Reputation: 6 110

3

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

l4m2

Posted 2018-03-12T15:49:36.737

Reputation: 5 985

Change the 1 to a 0 in case %random% returns 0? – Neil – 2018-03-12T17:31:06.037

@Neil Done               – l4m2 – 2018-03-12T17:36:43.067

3

Python 3, 52 bytes

prints 1 to 256 ducks.

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

Try it online!

ovs

Posted 2018-03-12T15:49:36.737

Reputation: 21 408

3

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

powelles

Posted 2018-03-12T15:49:36.737

Reputation: 1 277

17 bytes – Shaggy – 2018-03-13T07:53:50.100

16 bytes – Oliver – 2018-03-14T18:01:42.307

You can use p2â ö to randomly return 1 or 2. Unfortunately the shortcut for p2 wouldn't be useful here so it would still be 17 bytes. – Oliver – 2018-03-14T18:09:32.457

Thanks @Oliver! I didn't catch that in the shortcuts. – powelles – 2018-03-14T20:44:53.820

3

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

Οurous

Posted 2018-03-12T15:49:36.737

Reputation: 7 916

3

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

Herman L

Posted 2018-03-12T15:49:36.737

Reputation: 3 611

3

PHP, 35 bytes

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

Or rand() if you prefer.

Try it online!

ToXik-yogHurt

Posted 2018-03-12T15:49:36.737

Reputation: 311

I think this breaks the rule "There must be exactly one bird on each line. No empty lines." – Goose – 2018-03-13T18:50:13.907

@Goose: There is a leading duck in the first line before the code. – Titus – 2018-03-14T15:54:19.100

Save one byte with -n and date(s) instead of time()%2. – Titus – 2018-03-14T15:57:11.753

@Tinus there's nothing in this code to makes new lines. Everything is on the same line. Every duck and goose must be on it's own line. – Goose – 2018-03-14T17:27:38.250

1@Goose works for me – Οurous – 2018-03-14T21:42:30.763

@Οurous I see my mistake, whoops – Goose – 2018-03-14T21:46:39.007

You can save another byte by putting goose on the same line as ?> Try it online!

– Ethan – 2018-03-19T12:43:49.027

3

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!

niczky12

Posted 2018-03-12T15:49:36.737

Reputation: 301

Welcome to PPCG! – Martin Ender – 2018-03-13T10:08:37.600

Welcome to PPCG! You can include a link to Try it online! (aka TIO) for your answer; TIO has a lot of interpreters and can automatically format your answer for you :)

– Giuseppe – 2018-03-13T13:45:38.713

3

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.

Ciaran_McCarthy

Posted 2018-03-12T15:49:36.737

Reputation: 689

Why using variable c and not just for i=0 to System.Random().Next()do printfn"duck" directly? – manatwork – 2018-03-13T15:15:53.233

It would interfere with the randomness of it. Instead of i terminating at a random value, the larger i gets the more chance it has of being greater than a new random value. – Ciaran_McCarthy – 2018-03-13T15:35:35.090

3

T-SQL, 44 bytes

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

Different method than Alex' excellent answer.

BradC

Posted 2018-03-12T15:49:36.737

Reputation: 6 099

3

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!

tripleee

Posted 2018-03-12T15:49:36.737

Reputation: 131

3

PHP, 36 bytes:

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

Run with -n (no config file)

Titus

Posted 2018-03-12T15:49:36.737

Reputation: 13 814

3

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

panicmore

Posted 2018-03-12T15:49:36.737

Reputation: 51

Technically you need to add include random.fs also you can make it 67 bytes by using a do loop

– reffu – 2018-08-03T15:42:25.713

3

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.

negative seven

Posted 2018-03-12T15:49:36.737

Reputation: 1 931

2

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

HyperNeutrino

Posted 2018-03-12T15:49:36.737

Reputation: 26 575

I've not seen it finishing after a few tries... Theoretically it will is a fun one, tho ;) – AJFaraday – 2018-03-12T15:55:46.163

265 bytes – Rod – 2018-03-12T15:58:02.707

2I'm not totally certain this is valid, isn't it possible that for some seed the PRNG will actually never generate a zero? It's not a particularly big deal, since you can correct it easily, but I think this would technically need a proof. – FryAmTheEggman – 2018-03-12T17:26:43.190

@FryAmTheEggman I think in this case "Never say never" is mathematically accurate. – Berry M. – 2018-03-12T18:41:01.430

2

Python 2, 54 bytes

Turns out thecoder16 ninja'd this Python 2 version...

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

Prints 1-9 ducks 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!

Jonathan Allan

Posted 2018-03-12T15:49:36.737

Reputation: 67 804

1

You can reach 54 bytes if you switch to py2

– Rod – 2018-03-12T16:45:30.873

I think I may have just posted that, sorry – Quintec – 2018-03-12T16:48:27.870

@thecoder16 Oh you ninja'd me? :D – Jonathan Allan – 2018-03-12T16:49:18.907

It’s down there somewhere, about 3 minutes ago, though it’s not properly formatted because I don’t know how :( Should I delete or what? – Quintec – 2018-03-12T16:51:08.950

@thecoder16 No, that's fine, I've hit the same solution as others within short time frames before - I only delete if I am much later and it's just a result of not reading other answers! (I've also linked to your post too) – Jonathan Allan – 2018-03-12T16:52:39.540

2

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

rafa11111

Posted 2018-03-12T15:49:36.737

Reputation: 310

Can you use tabs for indentation to save bytes? – Pavel – 2018-03-12T17:15:38.910

I'm afraid Fortran 77 do not accept tabs, since the first columns in each line are reserved for labels, e.g., as you can see in the fifth line. Tabs are accepted (with warnings) since Fortran 90. – rafa11111 – 2018-03-12T17:17:16.440

Can you save a byte using A*9 instead of A*10? – AdmBorkBork – 2018-03-12T18:52:33.083

Wow, I'm ashamed! Pretty clever! Thank you! – rafa11111 – 2018-03-12T18:59:11.887

2

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.

Nik Weiss

Posted 2018-03-12T15:49:36.737

Reputation: 91

2

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"

Kevin Cruijssen

Posted 2018-03-12T15:49:36.737

Reputation: 67 575

1d+=.1 => d*=2 – l4m2 – 2018-03-13T10:00:04.207

I made several searches before posting my answer, but I couldn't find this one, for some reason. I deleted it after seeing this one. Anyways, I'm not sure this fulfills the challenge as the challenge specifies "print", not "output". Edit... 2 pages, that's why I didn't see it... – Olivier Grégoire – 2018-03-13T11:00:16.847

"Anyways, I'm not sure this fulfills the challenge as the challenge specifies "print", not "output"." Well, it also specifies program instead of function. I personally interpret 'print' as 'print or return' in almost all cases, except for explicitly STDOUT is mentioned. But maybe that's just me.. – Kevin Cruijssen – 2018-03-13T11:55:36.897

I'm not familiar with Java, but this seems to work for 47 bytes. According to the docs, Math.random() returns values such that 0 <= x < 1, so Math.random()>0 should work too, but that seems hard to test and very unlikely to actually happen.

– my pronoun is monicareinstate – 2018-03-13T13:20:35.203

@someone The changes of an actual 0.000... are indeed astronomical small. But your 47-byte version is indeed a nice golf, so thanks! :) – Kevin Cruijssen – 2018-03-13T13:44:57.230

Try it online! seems to work for 43 bytes, but it requires creation of a instance Main and has a similar(i?)ly low chance of ducking twice, but it at least happens in a tight loop. – my pronoun is monicareinstate – 2018-03-14T02:15:18.853

@someone I'm afraid hashCode() will always give the same result for this class; 1418481495 in this case. So it won't ever be lower than 9 using the default non-overwritten hashCode. Nice try though.

– Kevin Cruijssen – 2018-03-14T07:43:47.340

2

Golfscript, 22 bytes

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

Quintec

Posted 2018-03-12T15:49:36.737

Reputation: 2 801

(completely new to golfscript, this may not be optimal) – Quintec – 2018-03-13T14:17:58.553

2

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.

Goose

Posted 2018-03-12T15:49:36.737

Reputation: 219

Presumably you could just as easily use millisecond? – AJFaraday – 2018-03-13T19:26:37.320

Probably a lot of options depending on how wide a range of random numbers you want, but I think they'd all be the same byte count. – Goose – 2018-03-13T20:19:24.963

@Goose using mktime() saves one byte – Ben – 2018-03-14T01:58:02.960

@Ben true, but it tries to allocate 7605159771 bytes and I can't run that on my machine so I'm not sure if it's appropriate to include. – Goose – 2018-03-14T12:55:34.013

For the purposes of code golf, you may assume infinite memory. – Shaggy – 2018-03-15T19:51:41.763

1default values (no config; flag -n) disable notices and allow <?=str_repeat("duck\n",date(h))?>goose or <?=str_repeat("duck\n",date(h)),goose;, saving two bytes; a literal newline saves another byte. – Titus – 2018-03-15T21:43:04.340

2

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!

c1000

Posted 2018-03-12T15:49:36.737

Reputation: 21

1Welcome to PPCG! – Shaggy – 2018-03-15T00:50:07.557

2

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"

jqblz

Posted 2018-03-12T15:49:36.737

Reputation: 2 062

2

Groovy, 42 bytes

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

Try it online!

Gurupad Mamadapur

Posted 2018-03-12T15:49:36.737

Reputation: 1 791

:) Yea kinda fun for golfing. – Gurupad Mamadapur – 2018-03-16T12:09:51.970

2

Excel, 33 bytes

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

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

Wernisch

Posted 2018-03-12T15:49:36.737

Reputation: 2 534

2

T-SQL, 43 bytes

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

Razvan Socol

Posted 2018-03-12T15:49:36.737

Reputation: 341

2

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

moonheart08

Posted 2018-03-12T15:49:36.737

Reputation: 693

2

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!

snail_

Posted 2018-03-12T15:49:36.737

Reputation: 1 982

2

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"

Triggernometry

Posted 2018-03-12T15:49:36.737

Reputation: 765

2

Ink, 24 22 bytes

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

Try it online!

Sara J

Posted 2018-03-12T15:49:36.737

Reputation: 2 576

2

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)

Kevin Cruijssen

Posted 2018-03-12T15:49:36.737

Reputation: 67 575

To get a random number in range [1, 9] inclusive: 9╒w. This way, you don't have to discard the stack after the loop. 15-byter: 9╒wôÿduckp'g╕3`

– maxb – 2019-06-03T13:28:24.370

@maxb Ah, of course! I initially had 9w, but of course it could also result in 0, so I changed it to and combined it with , but was kinda annoyed by the integers still on the stack. But of course 9╒w is better, fixing that problem. :) – Kevin Cruijssen – 2019-06-03T13:47:58.703

1

C (gcc), 66 65 53 50 bytes

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

Try it online!

cleblanc

Posted 2018-03-12T15:49:36.737

Reputation: 3 360

I can print one or two ducks in 46 bytes if you're interested... – Neil – 2018-03-12T16:15:45.777

1@Neil Post your answer – cleblanc – 2018-03-12T16:21:44.667

2main(){puts("duck\nduck\ngoose"+time(0)%2*5);} – Neil – 2018-03-12T16:33:41.180

I think as puts returns 5 all the time (for this case), so for(;time(0)&puts("duck");) may work (although in a different way) – user202729 – 2018-03-12T16:37:27.653

If you use puts("duck")&time(0) u should say the environment. Some puts() return 0 – l4m2 – 2018-03-12T17:19:24.327

1

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!

AJFaraday

Posted 2018-03-12T15:49:36.737

Reputation: 10 466

Ah, you've bested my Ruby version by a byte! I have had to resort to a cheat to get down to 30 (which if you apply would get you to 29). – Turophile – 2018-03-14T04:42:59.273

That's 34 bytes, not 33. – Shaggy – 2018-03-15T20:01:50.717

@Shaggy I got there with Ruby’s ‘length’ function. Perhaps it’s reading the newline character as one? – AJFaraday – 2018-03-15T22:31:26.983

Note that TIO doesn't respect newline characters like a normal console This is not a TIO issue. \n works inside double quotes, but not inside single quotes. In any case, \n can be replaced with a literal newline. Try it online! – Dennis – 2018-05-16T15:20:54.290

1

J: 24 bytes

Arbitrarily limited to no more than 9 ducks:

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

DevonMcC

Posted 2018-03-12T15:49:36.737

Reputation: 79

2

I've just run this through Try It Online. It doesn't seem to output anything. https://tio.run/##y/r/X909P784VV2nzlrDzsreUlPFRt2lNDlbR0H9/38A

– AJFaraday – 2018-03-12T16:58:40.897

You need to use echo to get the output (presumably this is assumed to be run on the REPL). Try this. I don't know why it seems like it only outputs one possible number of "Duck"s, though (probably has to do with the way J evaluates ? in nouns).

– cole – 2018-03-12T17:08:57.853

TIO seems to prescribe a particular format not suited to an immediate execution language like J (or their J implementation is broken). Try putting the code both in "Code" and "Input". – DevonMcC – 2018-03-12T17:14:20.447

J seeds the RNG with 16807 on startup, so the output is always deterministic, noun or not. Try it with seeding

– FrownyFrog – 2018-03-12T20:41:16.963

According to Dennis at the tio site, you need to prefix the J code with "echo" to see the output. To re-seed the RNG, you could add this phrase to the right of a J phrase using random numbers: [ 9!:1]<.13#.|.}.6!:0'' – DevonMcC – 2018-03-12T21:49:09.030

1

Red, 38 bytes

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

Try it online!

Galen Ivanov

Posted 2018-03-12T15:49:36.737

Reputation: 13 815

1

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.

mypetlion

Posted 2018-03-12T15:49:36.737

Reputation: 702

This doesn't work. – Erik the Outgolfer – 2018-03-12T17:18:10.080

Is hash guaranteed to be non-zero? The output is required to have at least one duck. – recursive – 2018-03-12T17:18:22.900

@recursive Good point. Edited. – mypetlion – 2018-03-12T17:20:50.427

@EriktheOutgolfer How so? – mypetlion – 2018-03-12T17:21:06.237

So what about id(something) – l4m2 – 2018-03-12T17:27:27.040

@mypetlion The previous version wasn't guaranteed to have a non-zero hash... – Erik the Outgolfer – 2018-03-12T17:28:20.820

@l4m2 Do you know if id is guaranteed positive? I couldn't find any indication one way or the other online. – mypetlion – 2018-03-12T17:53:46.077

29 bytes using python2: print'Duck\n'*-~id(0)+'Goose' – Vincent – 2018-03-13T14:16:03.820

1

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.

Graham

Posted 2018-03-12T15:49:36.737

Reputation: 3 184

1

PHP 53 45 bytes

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

-8 bits thanks to @manatwork

Try it online!

Luis felipe De jesus Munoz

Posted 2018-03-12T15:49:36.737

Reputation: 9 639

1Wouldn't rand(1,99) do essentially the same as substr(rand(),-2)? – manatwork – 2018-03-13T12:20:20.607

@manatwork yep, didn't know that function existed, thanks – Luis felipe De jesus Munoz – 2018-03-13T13:10:14.620

1

Aceto with -l flag, 25 bytes

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

Try it online!

drham

Posted 2018-03-12T15:49:36.737

Reputation: 515

Command-line flags are counted as separate languages, now, so no need to add +1 to your byte count.

– AdmBorkBork – 2018-03-12T19:09:03.290

@AdmBorkBork Wasn't aware. Thanks! – drham – 2018-03-12T19:24:11.853

1

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.

Phlarx

Posted 2018-03-12T15:49:36.737

Reputation: 1 366

1

Add++, 42 bytes

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

Try it online!

caird coinheringaahing

Posted 2018-03-12T15:49:36.737

Reputation: 13 702

1

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

SalmonKiller

Posted 2018-03-12T15:49:36.737

Reputation: 121

1With 0.upto(rand 9){puts:duck};puts:goose you can get rid of the extra parenthesis needed due to the +1. – manatwork – 2018-03-13T13:41:03.440

1

AWK, 59 55 bytes

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

Try it online!

-4 bytes thanks to manatwork

Noskcaj

Posted 2018-03-12T15:49:36.737

Reputation: 421

No need for parenthesis around print's argument. – manatwork – 2018-03-13T12:37:33.070

1

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!

NTCG

Posted 2018-03-12T15:49:36.737

Reputation: 151

Hi there -- I don't know RUST at all but there's definitely some unnecessary whitespace you can remove. If there's any way to make shorter variable names, that will also help. – Giuseppe – 2018-03-13T17:42:24.617

1

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.

Manish Kundu

Posted 2018-03-12T15:49:36.737

Reputation: 1 947

1

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

Hyperfork

Posted 2018-03-12T15:49:36.737

Reputation: 19

Welcome to PPCG! You don't need to print duck so many times, so you can save a byte by reducing *10 to *9 or something like that. And I think a common way to get a shorter indeterminate number would be new Date()%9+1. – Martin Ender – 2018-03-13T12:27:25.993

@MartinEnder Thanks, I think about number 10 and 9 before but I forgot to try that number, and thanks for your suggestion about new Date()%9+1 that helped me saved some bytes, I will update the code – Hyperfork – 2018-03-13T12:32:54.837

The 52-byte version is completely fine. That's the usual output you'd use in a console (as opposed to a browser): https://tio.run/##y0osSyxOLsosKNHNy09J/f8/OT@vOD8nVS8nP11DPaU0OTsmT12vKLUgNbFEIy@1XMElsSRVQ1PVUttQU1s9PT@/OFVd8/9/AA

– Martin Ender – 2018-03-13T13:00:10.957

I have added a better solution with "alert", It only 46 bytes. – Hyperfork – 2018-03-13T13:10:29.757

save one byte by using `` with a literal newline instead of "" with \n – Brian H. – 2018-03-14T12:24:31.170

1save another 4 bytes by using lambda: _=>*duck *.repeat(new Date()%9+1)+'goose' (literal newline after duck and ` instead of *) – Brian H. – 2018-03-14T12:27:05.507

1

Pyth, 17 bytes

VhOT"duck";"goose

Try it online!

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

KSmarts

Posted 2018-03-12T15:49:36.737

Reputation: 1 830

1

Elixir, 57 bytes

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

Returns a string either one or two ducks.

Try it online!

Okx

Posted 2018-03-12T15:49:36.737

Reputation: 15 025

1

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!

manatwork

Posted 2018-03-12T15:49:36.737

Reputation: 17 865

1

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

Conor O'Brien

Posted 2018-03-12T15:49:36.737

Reputation: 36 228

1

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.

Giuseppe

Posted 2018-03-12T15:49:36.737

Reputation: 21 077

1

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)

Ben

Posted 2018-03-12T15:49:36.737

Reputation: 131

Checked the documentation of mktime()? The Notes contains a good golfing hint: mktime() without parameter is equivalent with time().

– manatwork – 2018-03-14T08:40:19.807

1

Funky, 51 bytes

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

Funky is surprisingly bad at Duck Duck Goose.

Try it online!

ATaco

Posted 2018-03-12T15:49:36.737

Reputation: 7 898

1

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.

Asitaka

Posted 2018-03-12T15:49:36.737

Reputation: 21

You can save a byte by using 9 instead of 10.

Also, you can shave off a few more by changing your random function to this:

(1..9).shuffled()[0]

So that your for loop looks like : for(i in 1..(1..9).shuffled()[0])

This will only work as long as you use small values. If you get into the millions, it will take up a lot of CPU and memory. – Makotosan – 2018-03-21T21:58:46.347

1

shell, 65 bytes

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

ideone

Divlaker

Posted 2018-03-12T15:49:36.737

Reputation: 11

Too many 2 character list operators, when the single character ; would be enough. Also discarding expr's output would be shorter with an assignment than with redirection: f(){ echo duck;x=\expr \`date +%N\` % 2`&&f;};f;echo goose` – manatwork – 2018-03-14T09:52:44.527

@manatwork Thank you for your advice. Just have fun. – Divlaker – 2018-03-15T08:53:00.090

1

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.

Phil H

Posted 2018-03-12T15:49:36.737

Reputation: 1 376

1

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

manatwork

Posted 2018-03-12T15:49:36.737

Reputation: 17 865

1

Labyrinth, 65 bytes

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

Try it online!

Herman L

Posted 2018-03-12T15:49:36.737

Reputation: 3 611

1

Swift 3/4, 94 74 73 bytes

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

Try it online!

Tamás Sengel

Posted 2018-03-12T15:49:36.737

Reputation: 211

1

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.

Titus

Posted 2018-03-12T15:49:36.737

Reputation: 13 814

1

Lua, 50 46 bytes

Giving a new language a try.

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

Try it online

Shaggy

Posted 2018-03-12T15:49:36.737

Reputation: 24 623

1

C (gcc), 48 bytes

Too many ducks for one goose!

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

Try it online!

KillerIsDead

Posted 2018-03-12T15:49:36.737

Reputation: 11

1

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

milk

Posted 2018-03-12T15:49:36.737

Reputation: 3 043

1

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

Ismael Miguel

Posted 2018-03-12T15:49:36.737

Reputation: 6 797

I guess it´s a feature, not a bug. 0..random(9) and random(9)..0 should also work. – Titus – 2018-03-15T13:04:02.210

Well, it could cause a bug. And yes, those work as well. – Ismael Miguel – 2018-03-15T13:30:48.153

1

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

manatwork

Posted 2018-03-12T15:49:36.737

Reputation: 17 865

1

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

sonrad10

Posted 2018-03-12T15:49:36.737

Reputation: 535

1

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!

MegaTom

Posted 2018-03-12T15:49:36.737

Reputation: 3 787

1

Visual Basic For Applications, 37 bytes

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

dnep

Posted 2018-03-12T15:49:36.737

Reputation: 301

1

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!

X1M4L

Posted 2018-03-12T15:49:36.737

Reputation: 1 586

1

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.

eaglgenes101

Posted 2018-03-12T15:49:36.737

Reputation: 577

1

C#, 97 Bytes

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

Romen

Posted 2018-03-12T15:49:36.737

Reputation: 161

1

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

Bubbler

Posted 2018-03-12T15:49:36.737

Reputation: 16 616

1

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!

pppery

Posted 2018-03-12T15:49:36.737

Reputation: 3 987

1

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.

Андрей Ломакин

Posted 2018-03-12T15:49:36.737

Reputation: 309

This usually errors as the program runs out memory trying to store an extremely large string – Jo King – 2018-08-02T07:41:42.347

1

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.

davey

Posted 2018-03-12T15:49:36.737

Reputation: 321

Suggest xor %esi, %esi instead of mov $0x0, %esi – ceilingcat – 2019-09-30T18:20:36.650

1

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!

akhmorn

Posted 2018-03-12T15:49:36.737

Reputation: 51

You say the 2 does nothing, but removing it gives you “goose” every time. If must do something? – AJFaraday – 2019-01-13T14:30:00.317

1@AJFaraday well ok it does do something. it forces the niladic dfn on the left to get called otherwise it won't be. – akhmorn – 2019-01-13T15:02:43.327

1

Japt -R, 15 bytes

`Ýõãµ&o `qÍtMq

Run it online

Oliver

Posted 2018-03-12T15:49:36.737

Reputation: 7 160

1

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 randjust so happens to have 196164532 as its seed, then the program won't print any DUCKs. 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.

Tau

Posted 2018-03-12T15:49:36.737

Reputation: 1 935

1

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!

Benjamin Urquhart

Posted 2018-03-12T15:49:36.737

Reputation: 1 262

120 bytes by creating a String to print at the end. EDIT: 113 bytes by exponentially growing the amount of "duck\n". – Kevin Cruijssen – 2019-06-03T10:46:12.027

Then again, an extension of my Java lambda is 105 bytes.. ;)

– Kevin Cruijssen – 2019-06-03T10:49:23.770

1

Trigger, 52 bytes

ABddduuuccckkk


AAB	 	 	 	 	 	 	 	Bgggooo ooossseee

Try it online!

MilkyWay90

Posted 2018-03-12T15:49:36.737

Reputation: 2 264

I think you missed a line when copy-pasting. – negative seven – 2019-06-04T12:56:41.610

@negativeseven I did not copy-paste. Also, there is no line missing\ – MilkyWay90 – 2019-06-04T20:51:57.000

Ah, TIO just wrapped the line but the UI here didn't. My bad. – negative seven – 2019-06-05T07:44:31.357

1

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'

clabe45

Posted 2018-03-12T15:49:36.737

Reputation: 121

1

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()). enter image description here

MilkyWay90

Posted 2018-03-12T15:49:36.737

Reputation: 2 264

1

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

Draco18s no longer trusts SE

Posted 2018-03-12T15:49:36.737

Reputation: 3 053

1

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

user85052

Posted 2018-03-12T15:49:36.737

Reputation:

0

Kotlin, 45 bytes

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

Try it online!

Makotosan

Posted 2018-03-12T15:49:36.737

Reputation: 503