title: Invert your code

text:
# Question
Title: Invert your code
# Challenge

Return the full contents of your program, but inverted. How do your invert something? Well,

**Letters**: Take the position of the letter in the alphabet, subtract from 26, and use the letter at that position and flip the case of the letter. E.g `A` becomes `z`, and `p` becomes `J`.

**Digits**: Subtract from 9. E.g `6` becomes `3` and `5` becomes `4`

**Brackets**: The brackets `(){}[]<>` become their corresponding closing/opening bracket. E.g `[` becomes `]` and `>` becomes `<`

**Other**

* `&` and `|` swap.
* ' ' \[space\] and '\n' \[newline\] swap.
* `£` and `$` swap, as do  and `¥`
* `¢` and `%` swap
* `_` and `-` swap
* `"` and `'` swap
* `?` and `!` swap
* `:` and `;` swap
* `/` and `\` swap
* `@` and `#` swap
* `~` and ``` swap
* `,` and `.` swap
* `©` and `®` swap

All other characters become their Unicode inverse (subtract from 137,374). However, if the result is specified above, **you must replace it again with the replacement provided**. You only need to run a maximum of two replacements on each character, so no infinite loops.

# Rules

* Standard loopholes are disallowed

### Good luck!

# Answer
> 2 votes
# 05AB1E, 147 bytes

```
0"D34çýεÐ.ïi9αëÐáQižiDyk52αèë']Qiº¦ë34ç39ç«UX„,.VYJćDŠåiXÂ‡YÂ‡ëÇ•2S¹•αçJ]J"D34çýεÐ.ïi9αëÐáQižiDyk52αèë']Qiº¦ë34ç39ç«UX„,.VYJćDŠåiXÂ‡YÂ‡ëÇ•2S¹•αçJ]J

```

Outputs:

```
9'x65,S0kSSxCQ47"[kS6560gd.,fcrxSdc7ir[r'x65,S0kSSxCQ47"[kS6560gd.,fcrxSdc7ir[r

```

Try it online.

If this can be done in 4 bytes without creating a new language doing this specific task I'd love to see it.. \>.\> Also, based on the characters to invert I almost have the feeling it's deliberately targeting 05AB1E.. xD Probably not the case, but almost all those characters are pretty frequently used builtins in 05AB1E..

## Explanation:

**-part:**

The shortest for 05AB1E is this one: `0"D34çý"D34çý` (**14 bytes**) provided by *@OliverNi*. My answer uses a modified version of that quine by adding at the `...` here: `0"D34çý..."D34çý...`. A short explanation of this quine:

```
0                 # Push a 0 to the stack (can be any digit)
 "D34çý"          # Push the string "D34çý" to the stack
        D         # Duplicate this string
         34ç      # Push 34 converted to an ASCII character to the stack: '"'
            ý     # Join everything on the stack (the 0 and both strings) by '"'
                  # (output the result implicitly)

```

**Challenge part:**

```
ε                 # Map each character in the string to:
 Ð.ïi             #  If it's an integer:
     9α           #   Get it's absolute difference with 9
 ëÐáQi            #  Else-if it's a regular letter ([A-Za-z]):
      žiD         #   Push "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" twice
         yk       #   Get the index of the current character
           52α    #   Get the absolute difference with 52
              è   #   And index it into the string again
 ë']Qi           '#  Else-if it's a "]":
      º           #   Mirror it to "]["
       ¦          #   And remove the first character so just "[" remains
  34ç             #  Push '"'
     39ç          #  Push "'"
        «         #  Merge them together: `"'`
         UX       #  Save it in variable `X`
  „,.             #  Push ",."
     VY           #  Save it in variable `Y`
       J          #  Join the character, `"'` and ",." together
        ć         #  Extract the head (the character)
         DŠ       #  Duplicate and triple-swap, so the stack becomes char, `"',.`, char
 ë         åi     #  Else-if the character is in this string:
             XÂ   #   Push variable `X` and its reverse
               ‡  #   Transliterate the character
             YÂ   #   Push variable `Y` and its reverse
               ‡  #   Transliterate the character
 ë                #  Else:
  Ç               #   Convert the character to its unicode value
   •2S¹•          #   Push compressed integer 137374
        α         #   Take the absolute difference between the two
         ç        #   Convert it to a character again
          J       #   Join (workaround because very high unicode characters are wrapped
                  #         in a list for some reason)
]                 # Close all if-else statements and map
 J                # Join every mapped character together to a single string
                  # (and output the result implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?* to understand why `•2S¹•` is `137374`.

# Answer
> 2 votes
# Perl 6, 142 bytes

```
<my@a='a'..'z',@("<(|;~'@./£-".comb);my@b=@('Z'...'A'),@(Q'>)&:`"#,\=$_'.comb);"<$_>~~.EVAL".trans(pair((|@a,|@b),(|@b,|@a))).say>~~.EVAL

```

Try it online!

Avoids using most of the annoying to represent characters. I think this could be shorter

---
Tags: code-golf, quine
---


# Question
Title: Polar Bear, Polar Bear, what do you hear?
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.

```

# Answer
> 34 votes
## 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."

# Answer
> 9 votes
# 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.";

```

# Answer
> 8 votes
# 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);

```

# Answer
> 7 votes
# ///, ~~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)!

# Answer
> 6 votes
# 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

```

# Answer
> 6 votes
# 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.")

```

# Answer
> 5 votes
# 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

# Answer
> 3 votes
# 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)

# Answer
> 3 votes
# 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!

# Answer
> 3 votes
## 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.

# Answer
> 3 votes
# 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)])

```

# Answer
> 3 votes
# 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.

# Answer
> 2 votes
# 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)

```

# Answer
> 2 votes
## 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.

# Answer
> 1 votes
## 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."))))

```

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# 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".

# Answer
> 1 votes
## 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

```

# Answer
> 1 votes
# **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

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# 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!

# Answer
> 1 votes
# 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 $$."

```

# Answer
> 0 votes
# 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")))

```

# Answer
> 0 votes
# 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."

```

# Answer
> 0 votes
# 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"

```

# Answer
> 0 votes
## 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.":",")")}

