Polar Bear, Polar Bear, what do you hear?

50

6

The text of the children's book Polar Bear, Polar Bear, What Do You Hear? has a very simple pattern. You might use the text to teach introductory programming concepts.

My son was quickly bored by this idea, so I decided to play some golf with it instead.

The Challenge

In your programming language of choice, write the smallest program possible which will print the following text. Output should match exactly, including case, spacing, and punctuation.

Polar Bear, Polar Bear, what do you hear?
I hear a lion roaring in my ear.

Lion, Lion, what do you hear?
I hear a hippopotamus snorting in my ear.

Hippopotamus, Hippopotamus, what do you hear?
I hear a flamingo fluting in my ear.

Flamingo, Flamingo, what do you hear?
I hear a zebra braying in my ear.

Zebra, Zebra, what do you hear?
I hear a boa constrictor hissing in my ear.

Boa Constrictor, Boa Constrictor, what do you hear?
I hear an elephant trumpeting in my ear.

Elephant, Elephant, what do you hear?
I hear a leopard snarling in my ear.

Leopard, Leopard, what do you hear?
I hear a peacock yelping in my ear.

Peacock, Peacock, what do you hear?
I hear a walrus bellowing in my ear.

Walrus, Walrus, what do you hear?
I hear a zookeeper whistling in my ear.

Zookeeper, Zookeeper, what do you hear?
I hear children...

...growling like a polar bear,
roaring like a lion,
snorting like a hippopotamus,
fluting like a flamingo,
braying like a zebra,
hissing like a boa constrictor,
trumpeting like an elephant,
snarling like a leopard,
yelping like a peacock,
bellowing like a walrus...
that's what I hear.

aaaantoine

Posted 2016-07-19T04:01:10.603

Reputation: 591

6[tag:kolmogorov-complexity] would be a good tag for this – charredgrass – 2016-07-19T04:03:33.167

3Are the uppercase B and C in Polar Bear and Boa Constrictor necessary? (In Batch this costs me 10% of my byte count...) – Neil – 2016-07-19T10:15:17.947

Is submitting a hash and bruteforcing the solution with a restricted set allowed? :D – polym – 2016-07-19T10:30:17.567

4This is a very nice first challenge! – Alex A. – 2016-07-19T16:24:27.507

Does the null terminator matter? – noɥʇʎԀʎzɐɹƆ – 2016-07-19T21:06:51.197

@AgentCrazyPython I don't think null terminators get output. Do you mean doing it in brainfuck or something, where they do get output? – Erik the Outgolfer – 2016-07-20T14:05:14.523

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ or newlines – noɥʇʎԀʎzɐɹƆ – 2016-07-20T17:36:08.550

1I'd +1 but you're at 42 upvotes, and who am I to disturb the ways of the galaxy? – FantaC – 2018-02-14T23:06:32.393

@tfbninja, you may now upvote! – Shaggy – 2018-02-16T09:21:46.403

@Shaggy duly noted and upvoted! – FantaC – 2018-02-16T16:05:16.870

Answers

34

05AB1E, 349 331 330 322 314 311 bytes

•4i;kV_†©:š×Îj€Yå—‚‘%˜ESδþ¤çÑ9¶‹{Å€7¾à{Ì®qA•35B0¡…ing«lV•7ü[¿‘¢wÀ¶à-‚¤î„jHâ™ÐJ'µ‡ÀÂý6›ü‚š¸€%NtÅýµL›fU¥ì€€uîT¡›Ÿ{!œ>'Ì&ý§¨Ü?é>•36B1ð:0¡™D©„, «D‚ø“€À€·€î—«?“¶«¸â€˜€JU¦“„¾“‚˜lv„I “—«0€†€¯¶å.“«0¡`yð«Y¦õ‚˜Nè«sr„ aN5Qi'n«}ð«N9›ijrj¨ðs«…...«}srJˆ}X¯‚ø€Jvy,¶?}…...DU?Y¨vN__i',¶}yð“€è€…“N6Qi'n«}ð®NèJl?}X,“€Š's€À I—«.“?

Try it online

Explanation

•4i;kV_†©:š×Îj€Yå—‚‘%˜ESδþ¤çÑ9¶‹{Å€7¾à{Ì®qA•
Packed string containing the sounds GROWL0ROAR0SNORT0FLUT0BRAY0HISS0TRUMPET0SNARL0YELP0BELLOW0WHISTL

35B0¡…ing«lV
Unpack, split on 0, add "ing" to each word, convert to lower and store in variable Y

•7ü[¿‘¢wÀ¶à-‚¤î„jHâ™ÐJ'µ‡ÀÂý6›ü‚š¸€%NtÅýµL›fU¥ì€€uîT¡›Ÿ{!œ>'Ì&ý§¨Ü?é>•
Packed string containing the animals POLAR1BEAR0LION0HIPPOPOTAMUS0FLAMINGO0ZEBRA0BOA1CONSTRICTOR0ELEPHANT0LEOPARD0PEACOCK0WALRUS0ZOOKEEPER

36B1ð:0¡™
Unpack, replace 1 with space, split on 0 and convert to title case

D©„, «D‚ø
Duplicate, save to register for later use, add ", " to one copy, duplicate that and zip.

“€À€·€î—«?“¶«¸
Dictionary words "what do you hear?", followed by a new line, added to a new list

‘€JU
Cartesian product of list of "Animal, Animal, " and "what do you hear?\n", flattened and joined and stores it in variable X. Pruduces list of strings of the form "Animal, Animal, what do you hear?n".

¦“„¾“‚˜l
Take the remaining list of animals from before, remove the zookeeper and add children, convert to lower case.

v
For each animal:

„I “—«0€†€¯¶å.“«0¡`

Push "I hear0 in my ear.", split on 0 and push as separate strings.

yð«Y¦õ‚˜Nè«
Push "animal sound" with children having no sound

sr„ a
Push "a" in correct place

N5Qi'n«}
If the animal is "Elephant" add "n"

ð«
Add space.

N9›ijrj¨ðs«…...«}
If animal is children, remove space and add "..."

srJˆ}
Join the sentence "I hear a(n) animal sound in my ear." (as well as the children one), store in global array and end loop

X¯‚ø€J
Retrieve the first lines, zip and join producing the first part of the rhyme "Animal, Animal, what do you hear?\nI hear a(n) animal sound in my ear."

vy,¶?}
Print followed by new line.

…...DU?
Print "..." and store a copy in variable X.

Y¨v
For each sound except "whistling":

N__i',¶} For each line except the first one, start it with ",\n" (making the comma go on previous line)

yð“€è€…“
Push sound, space and "like a"

N6Qi'n«}
If Elephant add "n".

ð®NèJl?}X,
Retrieve the animal saved in register, join everything, print and end loop followed by "...". This produces the "sound like a(n) animal," lines.

“€Š's€À I—«.“?
Print dictionary string "that's what I hear."

Emigna

Posted 2016-07-19T04:01:10.603

Reputation: 50 798

30This one is summoning Cthulhu. – aloisdg moving to codidact.com – 2016-07-19T18:53:13.377

6I can't see where the code ends and the packed data begins. – Adám – 2016-07-19T19:40:29.300

4@Adám I know. It looks a lot like gibberish :) I'll add an explanation eventually which will hopefully make it clearer. I might want to try and golf it some more first though. – Emigna – 2016-07-19T20:58:27.540

28This is probably how laymen imagine code. – noɥʇʎԀʎzɐɹƆ – 2016-07-19T21:09:38.523

1I have no idea what I just read... – Nico – 2016-07-21T09:23:43.963

Now do it again using the dictionary *LOL*. – Magic Octopus Urn – 2018-02-14T15:54:52.313

It's not working anymore with the changed compression size from 214 to 255 somewhere at the start of 2017, but +1 regardless for the effort and explanation. :) – Kevin Cruijssen – 2019-02-22T09:46:50.100

9

PHP, 420 414 434 414 412 bytes

call from CLI or prepend <pre> to output.

$v=[growl,roar,snort,flut,bray,hiss,trumpet,snarl,yelp,bellow,whistl];$a[6]=n;foreach($n=['polar bear',lion,hippopotamus,flamingo,zebra,'boa constrictor',elephant,leopard,peacock,walrus,zookeeper]as$i=>$p)echo$i?"I hear a$a[$i] $p $v[$i]ing in my ear.