```

# Answer
> 0 votes
# 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!

# Answer
> 0 votes
# 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!

# Answer
> 0 votes
# 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

---
Tags: code-golf, string, kolmogorov-complexity
---


title: Back to the chemistry class

text:
# Question
Title: Back to the chemistry class
## Introduction

One of the first things I learned in chemistry, was giving the formula for the combustion of alkanes. The most basic example was: `2CH4 + 4O2 -> 4H2O + 2CO2`. **Note that the equation could have been simplified by dividing every coefficient by 2, we would get** `CH4 + 2O2 -> 2H2O + CO2`. **To make things easier, we are going to ignore this to not complicate things**.

You can see that with the combustion of any alkane, oxygen is used. After the reaction, only `CO2` and `H2O` are made.

# The task

The input will always be in the form `C(n)H(2n+2)`, with `n>0`. These are some example inputs:

```
CH4
C2H6
C3H8
C4H10
C5H12
C6H14

```

## Useful tip:

Every alkane has a standard pattern in the combustion reaction:

```
2C(n)H(2n+2) + (3n+1)O2 -> (2n+2)H2O + (2n)CO2

```

e.g.

`C4H10` gives the following equation: `2C(4)H(2*4+2) + (3*4+1)O2 -> (2*4+2)H2O + (2*4)CO2`. After calculating everything, we get this final equation `2C4H10 + 13O2 -> 10H2O + 8CO2`

## Testcases

```
CH4
2CH4 + 4O2 -> 4H2O + 2CO2

C3H8
2C3H8 + 10O2 -> 8H2O + 6CO2

C4H10
2C4H10 + 13O2 -> 10H2O + 8CO2

C12H26
2C12H26 + 37O2 -> 26H2O + 24CO2