":"",$q=ucwords($p),", $q, what do you hear?
",$i>9?"I hear children...

...":""&$z[]="$v[$i]ing like a$a[$i] $p";echo join(",
",$z),"...
that's what I hear.";
  • a couple of notices for undefined constants; PHP´s implicit cast to literal string kicks in again
  • adding the "n" for "an elephant" took 20 bytes ... hmpf.
  • got the 20 bytes back by reordering stuff :)

breakdown

$n=['polar bear',lion,hippopotamus,flamingo,zebra,'boa constrictor',elephant,leopard,peacock,walrus,zookeeper];
$v=[growl,roar,snort,flut,bray,hiss,trumpet,snarl,yelp,bellow,whistl];
$a[6]=n;
// loop through nouns with index $i
foreach($n as$i=>$p) echo
    // print first part:
        // not first noun: print second line to previous step
        $i?"I hear a$a[$i] $p $v[$i]ing in my ear.\n\n":"",
        // uppercase the first letter of each word in the noun, print
        $q=ucwords($p),
        // print uppercase noun again and the rest of the line
        ", $q, what do you hear?\n",
        // for last noun print bridge, else print nothing
        $i>9?"I hear children...\n\n...":""
    // ... AND add line to second part
        &$z[]="$v[$i]ing like a$a[$i] $p"
;
// print second part and final line
echo join(",\n",$z),"...\nthat's what I hear.";

Titus

Posted 2016-07-19T04:01:10.603

Reputation: 13 814

8

JavaScript, 545 541 497 bytes

a="Polar Bear|Lion|Hippopotamus|Flamingo|Zebra|Boa Constrictor|Elephant|Leopard|Peacock|Walrus|Zookeeper".split`|`;s=btoa`º0:èj¼ìíÍùn·6ëk,áË3¶»¦¥ës²v«<ÛzYhÃ<!Ëe`.split`z`;a.map((m,n)=>{console.log(m+", "+m+", what do you hear?\n "+((n>9)?"I hear children...\n":"I hear a"+(n==5?"n ":" ")+a[n+1].toLowerCase()+" "+s[n+1]+"ing in my ear.\n"))});p="...";a.map((m,n)=>{if(n>9)return;p+=s[n]+"ing like a"+(n==6?"n ":" ")+m.toLowerCase()+(n>8?"...\nthat's what I hear.":",\n")});console.log(p)

Quite a fun challenge!

Thanks Downgoat for saving me 27 a ton of bytes using atob, and Titus for 4 bytes!

Ungolfed:

a="Polar Bear|Lion|Hippopotamus|Flamingo|Zebra|Boa Constrictor|Elephant|Leopard|Peacock|Walrus|Zookeeper".split`|`;
s=btoa`º0:èj¼ìíÍùn·6ëk,áË3¶»¦¥ës²v«<ÛzYhÃ<!Ëe`.split`z`;
a.map((m,n)=>{
  console.log(m+", "+m+", what do you hear?\n "+((n==10)?"I hear children...\n":"I hear a" + (n==5?"n ":" ") + a[n+1].toLowerCase() + " " + s[n+1] + "ing in my ear.\n"))
});
p="...";a.map((m,n)=>{
  if(n==10) return;
  p+=s[n] + "ing like a" + (n==6?"n ":" ") + m.toLowerCase() + (n==9?"...\nthat's what I hear.":",\n")
});
console.log(p);

charredgrass

Posted 2016-07-19T04:01:10.603

Reputation: 935

a.map((n,m)=>n>9||(p+=s[n]...)) – Neil – 2016-07-19T09:16:14.037

Why don't you have to declare the variables with var? – OldBunny2800 – 2016-07-19T12:04:16.390

1@OldBunny2800 For the purposes of golfing, you're allowed to set global variables. (Don't do this in a recursive function though!) – Neil – 2016-07-19T12:26:59.517

1Your code doesn't work, I assume stack exchanged some letters in your base64 code. After the split I get ["ujA66Gq87O3N+W63NutrLOHLM7a7pqXrc7J2q", "", "bellow", "why2U="]. – lolesque – 2016-07-19T12:35:48.370

1Define c=console.log; at the beginning then use c() to save 6 bytes. Or just save the string in a variable and print it once with alert(). – lolesque – 2016-07-19T12:38:22.313

You can also use template strings to reduce concatenation and escaped newlines. – Not that Charles – 2016-07-19T15:39:44.643

it may save you a bit of bytes (and duplication of logic) if you start with n=1 instead of 0. – Not that Charles – 2016-07-19T15:44:14.510

... and i wonder if encoding the determiner ("a", "an", nil for Children) in the hashes saves bytes. – Not that Charles – 2016-07-19T15:46:47.037

1@lolesque The c=console.log doesn't work because log must have a this of console or it produces an error. (Unless it doesn't in some browsers/environments?) The idea to put it all in a string sounds good, though – apsillers – 2016-07-19T19:31:21.727

I think you could reduce it further by removing the double "I hear ", i.e. changing: ", what do you hear?\n "+((n>9)?"I hear children...\n":"I hear a" into ", what do you hear?\n I hear "+((n>9)?"children...\n":"a" – elias – 2016-07-21T10:37:03.773

7

///, 523 512 bytes

/_/\/\///:/ar_!/, what do you he:?
I he: _$/!a_#/ing in my e:.

_%/ing like a_&/, _*/,
_0/Pol: Be:_1/ion_2/ippopotamus_3/lamingo_4/ebra_5/oa _S/onstrictor_6/lephant_7/eopard_8/eacock_9/alrus_Q/ookeeper_R/trumpet/0&0$ l1 ro:#L1&L1$ h2 snort#H2&H2$ f3 flut#F3&F3$ z4 bray#Z4&Z4$ b5cS hiss#B5CS&B5CS$n e6 R#E6&E6$ l7 snarl#L7&L7$ p8 yelp#P8&P8$ w9 bellow#W9&W9$ zQ whistl#ZQ&ZQ!children...

...growl% pol: be:*ro:% l1*snort% h2*flut% f3*bray% z4*hiss% b5cS*R%n e6*snarl% l7*yelp% p8*bellow% w9...
that's what I he:.

Try it online!

608 bytes less than the actual message (1120), this is less than half of it (560)!

Erik the Outgolfer

Posted 2016-07-19T04:01:10.603

Reputation: 38 134

6

Dyalog APL, 387 bytes

⎕UCS¯2(219⌶)¯128+⎕UCS'øZýÓÁî°üÁ~`Û¯ß(4Õ+ÖjáïvXô ¶Dhkë ©4¹³`LxÖ4¢gͼ4ªBáDÚN¼ùV ÂÅF]@¸hÆà bKÚ¸_oQãÔÝ ¸$8§ú_ÔÈxÖ ~6*ãªd ¿ð>¥ÐB8þôÍxwÄ6Å
ô¡é¢wBlDµ¯ë
Ãbqè+ý+ÜÈýgu!gWËØ#0="«ë"HDÝÀV·¦/ÕMÆí}h<àì7å ÝÒëëñX³ýM <dÄ<ëmµñqP]¥c¬l¾¤ìÚã/$ÝÕqÙÞîCLéMÝÏ}OÔϤr$¤è©~ì2[¢{·YWÒ俦à¶)YØ©;s÷¬¥+ó&¿ÉâgËr
,Ýî©)¥Ö­2è´ÝÅd{úK5­·Õ}ýÚ'

To ease reading: ⎕UCS¯2(219⌶)¯128+⎕UCS'...'

⎕UCS '...' convert string to Unicode code points

¯128+ subtract 128 to get -128 ≤ n ≤ 127

¯2(219⌶) un-zlib

⎕UCS convert Unicode code points to string

The source string is the following 365 bytes of zlib'ed Unicode code points:

F8 5A FD D3 C1 EE 04 B0 8C FC C1 7E 60 DB AF 91 DF 28 34 D5 2B D6 6A E1 EF 15 76 96 58 F4 09 B6 44 11 93 04 68 6B EB A0 A9 94 34 B9 10 98 0F B3 60 4C 78 0C D6 91 1C 34 A2 89 67 CD BC 34 AA 42 95 E1 44 9E DA 4E BC 0B 0F F9 87 85 56 20 83 C2 C5 46 5D 40 B8 68 C6 E0 20 92 62 13 81 89 4B DA B8 5F 9A 6F 51 E3 D4 DD 9F A0 B8 24 38 A7 FA 5F D4 C8 78 7F D6 A0 7E 36 2A E3 AA 64 20 BF F0 3E A5 D0 42 9A 95 38 FE F4 CD 8A 78 99 77 C4 17 89 11 10 36 82 C5 0D 8A 9A F4 A1 12 E9 A2 92 77 9D 42 1E 6C 44 B5 AF EB 0D 04 C3 62 71 87 9C E8 2B FD 2B DC 04 C8 FD 67 75 21 67 57 04 CB D8 23 12 30 9A 3D 22 AB EB 22 48 9E 44 DD C0 56 B7 87 85 A6 2F D5 03 4D 9D C6 ED 7D 1E 68 3C E0 EC 37 9C 94 08 86 E5 09 DD D2 EB EB F1 58 B3 FD 4D 20 04 3C 17 64 C4 3C EB 6D B5 F1 11 89 71 50 5D A5 63 AC 6C 9A BE A4 EC DA E3 2F 24 DD D5 71 D9 DE EE 04 43 4C E9 4D DD CF 7D 4F 13 D4 CF 13 A4 72 24 A4 E8 1A 9E A9 7E EC 1F 32 5B 19 10 A2 7B B7 01 59 57 D2 E4 BF A6 E0 B6 29 94 59 D8 A9 3B 73 1D 94 9B F7 AC A5 2B F3 26 BF C9 E2 67 7F CB 72 0A 2C DD EE A9 29 A5 D6 AD 92 32 E8 B4 DD C5 64 7B FA 8A 4B 35 AD B7 D5 7D 82 0F FD 1 DA

Adám

Posted 2016-07-19T04:01:10.603

Reputation: 37 779

6

Python 3, 497 484 480 bytes

P=print
N=lambda m:"an"[:("E"==m[0])+1]+" "+m.lower()
h="I hear "
A=[a.split("|")for a in"Polar Bear|growl:Lion|roar:Hippopotamus|snort:Flamingo|flut:Zebra|bray:Boa Constrictor|hiss:Elephant|trumpet:Leopard|snarl:Peacock|yelp:Walrus|bellow:Zookeeper|whistl".split(":")]
for i in range(11):
 a,b=A[i]
 if i:P(h+N(a)+" "+b+"ing in my ear.\n")
 a+=", ";P(a+a+"what do you hear?")
P(h+"children...\n\n..."+",\n".join([z+"ing like "+N(y)for y,z in A[:-1]])+"...\nthat's what I hear.")

(Credit for 13 bytes saved should go to Gábor Fekete, and an additional 4 bytes were saved by Taylor Lopez.)

So you could probably guess I was going to use a language like Python as a teaching tool. This was the program before I started golfing it.

def startsWithVowel(name):
    firstLetter = name[0]
    return firstLetter in ["A", "E", "I", "O", "U"]

def aOrAn(name):
    return "an" if startsWithVowel(name) else "a"

animals = [
#    NAME (0),     SOUND (1)
    ("Polar Bear", "growling"),
    ("Lion", "roaring"),
    ("Hippopotamus", "snorting"),
    ("Flamingo", "fluting"),
    ("Zebra", "braying"),
    ("Boa Constrictor", "hissing"),
    ("Elephant", "trumpeting"),
    ("Leopard", "snarling"),
    ("Peacock", "yelping"),
    ("Walrus", "bellowing"),
    ("Robot Dragon", "screeching"),
    ("Owl", "hooting"),
    ("Monkey", "laughing"),    
    ("Zookeeper", "whistling")]

NAME = 0
SOUND = 1
for animalNumber in range(len(animals)):
    thisAnimal = animals[animalNumber]
    if animalNumber + 1 < len(animals):    
        nextAnimal = animals[animalNumber + 1] 
    else: 
        nextAnimal = None

    print("{n}, {n}, what do you hear?".format(n=thisAnimal[NAME]))

    if nextAnimal != None:
        print("I hear {a} {n} {s} in my ear.".format(n=nextAnimal[NAME].lower(),
                                                     s=nextAnimal[SOUND],
                                                     a=aOrAn(nextAnimal[NAME])))
    else:
        print("I hear children...")

        children = []        
        for animal in animals[:-1]:
            children.append("{s} like {a} {n}".format(n=animal[NAME].lower(), 
                                                      s=animal[SOUND],
                                                      a=aOrAn(animal[NAME])))
        print("...{}...".format(",\n".join(children)))
        print("that's what I hear.")

aaaantoine

Posted 2016-07-19T04:01:10.603

Reputation: 591

2You could use the unpacking syntax to save some bytes: change a=A[i] to a,b=A[i] and then you can write a and b instead of a[0] and a[1]. This will save 12 bytes. – Gábor Fekete – 2016-07-19T12:09:07.727

Changing N=lambda m:("a","an")["E"==m[0]]+" "+m.lower() to N=lambda m:"an"[:("E"==m[0])+1] and n=a[0]+", ";P(n+n+"what do you hear?") to a+=", ";P(a+a+"what do you hear?") will save 2 more bytes. – Gábor Fekete – 2016-07-19T12:19:00.460

General golfing question. Where you have len(A), since the purpose of this challenge is simply to generate the static output (not deal with dynamic input), is it acceptable to use a hard-coded 11 instead to save bytes? – Taylor Lopez – 2016-07-25T15:40:52.100

1@TaylorLopez sure, it's bad practice in general, but for golfing where the goal is to minimize code, I see no reason why not. – aaaantoine – 2018-02-19T18:58:25.263

5

Pyth - 427 384 Bytes

=G"1, 1, what do you hear?\nI hear a 2 in my ear.\n"=Hc"growling/Polar Bear/roaring/Lion/snorting/Hippopotamus/fluting/Flamingo/braying/Zebra/hissing/Boa Constrictor/trumpeting/Elephant/snarling/Leopard/yelping/Peacock/bellowing/Walrus/whistling/Zookeeper"\/FNT
::G\1@H+yN1\2++r@H+yN3Zd@H+yN2)p+::G"I(.|\n)*"k\1@H20"I hear children...\n\n..."FN9
::"1 like a 2,"\1@HyN\2r@H+yN1Z)p"bellowing like a walrus...\nthat's what I hear.

J"%s, %s, what do you hear?"K"I hear a%sing in my ear.\n"=Hc"Polar Bear/roar/Lion/snort/Hippopotamus/flut/Flamingo/bray/Zebra/hiss/Boa Constrictor/trumpet/Elephant/snarl/Leopard/yelp/Peacock/bellow/Walrus/whistl/Zookeeper/growl"\/FN11
%J*2[@HyN)?qNT"I hear children...\n"%Kjd[?qN5\nkr@H+yN2Z@HhyN))p"..."FN9
+%=J"%sing like a%s"[@HtyN+?qN5\nk+dr@HyNZ)?qN8"..."\,)
"that's what I hear"

Try it here - permalink

KoreanwGlasses

Posted 2016-07-19T04:01:10.603

Reputation: 888

Can you golf away the ings? I go crazy seeing PHP beat Pyth. – Titus – 2016-07-19T07:30:42.143

1The code outputs a elephant. – Antti29 – 2016-07-19T11:09:40.137

All the problems (including the fact that PHP beat Pyth) are fixed! – KoreanwGlasses – 2016-07-19T14:05:51.770

3

R 518 509 482 477 474 465 452 456 bytes

Link to R-Fiddle to try code

a=c("Polar Bear","Lion","Hippopotamus","Flamingo","Zebra","Boa Constrictor","Elephant","Leopard","Peacock","Walrus","Zookeeper")
b=c("...growl","roar","snort","flut","bray","hiss","trumpet","snarl","yelp","bellow","whistl")
d=c(rep("a ",6),"an ")
f=tolower(a)
cat(c(paste0(a,", ",a,", what do you hear?\nI hear ",c(paste0(d,f," ",b,"ing in my ear.")[-1],"children..."),"\n\n"),paste0(b,"ing like ",d,f,c(rep(",\n",9),"...\nthat's what I hear."))[-11]))
  • Moved children out of the vector a, and got rid of corresponding entry in the d vector to save 8 bytes
  • More tidying up and removing of subscripts made redundant by moving children, saved further 27 bytes.
  • Globalised the tolower function, saved 5 bytes
  • Replace writeLines with cat and reformatted appropriately (added \n in places) saved 3 bytes
  • Realised that if d is only 7 elements not the full 11, R will just loop back to the start again. As 11 < 14 then this works for us. Saved 9 bytes.
  • globalised subscripts, saved 13 bytes.
  • cat function was separating with " ", changed back to writeLines. Added 4 bytes (cat can be fixed by adding ,sep="" to the function)