```

# Rules

* Note that I used spaces for the examples to increase readability, **these are not necessary**. `2CH4 + 4O2 -> 4H2O + 2CO2` and `2CH4+4O2->4H2O+2CO2` are both valid outputs. However, if you *consistently* use spaces for the output, you get a **-10% bonus**
* This is , so the program with the least amount of bytes wins!

# Answer
> 1 votes
# Pyth, 40 bytes

```
s[2z\+h*3Jv|hctz\H\1"O2>"yhJ"H2O+"yJ"CO2

```

Try it online. Test suite.

# Answer
> 8 votes
# Python 3, 86 * 0.9 = 77.4 bytes

```
s=input()
N=int(s.split('H')[1])
print("2%s + %dO2 > %dH20 + %dCO2"%(s,N*1.5-2,N,N-2))

```

Try it online!

Extracts the number of `H`'s rather than the number of `C`'s from the input. This avoid special-casing `CH4` and simplifies the output expressions in terms of `N=2n+2`.

The output has parameters plugged in via string formatting. The first summand is just the input string, and the rest have calculated numbers plugged in. Note that `N*1.5-2` (same as `N*3/2-2`) gives a float, but the string formatting converts it to an int.

# Answer
> 4 votes
# Java, 202 * 0.9 = 181.8 bytes

Sometimes, I wonder if I'm just hurting myself with Java.

Thanks to @TNT and @TFeld for shaving off a good 20 bytes!

```
class A{public static void main(String[]a){String s=a[0].substring(1,a[0].indexOf("H"));long n=Long.parseLong((s.length()>0)?s:"1");System.out.printf("2%s + %dO2 > %dH2O + %dCO2",a[0],3*n+1,2*n+2,2*n);}}

```

Pretty simple. Basically, I cut the input from `C` to `H`, and get that substring. If it's nothing, I set `n` to one. Otherwise, I set it to the number between `C` and `H`. The code following just prints it out and puts it into proper notation.

Ungolfed

```
class A{
    public static void main(String[]a) {
         String s=a[0].substring(1,a[0].indexOf("H"));
         long n=Long.parseLong((s.length()>0)?s:"1");
         System.out.printf("2%s + %dO2 > %dH2O + %dCO2",a[0],3*n+1,2*n+2,2*n);
    }
}

```

# Answer
> 4 votes
# Python 2, ~~122~~ 91 * 0.9 = 81.9 bytes

```
i=input()
n=2*int(i[1:i.find('H')]or 1)
print'2%s + %dO2 > %dH2O + %dCO2'%(i,n*3/2+1,n+2,n)

```

Try it online!

# Answer
> 3 votes
# JavaScript ES6, 63 * 0.9 = 56.7 bytes

```
_=>`2${_} + ${$=_.split`H`[1],$*1.5-2}O2 > ${$}H2O + ${$-2}CO2`

```

Similar to my ESMin answer

# Answer
> 3 votes
# Pyth, 53\*0.9 = 48 bytes

Previous byte count:

* 69 * 0.9 = 62
* 63 * 0.9 = 57
* 56 * 0.9 = 50

```
Js>z+xz\H1s[\2z%" + %dO2 > %dH2O + %dCO2"[-*1.5J2J-J2

```

It is just like xnor's answer, where I use the H values. A variable J is used to store the amount of H's in the molecular formula of the molecule.

Try it here

# Answer
> 2 votes
# Python, 148 * 0.9 = 133 bytes

Prev byte counts

* 0.9\*195 = 175
* 0.9\*190 = 171

```
i=raw_input()
O=3*int(i[1:i.find('H')]or 1)+1;C=2*int(i[1:i.find('H')]or 1);print"2"+i+" + "+`O`+"O2"+" > "+i[i.find('H')+1:]+"H2O"+ " + "+`C`+"CO2"

```

Try it online!

# Answer
> 2 votes
# Javascript ES6, 96\*0.9 = 86.4

```
f=s=>`2C${(n=(s.match(/\d+(?!.*\d)/)[0]-2))>2?n/2:''}H${n+2} + ${1.5*n+1}O2 > ${n+2}H2O + ${n}CO2`

```

# Answer
> 2 votes
# CJam, ~~45~~ 44 bytes

```
2r_'H/1=[i_((_2/1$+)@@]"+%dO2>%dH2O+%dCO2"e%

```

Try it online

To avoid special casing `CH4`, I don't use the first number at all, and only extract the number after the `H`. This gives the value of `2n+2`. The remaining values are then calculated based on that, and formatted.

Explanation:

```
2       Push leading 2 for output.
r       Get input.
_'H/    Copy and split at 'H.
1=      Take second part after split, this is 2n+2.
[       Start list.
  i       Convert string value to integer.
  _((     Copy and decrement twice, giving 2n.
  _2/     Copy and divide by 2, giving n.
  1$      Copy the 2n to the top.
  +       Add, to get 3n.
  )       Increment, giving 3n+1. We now have 2n+2, 2n, 3n+1 on stack.
  @@      Rotate top 3 entries twice, to get 3n+1, 2n+2, 2n.
]       Close list.
"+%dO2>%dH2O+%dCO2"
        Format string for output.
e%      "printf" operator.

```

# Answer
> 2 votes
## Perl, (84 + 1) * 0.9 = 76.5

(+1 char for running with the `-n` flag)

My first Perl golf!

```
@x=(1,m/C(\d)/g);$n=$x[$#x];say"2$_ + ".(3*$n+1)."O2 > ".(($n*=2)+2)."H20 + ${n}CO2"

```

It's important that STDIN not contain a trailing newline. Example usage:

```
llama@llama:...code/perl/ppcg64412chemistry$ printf CH4 | perl -n chemistry.pl
2CH4 + 4O2 > 4H20 + 2CO2

```

Ungolfed-ish:

```
#!/usr/bin/perl
use 5.10.0;

$_ = 'C3H8';
my @x = (1, m/C(\d)/g);
my $n = $x[$#x];
say "2$_ + ".(3*$n+1)."O2 > ".(($n*=2)+2)."H20 + ${n}CO2";

```

The lines

```
my @x = (1, m/C(\d)/g);
my $n = $x[$#x];

```

are fairly interesting here. `$#x` represents the "last populated index" of `@x` (and SE's syntax highlighting thinks it's a comment because it's dumb), so `$x[$#x]` will select the captured part of the `C(\d)` regex *if* it exists, or `1` otherwise. (Perl doesn't care that it'll be a string in all other cases except `1`; you can use numerical operators on strings just fine in Perl.)

# Answer
> 2 votes
# , 64 * 0.9 = 57.6 bytes

```
a=ïČ`H”[1],`2⦃ï} + ⦃a*1.5-2}O2 > ⦃a}H2O + ⦃a-2}CO2`

```

Try it here (Firefox only)

## Explanation

```
a=ïČ`H”[1],      // split input along H to get 2n+2
`  2⦃ï}          // 2C(n)H(2n+2) – this is the same as 2[input alkane's formula]
   + ⦃a*1.5-2}O2 // + 2(3n+1)O2
   > ⦃a}H2O      // > (2n+2)H2O
   + ⦃a-2}CO2    // + (2n)O2
`                // implicitly output the template string above

```

# Answer
> 1 votes
## JS, 118 (106) bytes

```
x=prompt();y=x.replace("CH","C1H").match(/\d{1,}/g)[0];alert(2+x+" + "+(3*y+1)+"O2 > "+(2*y+2)+"H2O + "+(2*y)+"CO2");

```

# Answer
> 1 votes
# C++ (clang), 160 bytes

```
#include<iostream>
int main(){int n=1,t;std::cin.get();std::cin>>n;t=2*n;printf("2C");n-1&&printf("%i",n);printf("H%i + %iO2 > %iH2O + %iCO2",t+2,t+n+1,t+2,t);}

```

Try it online!

A bit more that I expected. Reads first char and discards it, then reads int and outputs the result. Problem is with `n` being 1. I can't think of shorter way to output it.

Ungolfed

```
#include <iostream>
int main()
{
    int n = 1, t;
    std::cin.get();
    std::cin >> n;
    t = 2 * n;
    printf("2C");
    n - 1 && printf("%i", n);
    printf("H%i + %iO2 > %iH2O + %iCO2", t + 2, t + n + 1, t + 2, t);
}

```

# Answer
> 1 votes
# F# (.NET Core), 113 bytes

```
let s=stdin.ReadLine()
float s.[1+s.IndexOf 'H'..]|>fun f->printf"2%s + %gO2 > %gH2O + %gCO2"s<|f*1.5-2.<|f<|f-2.

```

Try it online!

# Answer
> 1 votes
# MATLAB, 96 * 0.9 = 86.4 bytes

```
s=input('');i=[sscanf(s,'C%dH'),1];n=i(1);fprintf('%s + %dO2 > %dH2O + %dCO2',s,3*n+1,2*n+2,2*n)

```

Fairly self explanatory. Takes an input string (need to wrap it in quote marks so MATLAB doesn't try to execute it!). Then converts the number between the C and the H in the input to decimal. The value 1 is appended as an array to the output of sscanf so that in the case `CH4` when we extract the first index in the array into `n` we get a 1 if there was no number between the C and H. Then just prints out with the spaces following the formula in the question.

This should also work with **Octave** using the online interpreter here.

# Answer
> 1 votes
# Clojure/ClojureScript, 98\*0.9 = 88.2 bytes

```
#(let[n(max 1(int((re-find #"C(.*)H"%)1)))m(* 2 n)](str "2"%" + "(inc(* 3 n))"O2 > "(+ 2 m)"H2O + "m"CO2"))

```

Creates an anonymous function. Try it by going here and entering `(def f #(let...))`, then `(f "C3H8")`.

# Answer
> 1 votes
# Excel, 123 * 0.9 = 110.7 bytes

```
=="2"&A1&" + "&(3*MID(A1,FIND("H",A1)+1,9)/2-2)&"O2 > "&MID(A1,FIND("H",A1)+1,9)&"H2O + "&(MID(A1,FIND("H",A1)+1,9)-2)&"CO2"

```

If we could take CH4 input as C1H4, can be reduced to 122 * 0.9 = 109.8 bytes

```
="2"&A1&" + "&3*MID(A1,2,FIND("H",A1)-2)+1&"O2"&" > "&MID(A1,FIND("H",A1)+1,9)&"H2O + "&(MID(A1,FIND("H",A1)+1,9)-2)&"CO2"

```

# Answer
> 1 votes
# Jelly, 33 bytes

```
ṣ”HṪVµ2³”+2⁸_©+H“O2>”⁸“H2O+”®“CO2

```

Try it online!

The bonus doesn't help here.

---
Tags: code-golf, chemistry
---


title: Binary self-rotation

text:
# Question
Title: Binary self-rotation
Given a binary 3D array, for each layer, cyclically rotate up each of its columns as many steps as indicated by the binary encoding of the columns of the layer above it, and then cyclically rotate left each of its rows as many steps as indicated by the binary encoding of the rows of the layer below it.

There will always be at least three layers. The top layer's columns and the bottom layer's rows should not be rotated.

## Walk-through

Lets start with the small 4-layer, 2-row, 3-column array:

```
[[[1,0,1],
  [1,0,0]],

 [[1,0,1],
  [0,1,1]],

 [[0,1,1],
  [1,1,1]],

 [[1,1,0],
  [1,1,1]]]

```

The first step is evaluating the numbers encoded in binary by the columns and rows of each layer:

```
     3 0 2
5 [[[1,0,1],
4   [1,0,0]],

     2 1 3
5  [[1,0,1],
3   [0,1,1]],

     1 3 3
3  [[0,1,1],
7   [1,1,1]],

     3 3 1
6  [[1,1,0],
7   [1,1,1]]]

```

The first layer, `[[1,0,1],[1,0,0]]` will not have its columns rotated, but its rows will be cyclically rotated left 5 steps and 3 step respectively, thus becoming `[[1,1,0],[1,0,0]]`.
The second layer, `[[1,0,1],[0,1,1]]`, will have its columns cyclically rotated up 3, 0, and 2 steps respectively, giving `[[0,0,1],[1,1,1]]`, and then the rows are cyclically rotated left 3 and 7 steps respectively, with no visible change.
The third layer, `[[0,1,1],[1,1,1]]` rotated up 2, 1, and 3 steps stays the same, and neither does rotating left 6 and 7 steps do anything.
Finally, the fourth layer, `[[1,1,0],[1,1,1]]` rotated up 1, 3, and 3 steps is `[[1,1,1],[1,1,0]]`, but its rows are not rotated afterwards, as it is the last layer.
Putting all the layers together again, gives us the binary self-rotated 3D array:

```
[[[1,1,0],
  [1,0,0]],

 [[0,0,1],
  [1,1,1]],

 [[0,1,1],
  [1,1,1]],

 [[1,1,1],
  [1,1,0]]]

```

Example cases:

`[[[1,0,1],[1,0,0]],[[1,0,1],[0,1,1]],[[0,1,1],[1,1,1]],[[1,1,0],[1,1,1]]]` gives
`[[[1,1,0],[1,0,0]],[[0,0,1],[1,1,1]],[[0,1,1],[1,1,1]],[[1,1,1],[1,1,0]]]`

`[[[1]],[[1]],[[0]]]` gives
`[[[1]],[[1]],[[0]]]`

`[[[1,0,1],[1,0,1],[1,0,1]],[[0,0,1],[0,0,1],[0,0,1]],[[1,0,0],[1,0,1],[0,0,1]]]` gives
`[[[0,1,1],[0,1,1],[0,1,1]],[[0,1,0],[1,0,0],[0,1,0]],[[1,0,1],[1,0,1],[0,0,0]]]`

# Answer
# Jelly,  ~~18~~  17 bytes

```
ṙ""Ḅ}
Z€çŻṖ$$Z€çḊ

```

**Try it online!**

### How?

```
ṙ""Ḅ} - Link 1, rotation helper: 3d matrix to rotate, 3d matrix of rotation instructions
    } - use the right argument for:
   Ḅ  -   un-binary (vectorises) - get the rotation amounts as a 2d matrix
  "   - zip with:
 "    -  zip with:
ṙ     -    rotate (the current row) left by (the current amount)

Z€çŻṖ$ $Z€çḊ - Main Link: 3d matrix, M
Z€           - transpose €ach (layer of M)
       $     - last two links as a monad:
     $       -   last two links as a monad:
   Ż         -     prepend a zero
    Ṗ        -     pop (i.e. remove the tail)
  ç          -   call the last Link as a dyad (i.e. f(Z€ result, ŻṖ$ result) )
        Z€   - transpose €ach (layer of that)
           Ḋ - dequeue (i.e. remove the head layer of M)
          ç  - call the last Link as a dyad (i.e. f(Z€çŻṖ$$Z€ result, Ḋ result) )

```

Note: `$$` (or possibly `$$ ... $$`?) seems to mess up the code-block formatting (but only once posted, not in the preview), so I added a space to make my life easier.
> 3 votes

# Answer
# Python 2, ~~220~~ ~~211~~ ~~209~~ ~~185~~ ~~176~~ ~~174~~ ~~164~~ ~~161~~ 159 bytes

```
lambda m:map(R,z(map(R,z(m,['']+[z(*l)for l in m])),m[1:]+['']))
R=lambda(l,L):map(lambda r,i:r[i:]+r[:i or 0],z(*l),[int(`b`[1::3],2)%len(b)for b in L])
z=zip

```

Try it online!

-2 bytes, thanks to Jonathan Allan
> 3 votes

# Answer
# APL+WIN, ~~53~~ 39 bytes

Many thanks to Adám for saving 14 bytes

```
(1 0↓⍉2⊥⍉m⍪0)⌽(¯1 0↓2⊥2 1 3⍉0⍪m)⊖[2]m←⎕

```

Try it online! Courtesy of Dyalog Classic

Prompts for input of a 3d array of the form:

```
4 2 3⍴1 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 1 1 1 0 1 1 1

```

which yields:

```
1 0 1
1 0 0

1 0 1
0 1 1

0 1 1
1 1 1

1 1 0
1 1 1

```

Explanation:

```
m←⎕ Prompt for input

(¯1 0↓2⊥2 1 3⍉0⍪m) Calculate column rotations

(1 0↓⍉2⊥⍉m⍪0) Calculate row rotations

(...)⌽(...)⊖[2]m Apply column and row rotation and output resulting 3d array:

1 1 0
1 0 0

0 0 1
1 1 1

0 1 1
1 1 1

1 1 1
1 1 0

```
> 2 votes

# Answer
# , ~~226~~ ~~216~~ 205 bytes

-21 bytes thanks to digEmAll

```
function(a,L=`for`){d=dim(b<-a)
r=function(a,n,l=sum(a|1))a[(1:l+sum(n*2^(sum(n|1):1-1))-1)%%l+1]
L(i,I<-2:d[3],L(j,1:d,b[j,,i]<-r(b[j,,i],a[j,,i-1])))
L(i,I-1,L(k,1:d[2],b[,k,i]<-r(b[,k,i],a[,k,i+1])))
b}

```

Try it online!
> 2 votes

# Answer
# 05AB1E, ~~41~~ 39 bytes

```
εNĀiø¹N<èøJC‚øε`._}ø}N¹g<Êi¹N>èJC‚øε`._

```

This feels way too long.. Can definitely be golfed some more.

Try it online or verify all test cases.

**Explanation:**

```
ε                    # Map each layer in the (implicit) input to:
                     # (`N` is the layer-index of this map)
 NĀi                 #  If it is not the first layer:
    ø                #   Zip/transpose the current layer; swapping rows/columns
    ¹N<è             #   Get the `N-1`'th layer of the input
        ø            #   Zip/transpose; swapping rows/columns
         J           #   Join all inner lists (the columns) together
          C          #   And convert it from binary to integer
           ‚         #   Pair it with the current layer's columns we're mapping
            ø        #   Zip/transpose; to pair each integer with a layer's columns
             ε   }   #   Map over these pairs:
              `      #    Push both values of the pair separately to the stack
               ._    #    Rotate the column the integer amount of times
    ø                #   Zip/transpose the rows/columns of the current layer back
   }                 #  Close the if-statement
 N¹g<Êi              #  If this is not the last layer (layer-index-1 != amount_of_layers):
       ¹N>è          #   Get the `N+1`'th layer of the input
           J         #   Join all inner lists (the rows) together
            C        #   And convert it from binary to integer
             ‚       #   Pair it with the current layer's rows we're mapping
              ø      #   Zip/transpose; to pair each integer with a layer's rows
               ε     #   Map over these pairs:
                `    #    Push both values of the pair separately to the stack
                 ._  #    Rotate the row the integer amount of times
                     # (implicitly output the result after the layer-mapping is done)

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~138~~ ~~131~~ ~~125~~ 123 bytes

```
t=Map@Thread
m=MapThread[r=RotateLeft,#,2]&
b=(a=ArrayPad)[Map@Fold[#+##&]/@#,1]~r~#2~a~-1&
g=m@{t@m@{t@#,t@#~b~-1},#~b~1}&

```

Try it online!

* `Map[Thread]` is equivalent to `Transpose[a, {1,3,2}]`, which transposes the columns and rows.
* `Fold[#+##&]` is shorter than `IntegerDigits[#,2]` for converting from binary.
> 1 votes

---
Tags: code-golf, matrix, cellular-automata, 3d
---


# Question
Title: Python workarounds for assignment in lambda
*This is a tips question for golfing in Python.*

In Python golfing, it's common for a submission to be a function defined as a lambda. For example,

```
f=lambda x:0**x or x*f(x-1)

```

computes the factorial of x.

The lambda format has two big advantages:

* The boilerplate of `f=lambda x:...` or `lambda x:...` is shorter than the `def f(x):...return...` or `x=input()...print...`
* A recursive call can be used to loop with little byte overhead.

However, lambdas have the big drawback of allowing only a single expression, no statements. In particular, this means no assignments like `c=chr(x+65)`. This is problematic when one has a long expression whose value needs to be referenced twice (or more).

Assignments like `E=enumerate` are possible outside the function or as an optional argument, but only if they don't depend on the function inputs. Optional arguments like `f=lambda n,k=min(n,0):...` fail because input `n` hasn't been defined when `k` is evaluated at definition time.

The result is that sometimes you suck up repeating a long expression in a lambda because the alternative is a lengthy non-lambda.

```
lambda s:s.strip()+s.strip()[::-1]
def f(s):t=s.strip();print t+t[::-1]

```

The break even point is about 11 characters (details), past which you switch to a `def` or `program`. Compare this to the usual break-even point of length 5 for a repeated expression:

```
range(a)+range(b)
r=range;r(a)+r(b)

print s[1:],s[1:]*2
r=s[1:];print r,r*2

```

Other languages have workarounds, Octave for example. There are known tricks for Python, but they are long, clunky, and/or limited-use. A short, general-purpose method to simulate assignment in a lambda would revolutionize Python golfing.

---

What are ways for a Python golfer to overcome or work around this limitation? What potential ideas should they have in mind when they see a long expression repeated twice in a lambda?

My goal with this tips question is to dive deep into this problem and:

* Catalog and analyze golfing workarounds to fake assignment inside a lambda
* Explore new leads for better methods

Each answer should explain a workaround or potential lead.

# Answer
## Assignment expressions in Python 3.8

Python 3.8 (TIO) introduces assignment expressions, which use `:=` to assign a variable inline as part of expression.

```
>>> (n:=2, n+1)
(2, 3)

```

This can be used inside a `lambda`, where assignments are not ordinarily allowed. Compare:

```
lambda s:(t:=s.strip())+t[::-1]
lambda s:s.strip()+s.strip()[::-1]
def f(s):t=s.strip();return t+t[::-1]

```

See this tip for more.
> 9 votes

# Answer
### `eval`

This is not that great in of itself, but if your solution already uses `eval` in some way or form you can usually use this technique.

```
eval("%f*%f+%f"%((5**.5,)*3))

```
> 6 votes

# Answer
## Inner lambdas

These allow you to define multiple variables at once.

```
lambda s:s.strip()+s.strip()[::-1]

```

vs.

```
lambda s:(lambda t:t+t[::-1])(s.strip())

```

is much longer, but if you have multiple variables, or variables that are longer, which are repeated many times:

```
lambda a,b,c:a.upper()*int(c)+b.lower()*int(c)+a.upper()[::-1]+b.lower()[::-1]+a.upper()*int(c)+a.lower()*int(c)

```

vs.

```
lambda a,B,c:(lambda A,b,n:A*n+b*n+A[::-1]+b[::-1]+A*n+b*c)(a.upper(),B.lower(),int(c))

```

### Character count

Initial: `(lambda:)()` (11 bytes)
First variable: `[space]a` (2 bytes)
Subsequent variables: `,b,` (3 bytes)
Use: `a` (1 byte).

```
(lambda* a*_,b_:)(*<value a>*_,<value b>_)
```

(Also saves on brackets)

So, this takes `3n + 10` bytes, where `n` is the number of variables. This is a high initial cost, but can pay off in the end. It even returns it's inner value,so you can nest multiple (Though this will quickly become not worth it.)

This is really only useful for long intermediate calculations in nested list comprehensions, as a `def f():a=...;b=...;return` will usually be shorter.

For 1 value, this saves: `uses * length - length - uses - 13`, so is only useful when that expression is positive.
For a `n` different expressions used `u` times in total, where their combined length is `l`, this saves:
`l - (3 * n) - u - 10 ( + brackets removed )`
> 2 votes

# Answer
# Use a List

Declare a list as parameter and use `.append() or` to store the value:
`lambda s:s.lower()+s.lower()[::-1]`
turns into
`lambda s,l=[]:l.append(s.lower())or l[-1]+l[-1][::-1]`

### Character count:

`,l=[]` 5 characters
`l.append()or`  13 characters
`l[-1]` 5 characters for each use

### Break Even

The amount of added character is :
`uses*(5-length) + 18 + length`
In the previous example the statement is `s.lower()` is 9 characters long and is used 2 times, applying this technique added 19 characters. If it was used 7 times, there would be a 1 character reduction.
The amount of minimal uses to this technique be worth is
`min_uses = (18+length)/(length-5)`

## Upsides

* Allow a new assignment at a slightly reduced cost (the list already is declared)
* Is a `list` object so `[0]`, `.pop()`, `[x:y]` and other list functions can be used for tricks. *highly situational*

## Downsides

* High initial cost
* High use cost
* Only works for uses with the length higher than `5`

---

# Use a Dictionary

thanks @Zgarb
Same idea as above Declare a dictionary as parameter and use `.setdefault()` to store (and return) the value:
`lambda s:s.lower()+s.lower()[::-1]`
turns into
`lambda s,d={}:d.setdefault(0,s.lower())+d[0][::-1]`
Note that, unlike the `list` counterpart, `setdefault` returns the value assigned.

### Character count:

`,d={}` 5 characters
`d.setdefault(k,)` 16 characters
`d[k]` 4 characters for each use

### Break Even

The amount of added character is :
`(uses-1)*(4-length) + 21`
In the previous example the statement is `s.lower()` is 9 characters long and is used 2 times, applying this technique added 16 characters. If it was used 7 times, there would be a 1 character reduction.
The amount of minimal uses to this technique be worth is
`min_uses = 1-21/(4-length)`

## Upsides/Downsides

* Basically the same as the list
* Only works for uses with the length higher than `4`

---

## Other considerations

* If this technique worth the character reduction, then the `lambda` can probably be dropped and the function be rewritten with `def`/`input` for a shorter program.
* As @FlipTack pointed, the list and the dict **ARE KEEPT** between function calls, while this will mostly disturb, it can be used on recursive calls.*again highly situational*
* The dictionary will always be shorter than the list.
> 0 votes

# Answer
Use to set variables and return the data after operation like such:

```
add = lambda x, y: exec("x+=y")

```
> 0 votes

# Answer
# List comprehensions

This is more of a last resort since it's so ungolfy, but you can do
`[<expression> for <variable> in <value>]`
to pseudo-set a variable in a lambda. Basically the only good point about this method is that the inner expression can stay readable, which is obviously the least of your concern when golfing.
> 0 votes

---
Tags: code-golf, tips, python
---


title: Pairable strings

text:
# Question
Title: Pairable strings
A string is *pairable* if it can be split into subtrings, each of which is a string repeated twice consecutively. For example, `aabaaababbbaba` is pairable as:

```
aaba aaba
b b
ba ba

```

Given a non-empty string of `a`'s and `b`'s, output a Truthy value if it's pairable and a Falsey value if it isn't.

**Pairable:**

```
aa
abaaba
bbababbb
aabaaababbbaba
babababa
bbbbbbbbbbbb
aaababbabbabbbababbaabaabaababaaba
aaaabaab

```

**Not pairable:**

```
a
ba
baab
abaabaaba
bbbbbbbbbbbbbbb
baababbabaaaab
aaaaabbaaaaa

```

I encourage you to come up with non-regex-based solutions even when there's already a shorter regex answer in your language. You can mark them as "no regex". By regex, I mean a built-in string pattern matching subsystem.

---

**Leaderboard:**

```
var QUESTION_ID=98252,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/98252/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 11 votes
# Python 2, ~~68~~ 63 bytes

```
f=lambda s,n=1:s==2*s[:n]or''<s[n:]>-f(s,n+1)<f(s[n:])*f(s[:n])

```

Returns *True* or *False*. Test it on Ideone.

# Answer
> 8 votes
# Retina, 11 bytes

```
^((.+)\2)+$

```

Try all the test cases. The first two bytes make it multi-line.

Pretty literal interpretation of the rules, obviously uses regex, like all Retina programs will.

# Answer
> 8 votes
# Jelly, 10 bytes

```
ẆŒPẋ€€2F€ċ

```

Not exactly efficient... Try it online!

### How it works

```
ẆŒPẋ€€2F€ċ  Main link. Argument: s (string)

Ẇ           Window, generate the array of all substrings of s.
 ŒP         Powerset; generate all subarrays of substrings of s.
   ẋ€€2     Repeat each substring in each subarray twice.
            For example, ["ab", "a", "b"] becomes ["abab", "aa", "bb"].
       F€   Flatten the subarrays by concatenating their strings.
         ċ  Count how many times s appears in the generated strings.

```

# Answer
> 5 votes
## Haskell, ~~72~~ 69 bytes (no regex)

```
g(a:b:c)|a==b=g c
g x=x==[]
any(g.words.concat).mapM(\c->[[c],c:" "])

```

A brute-force approach. Try it on Ideone.

Thanks to BlackCap for -3 bytes.

## Explanation

The helper function `g` takes a list of strings, and checks that it consists of pairs of identical strings, like `["aa","aa","bba","bba","ab","ab"]`. The (anonymous) main function splits a string in all possible ways, and checks that at least one splitting results in a list that `g` accepts.

```
g(a:b:c)                                  g on list with elements a, b and tail c,
        |a==b                              in the case that a==b,
             =g c                          recurses to the tail c.
g x=                                      g on any other list x
    x==[]                                  checks that x is empty.
                                           This includes the case where a is not equal
                                           to b, resulting in False.
any(g.words.concat).mapM(\c->[[c],c:" "]) The main function:
                    mapM(\c->[[c],c:" "])  Replace each letter c with either "c" or "c "
                                           in all possible ways, return list of results.
any(              ).                       Check that at least one result satisfies this:
            concat                          Concatenate the 1- or 2-letter strings,
      words.                                split again at each space,
    g.                                      apply g.

```

# Answer
> 5 votes
# Python 2, 60 bytes

```
f=lambda s,t='':''<s>f(s[1:],t+s[0])|f(t and s)*f(t)>-(s==t)

```

I hope this is correct. It runs pretty slowly and the `and` doesn't look optimal.

# Answer
> 4 votes
# Jelly, 12 bytes

```
ŒṖµœs€2ZEµ€S

```

Two bytes longer than my other answer, but this approach is a lot more efficient and handles all but one of the test cases.

Try it online!

### How it works

```
ŒṖµœs€2ZEµ€S  Main link. Argument: s (string)

ŒṖ            Generate all partitions of s.
  µ      µ€   Map the monadic chain between the µ's over the partitions.
   œs€2         Split each string in the partition into two chunks of equal length.
       Z        Zip/transpose, collecting the first halves in one array and the
                second halves in another.
        E       Test the arrays of halves for equality.
           S  Return the sum of the results, counting the number of different
              ways s can be paired.

```

# Answer
> 3 votes
# Pyth - No Regex - ~~13~~ 12 bytes

Checks if any of the partitions are made up of all string that are equals to each other when chopped in two.

```
sm.AqMcL2d./

```

Test Suite.

# Answer
> 3 votes
## JavaScript (ES6), no regexp, ~~75~~ 74 bytes

```
f=s=>!s|[...s].some((_,i)=>i&&s[e='slice'](0,i)==s[e](i,i+=i)&&f(s[e](i)))

```

Returns `1` for pairable otherwise `0`. Edit: Saved 1 byte thanks to @edc65.

# Answer
> 3 votes
# Brachylog, 14 bytes (no regex)

```
lye~l:1j@2zcc?

```

Try it online!

This is too slow for some of the test cases

### Explanation

```
ly                  The list [0, …, length(Input)]
  e~l               A list whose length is an element of the previous list
     :1j            Append itself to this list
        @2zc        Split in half, zip and concatenate so that the list contains pairs of
                      consecutive identical elements
            c?      The concatenation of that list must result in the Input

```

# Answer
> 3 votes
## Python, 58 bytes

```
f=lambda s,p='':s>''and(f(p)>-(s==p)<f(s))|f(s[1:],p+s[0])

```

This is based on the Dennis's recursive method. The Boolean negation trick is taken from there as well.

The new idea is to recurse over partitions `(p,s)` of the original string by starting with `('',s)` and repeatedly moving the first character of `s` to be the last character of `p`. This allows for the parts to be referred to directly without string slicing. But, because the partition starts with `p` empty, we must be careful to avoid infinite loops of `f(s)` calling `f(s)`.

# Answer
> 2 votes
# JavaScript (ES6), 24 bytes

```
x=>/^((.+)\2)+$/.test(x)

```

Probably doesn't get shorter than this.

# Answer
> 2 votes
# PHP, 40 Bytes

prints 0 for false and 1 for true

```
<?=preg_match("#^((.+)\\2)+$#",$argv[1]);

```

# Answer
> 2 votes
# Python, ~~66~~ 64 bytes

Thanks @Zgarb for -1 byte!

```
f=lambda x,s=1:x>x[:s]and(x==2*x[:s])|f(x[:s])&f(x[s:])|f(x,s+1)

```

Returns `True` or `False`.

Try it online!

Any help golfing this would be appreciated.

# Answer
> 1 votes
## Racket 230 bytes

```
(let((sl string-length)(ss substring))(if(odd?(sl s))(printf ".~n")(begin(let p((s s))(if(equal? s "")(printf "!")
(for((i(range 1(add1(/(sl s)2)))))(when(equal?(ss s 0 i)(ss s i(* 2 i)))(p(ss s(* 2 i)(sl s)))))))(printf ".~n"))))

```

Prints a '!' for each way in which the string is pairable. Prints a '.' at the end.

Ungolfed:

```
(define (f s)
  (let ((sl string-length)                              ; create short names of built-in fns
        (ss substring))
    (if (odd? (sl s))  (printf ".~n")                   ; odd length strings cannot be pairable; end here.
        (begin
          (let loop ((s s))                             ; start testing here
            (if (equal? s "") (printf "!")              ; if no remaining string, it must be pairable
                (for ((i (range 1 (add1 (/(sl s)2)))))  ; ch lengths varying from 1 to half of string length
                  (when (equal? (ss s 0 i)              ; ch if substrings are same
                                (ss s i (* 2 i)))
                    (loop (ss s (* 2 i) (sl s) ))))))   ; if yes, loop to check remaining string.
          (printf ".~n")))))                            ; End of testing.

```

Testing:

```
(println "Following should be pairable")
(f "bbaabbaa")            ; should produce 2 '!' since 2 ways are possible.
(f "aa")
(f "abaaba")
(f "bbababbb")
(f "aabaaababbbaba")
(f "babababa")                    ; should be pairable in 2 ways.
(f "bbbbbbbbbbbb")                ; should be pairable in many ways.
(f "aaababbabbabbbababbaabaabaababaaba")
(f "aaaabaab")
(println "Following should be unpairable")
; (f "a")
(f "ba")
(f "baab")
(f "abaabaaba")
(f "bbbbbbbbbbbbbbb")
(f "baababbabaaaab")
(f "aaaaabbaaaaa")

```

Output:

```
"Following should be pairable"
!!.
!.
!.
!.
!.
!!.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!.
!.
!.
"Following should be unpairable"
.
.
.
.
.
.

```

# Answer
> 1 votes
# Perl, 16 +2 = 18 bytes (with regex)

Run with the `-nl` flags. `-E` is free.

```
say/^((.+)\2)+$/

```

Run as:

```
perl -nlE 'say/^((.+)\2)+$/'

```

Returns a list of the capture groups (a truthy) if pairable, null string if not pairable.

Explanation

The `-nl` flags will run the code in a loop (`-n`), putting the input (with trailing newline removed because of `-l`) into the variable `$_` each time, then evaluating the code each time input is entered, until the program is manually terminated. The `-E` flag lets you evaluate code on the command line, and enables the `say` command.

```
say/^((.+)\2)+$/

   /^((.+)\2)+$/  #The regex engine
      (.+)\2      #Find any set of at least one character, followed by itself
     (      )+    #Do this at least one time
   /^         $/  #Make sure that this matches the entire string from start to end
say               #Output the result of the regex

```

If a match is found (e.g. if the string is pairable), then the regex returns a list of the capture groups, which evaluates to a truthy, which is then passed to `say`, and output. If no match is found, then the regex returns the empty string, which evaluates to falsy, which is then passed to `say`, and output.

Sample:

```
$ perl -nlE 'say/^((.+)\2)+$/'
aaababbabbabbbababbaabaabaababaaba
baababaababaaba                      #Truthy
baababbabaaaab
                                     #Falsy
bbababbb
bbb                                  #Truthy
aabaaababbbaba
bababa                               #Truthy
abaabaaba
                                     #Falsy

```

# Answer
> 1 votes
# GNU Prolog, ~~49~~ 46 bytes

Probably works in other variants too, although they don't all represent strings the same way; GNU Prolog's representation is a useful one for this problem.

It's unclear whether this counts as using regex or not. It's not using any regex-like feature, but the entire semantics of the language are similar to those of regex.

New version (uses the recursion trick seen in some other answers):

```
s(X):-append(A,B,X),(A=B;A\=X,B\=X,s(A),s(B)).

```

Older version:

```
s(X):-X=[];append(A,B,X),B\=X,append(C,C,A),s(B).

```

This is a predicate (Prolog's equivalent of a function) called `s`, not a complete program. Use it like this:

```
| ?- s("aa").
true ?
yes
| ?- s("aaababbabbabbbababbaabaabaababaaba").
true ?
yes
| ?- s("baababbabaaaab").
no
| ?- s("bbbbbbbbbbbbbbb").
no

```

An interesting feature of the older solution is that if you ask the interpreter "are there more solutions?" via use of `;` at the `true ?` prompt (rather than asking "is there any solution" via pressing return at the prompt, like I did above), it returns "true" a number of times equal to the number of different ways the string can be expressed in the given form (e.g. it returns "true" twice with `s("aaaa").`, as this can be parsed as `(a a)(a a)` or as `(aa aa)`).

Prolog programs are often reversible (allowing `s` to *generate* a list of strings with the given property). The older one isn't (it goes into an infinite loop), but that's because of the golfed method I used to ensure that C is nonempty; if you rewrite the program to specify C as nonempty explicitly, it generates strings of the form "aa", "aabb", "aabbcc", and so on (Prolog being Prolog, it doesn't specify identities for the characters that make them up, just a specification of which characters are the same). The newer one generates strings of the form "aa", "abab", "abcabc", and so on; this is an infinite loop in its own right, and thus never hits the point at which it'd get stuck due to failing to detect a zero-length string.

# Answer
> 1 votes
## Brainfuck, 177 bytes

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

```

Formatted:

```
+[<<<<,]
>>>>
[
  >+
  [
    >+
    [
      [>>]
      <+<[<<]
      >+>-
    ]
    <[>+<-]>
    >>,>>[>>]
    +<<[<+> >-<-]
    <[>+<-]>
    >
    [
      not equal
      ,>[-<<<<]
      <[<<<<]
      >
    ]
    <
    [
      equal
      [<<]
      >
    ]
    >>
  ]
  >>
  [
    mismatch
    [>+>>>]
    >>>[>]
    <<<<
    [
      backtrack
      >+[-<<<,<]
      <
      [
        not done yet
        <<<
        [
          [<<<<]
          >>
        ]
        <
      ]
      >
    ]
    >>
  ]
  <
  [
    match
    [->>>>]
    >>[<]
    <
  ]
  <<
]
<.

```

Expects input without a trailing newline. Prints `\x00` for false and `\x01` for true.

Try it online.

This implements depth-first search. In particular: check for repeated prefixes of increasing length starting from the current suffix, then move to the next suffix if a match is found, otherwise backtrack.

At the beginning, the string is reversed and a sentinel `\x01` is placed at the end.

The tape is divided into 4-cell nodes. The memory layout of a node is:

`c h x 0`

where `c` is the character, `h` is a flag for whether the character is in the first half of a repeated prefix, and `x` is a flag to keep track of the current pair of characters being compared. The `h` flags stay in place while the `x` flags form a moving window.

If the string is pairable, the pointer lands next to the sentinel at the end of the main loop; otherwise, the pointer falls off the left side of the string while backtracking.

# Answer
> 1 votes
# Brachylog, 5 bytes

```
~c~jᵐ

```

Try it online!

Note that this algorithm can take a *very* long time, especially on falsey cases, since it checks every possible partition of the input string.

### Explanation

```
~c     Reversed concatenate: find a list that, when concatenated, results in the input string
       This examines all partitions of the input
  ~jᵐ  Map reversed juxtapose: for each string in that list, is it the result of concatenating
       a string to itself?

```

For an input string like `"ababcc"`, `~c` tries different partitions until it comes to `["abab", "cc"]`, at which point `~j` succeeds for both items of the list,  outputs `["ab", "c"]`, and the predicate succeeds.

# Answer
> 1 votes
# , 31 bytes

```
grepl("^((.+)\\2)+$",scan(,""))

```

Try it online!

Based on Retina answer.

# , 129 bytes

And here’s an original, non-regex answer:

```
o=(y=utf8ToInt(scan(,"")))<0;for(i in 2*1:(sum(y>0)/2))for(j in 1:(i/2)){w=i:(i-j+1);v=w-j;if(all(y[w]==y[v]))o[c(v,w)]=T};all(o)

```

Try it online!

# Answer
> 0 votes
# Lithp, 57 characters

```
#S::((? (!= (null) (match S "^((.+)\\2)+$")) true false))

```

Sample usage:

```
% pairable_strings.lithp
(
    (def f #S::((? (!= (null) (match S "^((.+)\\2)+$")) true false)))
    (print (f "aa"))
    (print (f "aabaaababbbaba"))
    (print (f "aaababbabbabbbababbaabaabaababaaba"))
    (print (f "ba"))
)

# ./run.js pairable_strings.lithp
AtomValue { value: 2, type: 'Atom', name: 'true' }
AtomValue { value: 2, type: 'Atom', name: 'true' }
AtomValue { value: 2, type: 'Atom', name: 'true' }
AtomValue { value: 3, type: 'Atom', name: 'false' }

```

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