Robert Maidstone

Posted 2016-07-19T04:01:10.603

Reputation: 31

Welcome to PPCG! This is a nice first answer. Is there a way to try your code online? – aloisdg moving to codidact.com – 2016-07-21T03:04:12.623

1

Try this http://www.r-fiddle.org/#/fiddle?id=5pqkHPyL&version=1

although I had to add a character (backslash) to get it to read the apostrophe in "that's" correctly

– Robert Maidstone – 2016-07-21T08:35:34.293

Thank you. In R-Fiddle, I saw that you have a ' ' before each item of a after "Polar Bear". Is it normal? – aloisdg moving to codidact.com – 2016-07-21T11:07:48.897

I'm not entirely sure what you mean. Do you mean the space in the first section of the poem? As in the space before "Lion" here? "Polar Bear, Polar Bear......\nI hear a ......\n Lion, Lion.....\nI hear a... " I hadn't noticed this before. It comes from the cat function separating using a space. This can be fixed by adding sep="" to the function, however then using writeLines becomes preferable. (I've change the code back to writeLines) – Robert Maidstone – 2016-07-21T11:40:49.367

3

C#, 575 525 520 526 507 504 497 494 493 bytes

()=>{var t="growl,Polar Bear,roar,Lion,snort,Hippopotamus,flut,Flamingo,bray,Zebra,hiss,Boa Constrictor,trumpet,Elephant,snarl,Leopard,yelp,Peacock,bellow,Walrus,whistl,Zookeeper".Split(',');string r="",s="",z="a ",n="an ";for(int i=0,j=0;i<21;r+=t[++i]+$", {t[i]}, what do you hear?\nI hear "+(i>19?@"children...

...":(i==11?n:z)+t[++i+1].ToLower()+$" {t[i]}ing in my ear.\n\n"))s+=j<20?t[j]+"ing like "+(j==12?n:z)+t[++j].ToLower()+(++j<20?@",
":@"...
"):"that's what I hear.";return r+s;};

C# lambda where the output is a string.

Explanation

  1. Init t as a string with the format noise,animal,noise,animal,... and split by ,.
  2. Declare r and s. r is the first part of the song and s the last part. z and n are here to handle Elephant.
  3. Walk t and build r and s in the same loop. Weird ternary+interpolated stuff.
  4. Return the first part of the song followed by the last part.

Code

()=>{
    var t="growl,Polar Bear,roar,Lion,snort,Hippopotamus,flut,Flamingo,bray,Zebra,hiss,Boa Constrictor,trumpet,Elephant,snarl,Leopard,yelp,Peacock,bellow,Walrus,whistl,Zookeeper".Split(',');
    string r="",s="",z="a ",n="an ";
    for(int i=0,j=0;i<21;r+=t[++i]+$", {t[i]}, what do you hear?\nI hear "+(i>19?@"children...

...":(i==11?n:z)+t[++i+1].ToLower()+$" {t[i]}ing in my ear.\n\n"))
        s+=j<20?t[j]+"ing like "+(j==12?n:z)+t[++j].ToLower()+(++j<20?@",
":@"...
"):"that's what I hear.";
    return r+s;
};

Try it online!

aloisdg moving to codidact.com

Posted 2016-07-19T04:01:10.603

Reputation: 1 767

3

Batch, 650 647 bytes

@echo off
set e=echo(
set s=shift
call:d a "polar bear" ...growl "Polar Bear" a lion roar Lion a hippopotamus snort Hippopotamus a flamingo flut Flamingo a zebra bray Zebra a "boa constrictor" hiss "Boa Constrictor" an elephant trumpet Elephant a leopard snarl Leopard a peacock yelp Peacock a walrus bellow
exit/b
:d
call:v %* Walrus a zookeeper whistl Zookeeper
%e%I hear children...
%e%
:l
%e%%3ing like %1 %~2,
%s%
%s%
%s%
%s%
if not "%5"=="" goto l
%e%%3ing like a %2...
%e%that's what I hear.
exit/b
:v
%e%%~4, %~4, what do you hear?
if "%5"=="" exit/b
%e%I hear %5 %~6 %7ing in my ear.
%e%
%s%
%s%
%s%
%s%
goto v

Because %* is the nearest thing Batch has to an array. If I can use Polar bear and Boa constrictor then I can save 10%... but I'm still more than 50% of the original text...

Edit: Saved 3 bytes by setting e=echo( with a ( instead of a space, which allows me to use it to echo blank lines, although I then have to write out @echo off in full.

Neil

Posted 2016-07-19T04:01:10.603

Reputation: 95 035

3

Python 2 - 454 bytes

a="polar bear,lion,hippopotamus,flamingo,zebra,boa constrictor,elephant,leopard,peacock,walrus,zookeeper,whistl,bellow,yelp,snarl,trumpet,hiss,bray,flut,snort,roar,growl".split(',')
e='...\n\n'
r=range
print'\n'.join([(a[i].title()+', ')*2+"what do you hear?\nI hear "+((i<10)*("a%s %sing in my ear.\n"%("n "[i!=5:]+a[i+1],a[~-~i]))or"children%s..."%e+",\n".join(a[~j]+"ing like a"+"n "[j!=6:]+a[j]for j in r(10))+e+"that's what I hear.")for i in r(11)])

Cowabunghole

Posted 2016-07-19T04:01:10.603

Reputation: 1 590

3

C#, 592 572 Bytes

using System;class p{static void Main(){string[] s={"","","Polar Bear","Lion","Hippopotamus","Flamingo","Zebra","Boa Contrictor","Elephant","Leopard","Peacock","Walrus","Zookeeper","growl","roar","snort","flut","bray","hiss","trumpet","snarl","yelp","bellow","whistl"};for(int i=2;i<13;i++){s[0]+=(s[i]+", "+s[i]+", what do you hear?\nI hear "+(i<12?"a"+(i==7?"n ":" ")+s[i+1].ToLower()+" "+s[i+12]+"ing in my ear.\n\n":"children...\n\n..."));if(i<12)s[1]+=s[i+11]+"ing like a"+(i==8?"n ":" ")+s[i].ToLower()+(i<11?",\n":"...\nthat's what I hear.\n");}Console.Write(s[0]+s[1]);}}

Had such a great time taking this challenge with my colleague! Thanks for the idea.

Formatted:

using System;
class p {
    static void Main() {
        string[] s = { "", "", "Polar Bear", "Lion", "Hippopotamus", "Flamingo", "Zebra", "Boa Contrictor", "Elephant", "Leopard", "Peacock", "Walrus", "Zookeeper", "growl", "roar", "snort", "flut", "bray", "hiss", "trumpet", "snarl", "yelp", "bellow", "whistl" };
        for (int i = 2; i < 13; i++) {
            s[0] += (s[i] + ", " + s[i] + ", what do you hear?\nI hear " + (i < 12 ? "a" + (i == 7 ? "n " : " ") + s[i + 1].ToLower() + " " + s[i + 12] + "ing in my ear.\n\n" : "children...\n\n..."));
            if (i < 12) s[1] += s[i + 11] + "ing like a" + (i == 8 ? "n " : " ") + s[i].ToLower() + (i < 11 ? ",\n" : "...\nthat's what I hear.\n");
        }
        Console.Write(s[0] + s[1]);
        Console.ReadKey();
    }
}

EDIT: Thank you for your numerous and awesome tips, they helped a lot and I'll try to get the other ones working as well.

Derpcode

Posted 2016-07-19T04:01:10.603

Reputation: 31

1Remove all of the unnecessary whitespace, you can use new[] instead o. new string[] Also you can make this into an anonymous function like in @aloisdg's answer – TheLethalCoder – 2016-07-20T14:54:46.383

Welcome to PPCG! Good idea in this answer! You may find some inspiration to improve it in the tips for code golfing in C# page. Keep going!

– aloisdg moving to codidact.com – 2016-07-20T16:44:23.800

1You fell in the a elephant trap (I did too). It is an elephant ;) – aloisdg moving to codidact.com – 2016-07-20T16:46:55.047

Take out your "ing"s in the verb array and move it to the output for some more savings. – GuitarPicker – 2016-07-21T04:58:05.043

2

F#, 591 589 579 576 573 567 552 bytes

This is my first try at code golfing with a language i like. I bet there are some ways this could be made shorter. Runs in FSI, so no need for .NET boilerplate.

Edit: Shaved 10 bytes by removing \r. It still renders fine in VSCode so go figure. Cut another three bytes with function composition, and another three with a lambda, then six with a for loop instead of Seq.iter (getting rid of the lambda). Finally 15 bytes were cut by rearranging a(s:string)

let A="Polar Bear,Lion,Hippopotamus,Flamingo,Zebra,Boa Constrictor,Elephant,Leopard,Peacock,Walrus,Zookeeper".Split(',')
let S="growl,roar,snort,flut,bray,hiss,trumpet,snarl,yelp,bellow,whistl".Split(',')
let a(s:string)=(if s.[0]='E'then"an "else"a ")+s.ToLower()
let f i=sprintf"%s, %s, what do you hear?\nI hear "A.[i]A.[i]
for i in 0..9 do printfn"%s%s %sing in my ear.\n"(f i)(a A.[i+1])S.[i+1]
printf"%schildren...\n\n..."(f 10)
let t i=sprintf"%sing like %s"S.[i](a A.[i])
Seq.iter(t>>printfn"%s,")[0..8]
printfn"%s...\nthat's what I hear."(t 9)

asibahi

Posted 2016-07-19T04:01:10.603

Reputation: 371

3Welcome to PPCG, nice answer! – cat – 2016-07-19T13:28:29.353

I know #F is a .net languange, but I think for the purpose of this challenge you can replace the "\r\n" with a simple "\n", as the concept is the same and it saves bytes – Vale – 2016-07-19T13:33:20.260

@Vale thanks. saved 10 bytes – asibahi – 2016-07-19T13:39:22.230

1Doesn't affect the count, but you've spelled "Hippopotamus" wrong. – GentlePurpleRain – 2016-07-19T20:16:21.300

@GentlePurpleRain Heh. I thought I looked for all the spellings. I will fix it. – asibahi – 2016-07-19T20:20:34.710

2

Bash + zcat, 402 bytes

Just a joke:
a 2 lines bash script that tails itself and pipe the second line to zcat.
The second line is the gzipped text.

How to prepare it: all the text in a file a. Then

echo "tail -n+2 \$0|zcat;exit" > go.sh
gzip a ;
cat a.gz >> go.sh
chomod u+x go.sh

The file so created when executed returns the starting text, 402 Bytes.

Hastur

Posted 2016-07-19T04:01:10.603

Reputation: 277

Can you post the actual code? 402 bytes isn't that much (i.e. you can post it.) – Erik the Outgolfer – 2016-07-19T14:21:55.450

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ The code is only tail -n+2 \$0|zcat;exit followed by a newline and a binary string of 379 bytes (the gzipped version of the text proposed). Did you know the reason for the downvote? (it's a semi standard procedure for bash self installing scripts with an archive inside, IMHO not so different from the use of a library in c++). – Hastur – 2016-07-19T15:09:57.617

It seems you use coreutils (zcat), so your header must be (Bash + coreutils, 402 bytes) instead of (Bash (with zcat) 402). And, can you edit your answer (just append <!> at the end of your post)? I want to remove the downvote >:( – Erik the Outgolfer – 2016-07-19T15:15:07.297

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ zcat is not from coreutils, it comes with gzip. In many system is a script with that calls gzip -cd "$@"... BTW I modified in Bash + zcat, 402 bytes. – Hastur – 2016-07-19T15:22:00.537

Good, downvote removed. The upvote is mine. – Erik the Outgolfer – 2016-07-19T15:25:18.423

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Thx I went one of your question with a similarly lazy answer... – Hastur – 2016-07-19T16:19:03.430

It's called "Count up folks!" (discussion ends) – Erik the Outgolfer – 2016-07-19T16:25:03.447

1

Japt, 308 303 299 295 288 280 294 289 286 bytes

Contains a bunch of unprintables; follow the link below to view them.

`Pol BÁLiyHippopotam«yFlaÚÁoyZeßBoa CÆqÎtyE¤pÊCyLeopÂýPea¬ckyWalr«yZookeep`qy
`gwÓ2ÂüÍdfl©dßdÊdtruÛFdsnÓ)lpdÞ)owdØtl`qd
[¡[X',SX`, Ø º y Ê#?
I Ê# `Y<A?[Y¶5?``:'aSUg°Y v SVgY `g  my e.`R]¬:[`å,Á`Q='.³R²QU¯J £[Vv `g ¦ke `Y¶6?``:'aSXv]¬Ãq`,
` QR`È  's Ø I Ê#.`]¬]¬Ã·]¬

Test it

+14 bytes 'cause I'd ballsed up the walrus' line; will need to take another pass over it next week to see if I can get any of those bytes back.

Shaggy

Posted 2016-07-19T04:01:10.603

Reputation: 24 623

1

Powershell 921 889 886 898 Bytes

it's not perfect, but it saves 300 Bytes :)

EDIT: Thanks Jonathan Frech, i saved 32 Bytes. And thank you Veskah for correcting the Output.

filter Z($1,$2){while($1){$x,$1=$1
$y,$2=$2
[tuple]::Create($x,$y)}}
$0="ing"
$$="hear"
$1="I $$ a "
$3='in my ear.'
$a='Polar Bear'
$b='Lion'
$c='Hippopotamus'
$d='Flamingo'
$e='Zebra'
$f='Boa Constrictor'
$g='Elephant'
$h='Leopard'
$i='Peacock'
$j='Walrus'
$k='Zookeeper'
$v="children"
$2="roar$0"
$4="snort$0"
$5="flut$0"
$6="bray$0"
$7="hiss$0"
$8="trumpet$0"
$9="snarl$0"
$x="yelp$0"
$y="bellow$0"
$^="whistl$0"
$l="$1$b $2$3"
$m="$1$c $4$3"
$n="$1$d $5$3"
$o="$1$e $6$3"
$p="$1$f $7$3"
$q="I $$ an $g $8$3"
$r="$1$h $9$3"
$s="$1$i $x$3"
$t="$1$j $y$3"
$u="$1$k $^$3"
$z=' like a '
$w="I $$ $v..."
z $a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k $l,$m,$n,$o,$p,$q,$r,$s,$t,$u,$w|%{"$($_.item1),"*2+"what do you $$?";$_.item2;""}
"...growl$0$z$a,"
z $b,$c,$d,$e,$f $2,$4,$5,$6,$7|%{$_.item2+$z+$_.item1+","}
"$8 like an $g,"
z $h,$i $9,$x,$y|%{$_.item2+$z+$_.item1+","}
$y+$z+"Walrus..."
"that's what I $$."

Add-TheNewOne

Posted 2016-07-19T04:01:10.603

Reputation: 21

Would not using a standard 7 bit ASCII character instead of an ö be more byte efficient? – Jonathan Frech – 2019-02-22T16:41:49.040

Furthermore, I think there is some superfluous whitespace in your first line, along with a long function name. – Jonathan Frech – 2019-02-22T16:42:47.650

Thank you for the hints :)! (I used the Ö just because taught i used already all useable ASCII signs XD) – Add-TheNewOne – 2019-02-25T08:11:45.160

The character ö is only represented using a single byte in some codepages, UTF-8 requires two bytes for this character. – Jonathan Frech – 2019-02-25T19:25:04.260

Your output is a bit off. The last stanza repeats polar-bear which makes everything off by one and you include whistling which isn't needed. It's also missing an ellipses. It also writes an elephant There's also an extra line break between the earlier stanzas that can be axed by removing the "n". – Veskah – 2019-02-25T21:40:47.057

Oh yeah, animals on the I hear a $_ $_ing in my ear and in the last stanza aren't capitalized. Edit to the previous comment because I just noticed: I meant to write it uses a Elephant in the last stanza – Veskah – 2019-02-25T22:11:09.270

876b with less bugs – Veskah – 2019-02-25T22:31:00.840

First of all thank you for improving the script!!! I corrected the things you have written, but the Code is still 898b long.(Now it gives you the correct Output ;) ) And the part with the walrus is shorter just with text XD. If you have another great idea, pls share it. – Add-TheNewOne – 2019-02-26T11:08:26.907

1

Emacs Lisp, 576 (621) bytes

(let*((a'("polar bear""lion""hippopotamus""flamingo""zebra""boa constrictor""elephant""leopard""peacock""walrus""zookeeper"))(l(length a))(m(- l 1))(s'("growl""roar""snort""flut""bray""hiss""trumpet""snarl""yelp""bellow""whistl")))(dotimes(i l)(message"%s, what do you hear?"(let((a(capitalize(nth i a))))(concat a", "a)))(if(not(eq i m))(message "I hear a %s %sing in my ear.\n"(nth(1+ i)a)(nth(1+ i)s))(message"I hear children...\n")(dotimes(j m)(message(concat(when(eq j 0)"...")"%sing like a %s"(if(eq(1+ j)m)"..."","))(nth j s)(nth j a)))(message"That's what I hear."))))

When fixing "an elephant", it takes slightly longer:

(let*((a'("polar bear""lion""hippopotamus""flamingo""zebra""boa constrictor""elephant""leopard""peacock""walrus""zookeeper"))(l(length a))(m(- l 1))(s'("growl""roar""snort""flut""bray""hiss""trumpet""snarl""yelp""bellow""whistl")))(dotimes(i l)(message"%s, what do you hear?"(let((a(capitalize(nth i a))))(concat a", "a)))(if(not(eq i m))(message "I hear a %s %sing in my ear.\n"(nth(1+ i)a)(nth(1+ i)s))(message"I hear children...\n")(dotimes(j m)(message(concat(when(eq j 0)"...")"%sing like a"(and(string-match-p"^[aeiou]"(nth j a))"n")" %s"(if(eq(1+ j)m)"..."","))(nth j s)(nth j a)))(message"That's what I hear."))))

Ungolfed:

(let* ((animals '("polar bear"
                  "lion"
                  "hippopotamus"
                  "flamingo"
                  "zebra"
                  "boa constrictor"
                  "elephant"
                  "leopard"
                  "peacock"
                  "walrus"
                  "zookeeper"))
       (l (length animals))
       (m(- l 1))
       (sounds '("growl"
                 "roar"
                 "snort"
                 "flut"
                 "bray"
                 "hiss"
                 "trumpet"
                 "snarl"
                 "yelp"
                 "bellow"
                 "whistl")))
  (dotimes (i l)
    (message "%s, what do you hear?"
             (let ((animal (capitalize (nth i animals))))
               (concat animal ", " animal)))
    (if (not (eq i m))
        (message "I hear a %s %sing in my ear.\n"
                 (nth (1+ i) animals)
                 (nth (1+ i) sounds))
      (message "I hear children...\n")
      (dotimes (j m)
        (message
         (concat
          (when (eq j 0) "...")
          "%sing like a"
          (and (string-match-p"^[aeiou]" (nth j animals)) "n")
          " %s"
          (if (eq (1+ j) m) "..." ","))
         (nth j sounds )
         (nth j animals)))
      (message"That's what I hear."))))

Lord Yuuma

Posted 2016-07-19T04:01:10.603

Reputation: 587

Your regex could be shortened from ^[aeiou] to ^e, couldn't it? – owacoder – 2016-07-19T16:36:26.300

For the elephant yes, but if other animals were added it would need to change. With 600 bytes already, 6 bytes don't hurt that much. – Lord Yuuma – 2016-07-19T22:23:55.520

1

C, 596 bytes

Call f() without any arguments. This is not the best golf in the world, I probably can shrink it more.

f(n){char*t,a[99][99]={"Polar Bear","Lion","Hippopotamus","Flamingo","Zebra","Boa Constrictor","Elephant","Leopard","Peacock","Walrus","Zookeeper","growl","roar","snort","flut","bray","hiss","trumpet","snarl","yelp","bellow","whistl"};for(n=0;n<11;){strcpy(t=a[n+30],n^6?" ":"n ");strcat(t,a[n++]);for(;*t=tolower(*t);++t);}for(n=0;printf("%s, %s, what do you hear?\n",a[n],a[n]),n<10;++n)printf("I hear a%s %sing in my ear.\n\n",a[n+31],a[12+n]);puts("I hear children...\n");for(n=11;n<21;++n)printf("%s%sing like a%s%s\n",n^11?"":"...",a[n],a[n+19],n^20?",":"...");puts("that's what I hear.");}

Try it on ideone.

owacoder

Posted 2016-07-19T04:01:10.603

Reputation: 1 556

Can you add a link to ideone? – aloisdg moving to codidact.com – 2016-07-19T13:49:49.417

2Added ideone link. – owacoder – 2016-07-19T13:52:41.973

a[99][99] -> **a (-6). You can't call f() without arguments here, you need an n. Replace f(n){ with f{n;. Another -1 here. Also, f() is now callable. – Erik the Outgolfer – 2016-07-19T15:28:34.520

@owacoder How come? **a means an array of character arrays (or a character pointer pointer), and, to me, it has always worked (gcc 4.8). What compiler do you use? If you don't use gcc, you must specify it. If you use gcc, it's a default. – Erik the Outgolfer – 2016-07-19T15:56:24.553

@owacoder No! It makes an array that fits 98 strings of length 98! And you should definitely not call your ideone link "Try it online!" To golf, replace a[99][99] with a[<how many elements do I modify?>+1][<what is the maximum length of any string in here?>+1]. – Erik the Outgolfer – 2016-07-19T16:07:29.397

@owacoder I think the 99 in a[99][99] means 99 elements, including the null (\0), so [0]-[97] are available. And I really don't believe that 99 is the number of elements you actually need. – Erik the Outgolfer – 2016-07-19T16:18:51.447

1

Python 3, 442 441 bytes

h=t=''
for n,s in zip('polar bear,lion,hippopotamus,flamingo,zebra,boa constrictor,elephant,leopard,peacock,walrus,zookeeper'.split(','),'...growl roar snort flut bray hiss trumpet snarl yelp bellow whistl'.split()):u='n'[:'el'in n],n,s,n.title();h+="I hear a{0} {1} {2}ing in my ear.\n\n{3}, {3} what do you hear?\n".format(*u);t+="{2}ing like a{0} {1},\n".format(*u)
print((h+'I hear children...\n\n'+t)[44:-30]+"...\nthat's what I hear.")

ungolfed:

animals = 'polar bear,lion,hippopotamus,flamingo,zebra,boa constrictor,elephant,leopard,peacock,walrus,zookeeper'.split(',')

sounds = '...growl roar snort flut bray hiss trumpet snarl yelp bellow whistl'.split()

h=t=''
for n,s in zip(animals,sounds):
    u='n'[:'el'in n], n, s, n.title()

    h+="I hear a{0} {1} {2}ing in my ear.\n\n{3}, {3} what do you hear?\n".format(*u)

    t+="{2}ing like a{0} {1},\n".format(*u)

print((h+'I hear children...\n\n'+t)[44:-30]+"...\nthat's what I hear.")

Basically, just a loop that builds up two strings representing the two parts of the story. The 'n'[:'el'in n] handles the "an" for elephant. The [44:-30] chops off the leading "I hear a polar bear growling in my ear" and the trailing "whistling like a zookeeper".

RootTwo

Posted 2016-07-19T04:01:10.603

Reputation: 1 749

1

QB64 (QuickBASIC), 581 bytes

The code expands a bit when you throw it in the interpreter, but this source file is valid to load as-is. If you want to see the whole output before it scrolls past, then you'll need to add a width 80,46 statement to the beginning.

READ a$,v$
FOR x=0 TO 10
?a$+", "+a$+", what do you hear?"
IF x>9THEN
?"I hear children...":?:?"...";
RESTORE
FOR y=0 TO 9
READ a$,v$
?v$+"ing like ";
CALL j(a$)
IF y<9THEN?", "ELSE?"...":?"that's what I hear."
NEXT
END
ELSE
READ a$,v$
?"I hear ";
CALL j(a$)
?" "+v$+"ing in my ear."
?
END IF
NEXT
DATA"Polar Bear","growl","Lion","roar","Hippopotamus","snort","Flamingo","flut","Zebra","bray","Boa Constrictor","hiss","Elephant","trumpet","Leopard","snarl","Peacock","yelp","Walrus","bellow","Zookeper","whistl"
SUB j (A$)
?"a";
IF LEFT$(A$,1)="E"THEN?"n";
?" "+LCASE$(A$);
END SUB

GuitarPicker

Posted 2016-07-19T04:01:10.603

Reputation: 1 101

1I know this is kinda late, but: I think you can save some bytes by using GOSUB/RETURN instead of CALL/SUB/END SUB. Also, you can drop the quotes in DATA for all the entries that don't have spaces in them. Finally, since there's only one animal that starts with a vowel, A$="Elephant" is actually 1 byte shorter than LEFT$(A$,1)="E". Nice use of RESTORE, BTW! – DLosc – 2018-02-14T08:07:37.723

1

LUA 535 bytes

p=print a="growl.roar.snort.flut.bray.hiss.trumpet.snarl.yelp.bellow.whist"b="polar bear.lion.hippopotamus.flamingo.zebra.boa constrictor.elephant.leopard.peacock.walrus.zookeeper."z=a.gmatch(a,"%P+")x=b.gmatch(b,"%P+")w=''for j=1,11 do i=x()v=z()e=j==7 and'n 'or' 'p(j==1 and''or'I hear a'..e..i..' '..v..'ing in my ear.\n')w=w..(j>10 and''or v..'ing like a'..e..i..(j>9 and'...'or',')..'\n')y=i:gsub("^%l",a.upper):gsub("%s%l",a.upper)p(y..', '..y..' what do you hear?')end p('I hear children...\n')p('...'..w.."that's what I hear.")

ungolfed:

sound_list = "growl.roar.snort.flut.bray.hiss.trumpet.snarl.yelp.bellow.whist"
animal_list = "polar bear.lion.hippopotamus.flamingo.zebra.boa constrictor.elephant.leopard.peacock.walrus.zookeeper."

sound_it = string.gmatch(sound_list, "%P+")
animal_it = string.gmatch(animal_list, "%P+")
part_2 = ''

for i = 1, 11  do
    animal = animal_it()
    sound = sound_it()
    aORan = i == 7 and 'n ' or ' '

    print(i == 1 and '' or 'I hear a'..aORan..animal..' '..sound..'ing in my ear.\n')

    part_2 = part_2..(i > 10 and '' or sound..'ling like a'..aORan..animal..(i > 9 and '...' or ',')..'\n')

    big_animal = animal:gsub("^%l", string.upper):gsub("%s%l", string.upper)
    print(big_animal..', '..big_animal..' what do you hear?')
end

print('I hear children...\n')
print('...'..part_2.."that's what I hear.")

Try it online

CHlM3RA

Posted 2016-07-19T04:01:10.603

Reputation: 21

1

PHP, 366 bytes

Lazy answer, but why write a custom decompressor when gzip is available?

Hex dump of PHP code (can be saved with xxd -r)

0000000: 3c3f 3d67 7a69 6e66 6c61 7465 2827 7d53  <?=gzinflate('}S
0000010: c16a 8430 10bd e72b e6d6 cbe0 2f14 b6b4  .j.0...+..../...
0000020: b4d0 c3de 0abd 8d6e baca c64c 1823 62bf  .......n...L.#b.
0000030: be51 3354 1472 58f3 76de f864 e6bd 5cd9  .Q3T.rX.v..d..\.
0000040: 91c0 c592 20ec f1d4 5284 1bc3 cc23 b4a9  .... ...R....#..
0000050: f26c 3ed6 1308 5cc7 1e84 493a 7f87 ce43  .l>...\...I:...C
0000060: 3f43 222a 633e 1381 b03d 0bef b75d 081c  ?C"*c>...=...]..
0000070: 3852 3f0e 3078 9678 147a df75 20ec ff15  8R?.0x.x.z.u ...
0000080: 857f 1cf5 498a 1318 4f9a 6f99 4450 54d4  ....I...O.o.DPT.
0000090: fab5 b510 a4df 7c14 fa5e 1884 7c14 246a  ......|..^..|.$j
00000a0: 2668 d80f 51ba 26b2 a4b9 87e1 2876 6182  &h..Q.&.....(va.
00000b0: 97ff 1e84 63a1 f001 0fd6 d9d0 928f 1065  ....c..........e
00000c0: ec83 3dcd fc9a 7904 4565 632d 0792 5bf2  ..=...y.Eec-..[.
00000d0: 84c4 9dcc dd48 0405 25a5 60a9 e1e6 01b3  .....H..%.`.....
00000e0: 75e1 2874 dd38 0405 25a1 899c a494 d4d6  u.(t.8..%.......
00000f0: 399e 8e4a 5f2b 89a0 67c9 4ee6 87b5 c10a  9..J_+..g.N.....
0000100: 4cc9 86e8 4ea6 2a8f a0b0 b4fb a6ed dc4d  L...N.*........M
0000110: acaf aaf4 6e7a dc85 a755 d375 0fbb ccbf  ....nz...U.u....
0000120: dea4 3ab5 a211 2651 2adf 1e34 1a7b adb6  ..:...&Q*..4.{..
0000130: fb8c 1bcd 6f26 35d7 6896 3c2a a121 45a3  ....o&5.h.<*.!E.
0000140: c1ca d543 eed0 683a b465 971c 34d9 6ca5  ...C..h:.e..4.l.
0000150: 3404 68d4 3b1d 29bb 65b2 17ca a847 cb2a  4.h.;.).e....G.*
0000160: 624b f169 d8d6 b66d aa32 7f27 293b       bK.i...m.2.');

I used a few iterations of zopfli to convert the source text to 349 bytes of compressed data, avoiding the ' character which would otherwise have to be escaped with backslashes.

1133261

Posted 2016-07-19T04:01:10.603

Reputation: 137

0

C (clang), 552 bytes

(*P)()=printf;l(char*s){for(;*s;s++)putchar(*s>64?*s|32:*s);}char*a[]={"Zookeeper","Walrus","Peacock","Leopard","Elephant","Boa Constrictor","Zebra","Flamingo","Hippopotamus","Lion","Polar Bear"},*s[]={"whistl","bellow","yelp","snarl","trumpet","hiss","bray","flut","snort","roar","growl"};f(i){for(i=11;i--;)P("%s, %s, what do you hear?\nI hear%s ",a[i],a[i],i?i^5?" a":" an":""),i?l(a[i-1]):0,P(i?" %sing in my ear.\n\n":"children...\n\n...",s[i-1]);for(i=11;--i;)P("%sing like a%s ",s[i],i^4?"":"n"),l(a[i]),P(i-1?",\n":"...\nthat's what I hear.");}

Try it online!

gastropner

Posted 2016-07-19T04:01:10.603

Reputation: 3 264

537 bytes – ceilingcat – 2019-02-22T12:59:20.467

0

Perl 5, 413 bytes

@t=('Polar Bear',growl,Lion,roar,Hippopotamus,snort,Flamingo,flut,Zebra,bray,'Boa Constrictor',hiss,Elephant,trumpet,Leopard,snarl,Peacock,yelp,Walrus,bellow,Zookeeper,whistl);say$_=$t[$i],", $_, what do you hear?
I hear ",/Zo/?"children...
":"a".n x(/C/).lc" $t[$i+=2] $t[$i+1]ing in my ear.
"while!/Zo/;pop@t;pop@t;print'...';say+(shift@t)."ing like a ".lc.(@t?",":'...')while$_=shift@t;say"that's what I hear."

Try it online!

Xcali

Posted 2016-07-19T04:01:10.603

Reputation: 7 671

0

JavaScript, 424 bytes

f=(x=0,a=btoa`>Z¯ ^j¼Ëó*i¢-jk¬ÌYZ)à£6^n¶³²
춸¶óW©©íÌ·¨¥ªÝÌ÷r$Íf¥®ë3f$yê^¯0`[s=`split`]`y`.join` `[s]`z`,g=z=>n[z]+`ing like `+h(17)+l(z)+(z>9?`...
that's what I hear.`:`,
`+g(++z)),h=m=>++x%m?`a `:`an `,l=y=>a[y].toLowerCase(n=btoa`º0:èj¼ìíÍùn·6ëk,áË3¶»¦¥ës²v«<ÛzYhÃ<!ËeÌ`[s]`z`))=>a[x]+`, ${a[x]}, what do you hear?
I hear `+(x>9?`children...

...`+g(0):h(6)+l(x)+` ${n[x]}ing in my ear.

`+f(x))

Test it

Shaggy

Posted 2016-07-19T04:01:10.603

Reputation: 24 623

0

Pyth, 342 bytes

L:b"a e""an e"y>sm.F"
I hear a {1} {0} in my ear.

{2}, {2}, what do you hear?"+dr3edJC,+R"ing"c"growl
roar
snort
flut
bray
hiss
trumpet
snarl
yelp
bellow
whistl"bc"polar bear
lion
hippopotamus
flamingo
zebra
boa constrictor
elephant
leopard
peacock
walrus
zookeeper"b42"I hear children...
"jPPysm+j" like a "d",
"PJc2*6\."that's what I hear.

Try it online here.

Explanation to follow.

Sok

Posted 2016-07-19T04:01:10.603

Reputation: 5 592

0

Perl 6, 400 399 bytes

((my \a=<<"Polar Bear"Lion Hippopotamus Flamingo Zebra"Boa Constrictor"Elephant Leopard Peacock Walrus Zookeeper>>)>>.&{"$_, $_, what do you hear?
I hear a {a[++$!].lc} {($/=<growl roar snort flut bray hiss trumpet snarl yelp bellow whistl>)[$!]}ing in my ear.
"},"...{a[^10]>>.&{$/[$++]~"ing like a",.lc}.join(",
")}...
that's what I hear.")>>.trans(["a e",/a\s\s.*r/]=>["an e","children.."])>>.say

Try it online!

Sub-400 bytes!

Jo King

Posted 2016-07-19T04:01:10.603

Reputation: 38 234

0

clojure, 526 bytes

(use 'clojure.string)(let[l lower-case
a(partition 2(split"Polar Bear,...growl,Lion,roar,Hippopotamus,snort,Flamingo,flut,Zebra,bray,Boa Constrictor,hiss,Elephant,trumpet,Leopard,snarl,Peacock,yelp,Walrus,bellow,Zookeeper,whistl,children,x"#","))b(map(fn[[w x][y e]][(str
w", "w", what do you hear?
I hear a "(l y)" "e"ing in my ear.

")(str x"ing like a "(l w))])a(rest a))r
replace](print(r(str(r(join""(map first b))#".*x.*""I hear children...")(join",
"(butlast(map last b)))"...
that's what I hear.")#"(?i)a(?= e)""an")))

Here's my initial attempt. Gotta love the formatting and how unreadable it is. Hope the warnings from use 'clojure.string are acceptable.

Try it online.

Formatted code:

(use 'clojure.string)
(let [animal-sound (partition 2 (split "Polar Bear,...growl,Lion,roar,Hippopotamus,snort,Flamingo,flut,Zebra,bray,Boa Constrictor,hiss,Elephant,trumpet,Leopard,snarl,Peacock,yelp,Walrus,bellow,Zookeeper,whistl,children,x" #","))
      sentences (map (fn [[animal-1 sound-1] [animal-2 sound-2]]
                       [(str animal-1 ", " animal-1 ", what do you hear?\nI hear a "
                             (lower-case animal-2) " " sound-2 "ing in my ear.\n\n") (str sound-1 "ing like a " (lower-case animal-1))])
                     animal-sound (rest animal-sound))]
  (print (replace (str
                    (replace (join "" (map first sentences)) #".*x.*" "I hear children...")
                    (join ",\n" (butlast (map last sentences)))
                    "...\nthat's what I hear.") #"(?i)a(?= e)" "an")))

Chris F

Posted 2016-07-19T04:01:10.603

Reputation: 81

0

Java, 571 555 538 or 516 Bytes

String p(){String r="",z="...",b,x;String[]a="Polar Bear!Lion!Hippopotamus!Flamingo!Zebra!Boa Constrictor!Elephant!Leopard!Peacock!Walrus!Zookeeper!growling!roaring!snorting!fluting!braying!hissing!trumpeting!snarling!yelping!bellowing!whistling".split("!");for(int i=1;i<11;i++){b=i==6?"n ":" ";x=a[i-1];z+=a[i+10]+" like a"+b+x+(i==10?"...":"\n");r+=x+" , "+x+", what do you hear?\n I hear a"+b+a[i].toLowerCase()+" "+a[i+11]+" in my ear.\n\n";}r+=a[10]+" what do you hear?\n\tI hear children...\n"+z+"\nthat's what I hear.";return r;}

But only 516 bytes is required to get result in JShell

String r="",z="...",b,x;String[]a="Polar Bear!Lion!Hippopotamus!Flamingo!Zebra!Boa Constrictor!Elephant!Leopard!Peacock!Walrus!Zookeeper!growling!roaring!snorting!fluting!braying!hissing!trumpeting!snarling!yelping!bellowing!whistling".split("!");for(int i=1;i<11;i++){b=i==6?"n ":" ";x=a[i-1];z+=a[i+10]+" like a"+b+x+(i==10?"...":"\n");r+=x+" , "+x+", what do you hear?\n I hear a"+b+a[i].toLowerCase()+" "+a[i+11]+" in my ear.\n\n";}r+=a[10]+" what do you hear?\n\tI hear children...\n"+z+"\nthat's what I hear."

user902383

Posted 2016-07-19T04:01:10.603

Reputation: 1 360

It's giving incorrect output regarding spaces, tabs, lowercase and an vs a.. I've fixed and golfed it to 507 bytes

– Kevin Cruijssen – 2018-02-14T13:32:55.777

@KevinCruijssen your code is missing the "ing" of "I hear a ... ...ing in my ear". Also, very likely golfable by starting i with 0 up to 10 changing b=a[i-1] with b=a[i++] and removing the increment where it currently is. – Olivier Grégoire – 2018-02-16T09:53:02.967

0

Haskell 537 499 497 Bytes

import Data.Char
a&b=a++b
b=putStr
c=concat
d=init
e('E':s)="an e"&s
e s="a "&map toLower s
f="I hear "
l=zip(lines"Polar Bear\nLion\nHippopotamus\nFlamingo\nZebra\nBoa Constrictor\nElephant\nLeopard\nPeacock\nWalrus\nZookeeper")$words"growl roar snort flut bray hiss trumpet snarl yelp bellow whistl"
main=(b.drop 41.c)[f&e n&" "&v&"ing in my ear.\n\n"&n&", "&n&", what do you hear?\n"|(n,v)<-l]>>b(f&"children...\n\n..."&(d.d.c)[v&"ing like "&e n&",\n"|(n,v)<-d l]&"...\nthat's what I hear.\n")

Using the convention that a solution does not have be executable, only produce the output via some function, this can be shortened to 479 Bytes. The output is in g:

import Data.Char
a&b=a++b
c=concat
d=init
e('E':s)="an e"&s
e s="a "&map toLower s
f="I hear "
l=zip(lines"Polar Bear\nLion\nHippopotamus\nFlamingo\nZebra\nBoa Constrictor\nElephant\nLeopard\nPeacock\nWalrus\nZookeeper")$words"growl roar snort flut bray hiss trumpet snarl yelp bellow whistl"
g=(drop 41.c)[f&e n&" "&v&"ing in my ear.\n\n"&n&", "&n&", what do you hear?\n"|(n,v)<-l]&f&"children...\n\n..."&(d.d.c)[v&"ing like "&e n&",\n"|(n,v)<-d l]&"...\nthat's what I hear.\n"

user2845840

Posted 2016-07-19T04:01:10.603

Reputation: 391

0

Swift2, 519 bytes

var a=["Polar Bear","Lion","Hippopotamus","Flamingo","Zebra","Boa Constrictor","Elephant","Leopard","Peacock","Warlus","Zookeeper"],b=["...growl","roar","snort","flut","bray","hiss","trumpet","snarl","yelp","bellow","whistl"].map{"\($0)ing"},c=a.enumerate().map{"\($0.0==6 ?"an":"a") \($0.1)".lowercaseString},i=0,j=0
while i<11{print("\(a[i]), \(a[i++]), what do you hear?\nI hear \(i>10 ?"children...":"\(c[i]) \(b[i]) in my ear")\n")}
while j<10{print("\(b[j]) like \(c[j++])\(j>9 ?"...\nthat's what I hear.":",")")}

Vagner

Posted 2016-07-19T04:01:10.603

Reputation: 101