title: Sing Baby Shark

text:
# Question
Title: Sing Baby Shark
> "Baby Shark" is a children's song about a family of sharks. Having long been popular as a campfire song, it has been popularized since the mid-2000s by social media, online video and radio. - Wikipedia

Write program that takes no input, and writes the following text to the standard output or an arbitrary file:

```
Baby Shark doo doo doo doo doo doo
Baby Shark doo doo doo doo doo doo
Baby Shark doo doo doo doo doo doo
Baby Shark!
Daddy Shark doo doo doo doo doo doo
Daddy Shark doo doo doo doo doo doo
Daddy Shark doo doo doo doo doo doo
Daddy Shark!
Mommy Shark doo doo doo doo doo doo
Mommy Shark doo doo doo doo doo doo
Mommy Shark doo doo doo doo doo doo
Mommy Shark!
Grandpa Shark doo doo doo doo doo doo
Grandpa Shark doo doo doo doo doo doo
Grandpa Shark doo doo doo doo doo doo
Grandpa Shark!
Grandma Shark doo doo doo doo doo doo
Grandma Shark doo doo doo doo doo doo
Grandma Shark doo doo doo doo doo doo
Grandma Shark!

```

This is code golf — shortest code wins.

Found this on Reddit^^, and it seems like an interesting challenge to golf.

**Updates:**

No newline between stanzas, that makes it too easy :)

Leading/trailing newlines are okay.

# Answer
# SOGL, 40 bytes

```
o⅝ηvΒvPΝ┘÷ΖnΨ‘θ{"nOe;‘+ū:" doo”6*+TTPPļ!

```

Try it here!
> 13 votes

# Answer
## Emojicode, 292 bytes (140 characters)

```
Baby➡bDaddy➡yMommy➡oGrandpa➡gGrandma➡a Shark➡s doo➡db y o g a➡fm fi⏩⏩0 3❗m s d d d d d d❗m s!❗

```

Run it

Expanded out:

```

  Baby ➡ b
  Daddy ➡ y
  Mommy ➡ o
  Grandpa ➡ g
  Grandma ➡ a
   Shark ➡ s
   doo ➡ d
  b y o g a➡f
  m f
    i⏩⏩0 3❗
      m s d d d d d d❗

    m s!❗

```

Explained (per the Emojicode doc):

```

```

The same as a `{` and `}` (e.g. a code block)

```

```

The "program start" (e.g. `int main()`)

```
Baby ➡ b

```

Variable assignment (e.g. `const char* b = "Baby";`)

```
b y o g a➡f

```

Says, create a list of values between and and assign (➡) to `f` (e.g. `const char* f[] = {b,y,o,g,a};`)

```
m f ...

```

This line says to loop over the elements in `f` using the alias `m`, where the `...` is the code between and .

```
 i ⏩⏩ 0 3❗ ...

```

This line says to loop over the range \[0,3), where the `...` is the code between and .

```
 ... ❗

```

This line says to print the format specified in `...` (e.g. `printf("%s\n");`)

The code translated to C:

```
#include <stdio.h>

int main() {
  const char* b = "Baby";
  const char* y = "Daddy";
  const char* o = "Mommy";
  const char* g = "Grandpa";
  const char* a = "Grandma";
  const char* s = " Shark";
  const char* d = " doo";
  const char* f[] = {b,y,o,g,a};
  int m = 0, i = 0;
  for (; m < 5; ++m) {
    for (i = 0; i < 3; ++i) {
      printf("%s%s%s%s%s%s%s%s\n", f[m], s, d, d, d, d, d, d);
    }
    printf("%s%s!\n", f[m], s);
  }
  return 0;
}

```

Following this, the original code (posted below for posterity) had some issues; mostly that the block was not included for those who wish to run it, and the emoji's were not actually properly escaped, to that, here is the actual running version of that code:

## Original modified to run: Emojicode, 224 bytes (67 characters)

```
➡fm fi⏩⏩0 3❗m❗m!❗

```

Expanded out:

```

   ➡ f
   m f
     i ⏩⏩ 0 3❗
      m❗

    m!❗

```

Which produces the output:

```

!

!

!

!

!

```

Run it

Where in you have the individual emoji's representing the words:

```
 -> Baby
 -> Daddy
 -> Mommy
 -> Grandpa
 -> Grandma
 -> Shark
 -> doo

```

## Original: Emojicode, 138 bytes (47 characters)

```
➡fm fi⏩⏩0 3❗m❗m!❗

```

Expanded out:

```
➡f
m f
   i ⏩⏩ 0 3❗
     m ❗

   m !❗

```
> 83 votes

# Answer
# x86-16 machine code, IBM PC DOS, ~~108~~ 107 bytes

```
00000000: bd42 01e8 1600 bd47 01e8 1000 bd4d 01e8  .B.....G.....M..
00000010: 0a00 bd53 01e8 0400 c646 056d b409 b104  ...S.....F.m....
00000020: 8bd5 cd21 ba5b 01cd 21e2 06ba 6701 cd21  ...!.[..!...g..!
00000030: c3b3 06ba 6201 cd21 4b75 fbba 6801 cd21  ....b..!Ku..h..!
00000040: ebde 4261 6279 2444 6164 6479 244d 6f6d  ..Baby$Daddy$Mom
00000050: 6d79 2447 7261 6e64 7061 2420 5368 6172  my$Grandpa$ Shar
00000060: 6b24 2064 6f6f 2421 0d0a 24              k$ doo$!..$

```

Unassembled:

```
BD 0142         MOV  BP, OFFSET BABY        ; Baby Shark
E8 011C         CALL VERSE
BD 0147         MOV  BP, OFFSET DADDY       ; Daddy Shark
E8 011C         CALL VERSE
BD 014D         MOV  BP, OFFSET MOMMY       ; Mommy Shark
E8 011C         CALL VERSE
BD 0153         MOV  BP, OFFSET GRAND       ; Grandpa/ma Shark
E8 011C         CALL VERSE
C6 46 05 6D     MOV  BYTE PTR [BP][5], 'm'  ; change 'p' to 'm'
            VERSE:
B4 09           MOV  AH, 9                  ; DOS API display string function
B1 04           MOV  CL, 4                  ; loop verse counter
            LOOP_VERSE:
8B D5           MOV  DX, BP                 ; load shark name from BP
CD 21           INT  21H                    ; display shark name
BA 015B         MOV  DX, OFFSET SHARK       ; load 'Shark'
CD 21           INT  21H                    ; display 'Shark'
E2 06           LOOP LOOP_DOO               ; if not last line, write 'doo's
BA 0167         MOV  DX, OFFSET BANG        ; otherwise end with a bang
CD 21           INT  21H                    ; display !, CRLF
C3              RET                         ; return from CALL or to DOS
            LOOP_DOO:
B3 06           MOV  BL, 6                  ; loop 'doo' 6 times
BA 0162         MOV  DX, OFFSET DOO         ; load 'doo' string
            PRINT_DOO:
CD 21           INT  21H                    ; display 'doo'
4B              DEC  BX                     ; decrement doo count
75 FB           JNZ  PRINT_DOO              ; if not last doo, start again
BA 0168         MOV  DX, OFFSET CRLF        ; load CRLF string
CD 21           INT  21H                    ; display CRLF
EB DE           JMP  LOOP_VERSE             ; repeat verse

BABY    DB  'Baby$'
DADDY   DB  'Daddy$'
MOMMY   DB  'Mommy$'
GRAND   DB  'Grand'
PA      DB  'pa$'
SHARK   DB  ' Shark$'
DOO     DB  ' doo$'
BANG    DB  '!'
CRLF    DB  0DH,0AH,'$'

```

Try it online!

***Output***

*(TODO: update this screenshot for one less byte...)*
> 42 votes

# Answer
# Python 2, 93 bytes

```
for w in"Baby Daddy Mommy Grandpa Grandma".split():w+=" Shark";print(w+" doo"*6+"\n")*3+w+"!"

```

Try it online!

**94 bytes**

```
for w in"Baby Daddy Mommy Grandpa Grandma".split():print((" doo"*6+"\n%s Shark"%w)*4)[25:]+"!"

```

Try it online!
> 21 votes

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

```
“‡ÍÊÐ¢×myîºpaîºma“#ð«'ã¢«™v…doo6иyšÐy'!«»

```

~~Last part `v4FN3Qiy'!«ë…doo6иyšðý},` can definitely be golfed a bit..~~ And I was right, -9 bytes thanks to *@Emigna* (even more than I was expecting).

Try it online.

**Explanation:**

```
“‡ÍÊÐ¢×myîºpaîºma“ # Push dictionary string "baby daddy mommy grandpa grandma"
 #                 # Split by spaces: ["baby","daddy","mommy","grandpa","grandma"]
  ð«               # Append a space to each
    'ã¢«          '# Append dictionary string "shark" to each
        ™          # Title-case each word
v                  # Loop `y` over these strings
 …doo              #  Push string "doo"
     6и            #  Repeat it 6 times as list
       yš          #  Prepend the string `y` at the front of the list
         Ð         #  Triplicate this list
 y'!«             '#  Push string `y`, concatted with a "!"
 »                 #  Join everything on the stack by newlines
                   #  (and each list implicitly by spaces)
                   # (and after the loop, output the result implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `“‡ÍÊÐ¢×myîºpaîºma“` is `"baby daddy mommy grandpa grandma"` and `'ã¢` is `"shark"`.
> 20 votes

# Answer
# PowerShell, ~~88~~ ~~86~~ ~~85~~ ~~80~~ ~~79~~ 76 bytes

-5 bytes thanks to @mazzy
-1 byte thanks to @Joey
-3 bytes thanks to @AdmBorkBork

```
echo Baby Daddy Mommy Grandpa Grandma|%{,(($a="$_ Shark")+" doo"*6)*3;"$a!"}

```

Try it online!

We've certainly come a long way.

# PowerShell (with Text to Speech), 156 bytes

This is NOT up to spec, but it's kinda funny. Thanks to @rkeet for the idea!

```
Add-Type -a System.Speech;echo Baby Daddy Mommy Grandpa Grandma|%{(New-Object Speech.Synthesis.SpeechSynthesizer).Speak((($a="$_ Shark")+" doo"*6)*3+" $a")}

```

.NET Text to speech pronunciation is... well... interesting. Keep this in mind when listening. Enjoy!
> 14 votes

# Answer
# Java (JDK), 135 bytes

```
v->{for(var s:"Baby Daddy Mommy Grandpa Grandma".split(" "))System.out.println(((s+=" Shark")+" doo".repeat(6)+"\n").repeat(3)+s+"!");}

```

Try it online!
> 12 votes

# Answer
# Haskell, 122 113 108 106 104 bytes

```
s=" Shark";m=do x<-words"Baby Daddy Mommy Grandpa Grandma";("aaa">>x++s++(s>>" doo")++"\n")++x++s++"!\n"

```

Try it online!

* `"aaa">>x` replicates `x` 3 times, as `"aaa"` has length 3.
* `s>>" doo"` replicates `" doo"` 6 times, as `" Shark"` has length 6!
* *2 bytes saved thanks to @Fox*
* *2 bytes saved thanks to @Laikoni*
> 11 votes

# Answer
# Retina 0.8.2, ~~77~~ ~~75~~ 74 bytes

```

Baby¶Daddy¶MommyGpaGma
G
¶Grand
.+
$&s$&s$&s$&S!
s
S6$*O¶
O
 doo
S
 Shark

```

Try it online! Explanation:

```

Baby¶Daddy¶MommyGpaGma
G
¶Grand

```

Insert the relations on separate lines.

```
.+
$&s$&s$&s$&S!¶

```

Expand into four lines.

```
s
S6$*O¶
O
 doo
S
 Shark

```

Expand the placeholders.

~~69~~ 68 bytes in Retina 1:

```

Baby¶Daddy¶MommyGpaGma
G
¶Grand
.+
$& Shark
.+
3*$($&6*$( doo)¶)$&!

```

Try it online! Explanation:

```

Baby¶Daddy¶MommyGpaGma
G
¶Grand

```

Insert the relations on separate lines.

```
.+
$& Shark

```

Append Shark to each.

```
.+
3*$($&6*$( doo)¶)$&!

```

Expand into whole verses.
> 10 votes

# Answer
# Python 3, 105 97 96 bytes

```
for x in"Baby","Daddy","Mommy","Grandpa","Grandma":z=x+' Shark';print((z+' doo'*6+"\n")*3+z+"!")

```

Try it online!

A simple Python 3 solution. (9 bytes saved by Jo King and Quintec)
> 9 votes

# Answer
# bash, 78 bytes

```
printf %s\\n {Baby,Daddy,Mommy,Grand{p,m}a}\ Shark{" `echo doo{,,}{,}`"{,,},!}

```

TIO

73 bytes if trailing space is allowed

```
echo '
'{Baby,Daddy,Mommy,Grand{p,m}a}\ Shark{" `echo doo{,,}{,}`"{,,},!}

```
> 9 votes

# Answer
# Perl 6, ~~79~~ 78 bytes

```
(<Baby Daddy Mommmy Grandpa Grandma>X~" Shark"X~ |((" doo"x 6)xx 3),'!')>>.say

```

Try it online!

Pretty simple.

### Explanation:

```
 <...>X~                                  # Combine family members
        " Shark"X~                        # With "Shark" and
                   |((" doo"x 6)xx 3)     # doo repeated 6 times then 3 times
                                     ,'!' # Then !
(                                        )>>.say  # And print each line

```
> 7 votes

# Answer
# Ruby, 82 bytes

```
%w(Baby Daddy Mommy Grandpa Grandma).map{|a|puts [a+" Shark"]*4*(" doo"*6+?\n)+?!}

```

Try it online!
> 7 votes

# Answer
# ///, 124 bytes

```
/*/$!
//)/Grand//(/Baby//'/Mommy//&/Daddy//%/ doo//$/ Shark//#/a")//"/$%%%%%%
/("("("(*&"&"&"&*'"'"'"'*)p#p#p#pa*)m#m#m#ma$!

```

Try it online!
> 6 votes

# Answer
# JavaScript, 104 bytes

More golfing to follow.

```
_=>`Baby
Daddy
Mommy
Grandpa
Grandma`.replace(/.+/g,x=>(s=(x+=` Shark`)+` doo`.repeat(6)+`
`)+s+s+x+`!`)

```

Try It Online!
> 6 votes

# Answer
# PostgreSQL, ~~162~~ ~~156~~ 138 bytes

```
select a||' Shark'||replace(b,'1',repeat(' doo',6))from unnest('{Baby,Daddy,Mommy,Grandpa,Grandma}'::text[])a,unnest('{1,1,1,!}'::text[])b

```

Ungolfed

```
select
    a || ' Shark' || replace(b,'1',repeat(' doo',6))
from unnest('{Baby,Daddy,Mommy,Grandpa,Grandma}'::text[]) a
    ,unnest('{1,1,1,!}'::text[]) b

```

Saved ~~6~~ 24 bytes thanks to `@Nahuel Fouilleul`!

* use `||` instead of `concat()`
* use `unnest('{foo,bar}'::text[])` instead of `regexp_split_to_table('foo,bar')`

DB\<\>fiddle
> 6 votes

# Answer
# Emotion, 65 bytes

Explanation

```
 Push literal doo
 Push five copies of the first stack value.
 Collapse all stack values into a string seperated by spaces, then push that string.
 Push literal  Shark
 Push the difference of the second and first stack values.
 Store the first stack value in the a register.
 Push literal Grandma
 Push literal Grandpa
 Push literal Mommy
 Push literal Daddy
❤ Push literal Baby
 Push literal 6
 Push stack values into a list of the size of the first stack value starting with the second stack value.
 Enter an iteration block over the first stack value and push the iteration element register at the begining of each loop.
 Push three copies of the first stack value.
 Push literal 3
 Enter an iteration block over the first stack value.
 Push the value contained in the a register.
 Push the sum of the second and first stack values.
 Print the first stack value, then a newline.
 Ends a control flow structure.
 Push literal  Shark!
 Push the sum of the second and first stack values.
 Print the first stack value, then a newline.
 Ends a control flow structure.

```

Try it online!
> 6 votes

# Answer
# \>\<\>, ~~158~~ 115 bytes

*Saved a lot of bytes thanks to Jo King*

```
>4>1-&0'krahS '0l3-.
~ ^oa~<
ooo:?!/1-'ood 'o
\ao'!'^?$6:&~
\!?:o
^'ybaB'
^'yddaD'
^'ymmoM'
^'apdnarG'
^'amdnarG'
;

```

Try it online! You may also want to paste the code in at fishlanguage.com, where you can see an animation of it ~~swimming~~ running.
> 5 votes

# Answer
# Haskell, 97 bytes

```
unlines[x++s++p|x<-words"Baby Daddy Mommy Grandpa Grandma",p<-[a,a,a,"!"]]
s=" Shark"
a=s>>" doo"

```

Try it online!

This is an optimization of the Haskell solution by starsandspirals. The new trick is to iterate over the rows of each stanza with an inner loop, and join the lines using `unlines`, saving the need to explicitly insert newlines.

The suffixes of the four lines are `[a,a,a,"!"]`, where `a` is `" doo"` replicated 6 times with `a=s>>" doo"`, where starsandspirals cleverly reuses the six-character-long `s=" Shark"`. Writing `[a,a,a,...]` looks a bit silly, but I'm not seeing a shorter way.

A list-monad version is the same length but it looks cool.

```
unlines$(++).(++s)<$>words"Baby Daddy Mommy Grandpa Grandma"<*>[a,a,a,"!"]
s=" Shark"
a=s>>" doo"

```

Try it online!
> 5 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~153~~ 131 bytes

```
foreach(var i in"Baby Daddy Mommy Grandpa Grandma".Split()){var a=i+" Shark doo doo doo doo doo doo\n";Write(a+a+a+i+" Shark!\n");}

```

Thanks to @Destrogio for saving 30 bytes!

Try it online!
> 4 votes

# Answer
# whenyouaccidentallylose100endorsementsinnationstates \- ~~123,065~~ ~~121,716~~ ~~113,695~~ ~~100,889~~ 98,554 bytes

The program

~~I'll golf this later.~~ Done.

~~I'll golf this more (later)~~ Done.

~~I'll golf this even more later.~~ DONE.

~~I'll get the byte count to 5 digits later.~~ YAY.

I'll get the byte count to 4 digits (I don't know if this is possible, but I do know it is impossible to get 3 digits with my current approach).
> 4 votes

# Answer
# , ~~131~~ ~~122~~ 120 bytes

-9 bytes thanks to Giuseppe

-2 more bytes, also Giuseppe

```
`?`=c
s="Shark"
for(x in "Baby"?"Daddy"?"Mommy"?"Grandpa"?"Grandma")cat(rep("
"?x?s?rep("doo",6),3)?"
"?x?paste0(s,"!"))

```

Try it online!

Quite proud of this actually, especially with R being rather poor at handling strings. I started out using `cat(sapply(...))`, but realized a for loop shaves off a few bytes.

Abusing the `"?"=c` significantly reduced the amount of parentheses needed.

I also tried to do `"*"=rep` to repeat the individual lines of the stanzas and the "doos", but that did not shave off any bytes.

# 111 bytes

Giuseppe and ASCII-only's alternative, (and better) solution that fixes some spacing issues.

```
write(paste0(rep(c("Baby","Daddy","Mommy","Grandpa","Grandma"),,,4)," Shark",c(rep(strrep(" doo",6),3),"!")),1)

```

Try it online!
> 4 votes

# Answer
# C (gcc), ~~123~~ 122 bytes

-1 byte thanks to ceilingcat

```
#define A" doo doo"
f(i){for(i=20;i--;)printf("%.7s Shark%s\n","GrandmaGrandpaMommy\0 Daddy\0 Baby"+i/4*7,i%4?A A A:"!");}

```

Try it online!
> 3 votes

# Answer
# PHP, 104 bytes

```
foreach([Baby,Daddy,Mommy,Grandpa,Grandma]as$s)echo$t=$s.str_pad($u=" Shark",30," doo"),"
$t
$t
$s$u!
";

```

Run with `php -nr '<code>'` or try it online.
> 3 votes

# Answer
# , 139 138 137 bytes

```
s='Shark';d='doo';cat(paste(rep(c('Baby','Daddy','Mommy','Grandpa','Grandma'),e=4),c(rep(paste(s,d,d,d,d,d,d),3),paste0(s,'!'))),sep='
')

```

There's probably a better way to do the 'doo's but I wasn't able to get it.

**Edit:**
Replaced '\n' with actual new line at JDL's suggestion;
Removed trailing newline at Giuseppe's suggestion.

Try it online
> 3 votes

# Answer
# , ~~126~~ 125 bytes

```
cat(paste(rep(c("Baby","Daddy","Mommy","Grandpa","Grandma"),,,4),c(rep("Shark doo doo doo doo doo doo",3),"Shark!")),sep="
")

```

This doesn't feel as 'clever' as either CT Hall or Sumner18's answers, but by avoiding the overhead of defining variables it comes out smaller.

Try it online!

Edit: Saved 1 byte by using carriage return as per comment by Jonathan Frech
> 3 votes

# Answer
# Plain TeX, 147 Bytes

`\input pgffor\def\D{doo~}\def\d{\D\D\D\D\D\D}\def\S{Shark}\def\y{\x~\S~\d\par}\foreach\x in{Baby,Mommy,Daddy,Grandma,Grandpa}{\y\y\y\x~\S!\par}\bye`

Rather disappointing, but I haven't posted a TeX answer in ages. Loops are very verbose in teX (and looping over strings isn't even built-in so even this is a bit of a stretch)
> 3 votes

# Answer
# Jelly, 42 bytes

```
“¡N³»ẋ6Wẋ3;”!ṭ€;Y
“¡ʂɓṙṢ®ÑR+£ṭỤṙ»Ḳç€“¤⁾ċ»Y

```

**Try it online!**

### How?

```
“¡N³»ẋ6Wẋ3;”!ṭ€;Y - Link 1: make a verse: familyMember; space+animalName
                  -                        e.g. "Baby"; " Shark"
“¡N³»             - dictionary word " doo"
     ẋ6           - repeat 6 times -> " doo doo doo doo doo doo"
       W          - wrap in a list -> [" doo d..."]
        ẋ3        - repeat 3 times -> [" doo d..."," doo d..."," doo d..."]
           ”!     - literal '!' character
          ;       - concatenate    -> [" doo d..."," doo d..."," doo d...","!"]
               ;  - concatenate inputs ["Baby Shark"]
             ṭ€   - tack for €ach  -> [["Baby Shark"," doo d..."],...,["Baby Shark","!"]]
                Y - join with newline characters

“¡ʂɓṙṢ®ÑR+£ṭỤṙ»Ḳç€“¤⁾ċ»Y - Main Link: no arguments
“¡ʂɓṙṢ®ÑR+£ṭỤṙ»          - dictionary words "Baby"+" Daddy"+" Mommy"+" Grandpa"+" Grandma"
               Ḳ         - split at spaces -> ["Baby","Daddy","Mommy","Grandpa","Grandma"]
                  “¤⁾ċ»  - dictionary word " Shark"
                ç€       - call last Link (1) as a dyad for €ach
                       Y - join with newline characters
                         - implicit print

```
> 3 votes

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

```
”‡ÍÊÐ¢×myîºpaîºma”#„o€·À6×3и'!ª”ã¢”ìâ»

```

Try it online!

```
”‡ÍÊÐ¢×myîºpaîºma”                # compressed string "Baby Daddy Mommy Grandpa Grandma"
                  #               # split on spaces
„o€·                              # dictionary string "o do"
    À                             # rotated left: " doo"
     6×                           # string-repeat 6 times: " doo doo doo doo doo doo"
       3и                         # list-repeat 3 times
         '!ª                      # append "!" to that list
            ”ã¢”ì                 # prepend "Shark" to each element of that list
â                                 # cartesian product
 »                                # join by newlines
                                  # implicit output

```
> 3 votes

# Answer
# APL (Dyalog Unicode), 72 bytes (SBCS)

```
↑,(,∘' Shark'¨'BabyDaddyMommyGrandpaGrandma'(∊⊂⊣)⎕A)∘.,'!',⍨3⍴⊂24⍴' doo'

```

Try it online!

Explanation:

```
↑,(,∘' ..'¨'...'(∊⊂⊣)⎕A)∘.,'!',⍨3⍴⊂24⍴' doo'
                                   24⍴' doo'⍝ repeat 'doo' 6 times
                                  ⊂         ⍝ box the 'doo's
                                3⍴          ⍝ make three copies
                           '!',⍨            ⍝ append a `!` at the end
           '...'(∊⊂⊣)⎕A                     ⍝ split the long string on capitals
   ,∘' ..'¨                                 ⍝ append to all family members
                        ∘.,                 ⍝ construct a table where each row is
                                            ⍝ a full verse of the song
↑,                                          ⍝ flatten the resulting verse table

```

-28 thanks to @Adám

-2 bytes (-14 before; but I did a few golfs before checking the golfed version) thanks to @Razetime
> 3 votes

# Answer
# cQuents, ~~93~~ 89 bytes

```
|
#20&bk)~" Shark"~(" doo"6,Z,Z,bk)~" Shark!"
:"Baby","Daddy","Mommy","Grandpa","Grandma"

```

Try it online!

Note that as of posting TIO is not updated to the latest version, so the TIO link may not work.

## Explanation

```
|                               Set delimiter to newline
#20                             n = 20
   &                            Output first n terms in sequence
                                k = 1
                                First term is
    bk)~" Shark"                 kth term from the third line concatenated to " Shark"
                ~(" doo"6,        concatenated to " doo" repeated 6 times
Z,Z,                            Second and third terms equal the first term
    bk)~" Shark!"               Fourth term is the kth term from the third line concatenated to " Shark!"
                                k += 1, restart

Third line                      5 terms, each a string

```
> 2 votes

# Answer
# JavaScript (Node.js), 132 bytes

Probably very golf-able. Generates the "doo doo" line, then creates three of those with the "!" line after, and repeats this for each shark.

```
a=""
c=" doo"
for(b of["Baby","Daddy","Mommy","Grandpa","Grandma"]){b+=" Shark"
t=b+c+c+c+c+c+c+"\n"
a+=t+t+t+b+"!\n"}console.log(a)

```

Try it online!
> 2 votes

# Answer
# Japt `-R`, 55 bytes

Pretty naïve first pass.

```
`baß'adÝcomæ²T\`èT\`µ`qi Ë'!i4Æ` Srk`iDhDÎuÃqRi6ç` ºo

```

Test it
> 2 votes

# Answer
# Stax, 43 bytes

```
ÇÉ╕µM%╠2'§t╪╝½ôòn=n╢/╬╦Φ▲Vêø■T⌂g^N┴W.ìC↕ƒ·Φ

```

Run and debug it
> 2 votes

# Answer
# PHP, ~~153~~ 147 bytes

```
<?php $s='Shark';$d=str_pad('',23,'doo ');foreach(explode(' ','Baby Daddy Mommy Grandpa Grandma')as$a){echo str_repeat("$a $s $d\n",3),"$a $s!\n";}

```

Thanks to @manatwork for saving 6 bytes by pointing out `str_pad('',23'doo ');` is shorter than `rtrim(str_repeat('doo ',6));`

Try it online!
> 2 votes

# Answer
**JavaScript (~~134~~ 126 bytes)**

-2 bytes thanks to Stephen! -6 bytes thanks to mgthomas99!

```
["Baby","Daddy","Mommy","Grandma","Grandpa"].forEach(a=>console.log((a+" shark"+" doo".repeat(6)+"\n").repeat(3)+a+" Shark!"))

```

JS Fiddle
> 2 votes

# Answer
# jq, 87 characters

```
" Shark"as$s|("Baby Daddy Mommy Grandpa Grandma"/" ")[]|(.+$s+" doo"*6+"\n")*3+.+$s+"!"

```

Sample run:

```
bash-4.4$ jq -nr '" Shark"as$s|("Baby Daddy Mommy Grandpa Grandma"/" ")[]|(.+$s+" doo"*6+"\n")*3+.+$s+"!"'
Baby Shark doo doo doo doo doo doo
Baby Shark doo doo doo doo doo doo
Baby Shark doo doo doo doo doo doo
Baby Shark!
Daddy Shark doo doo doo doo doo doo
Daddy Shark doo doo doo doo doo doo
Daddy Shark doo doo doo doo doo doo
Daddy Shark!
Mommy Shark doo doo doo doo doo doo
Mommy Shark doo doo doo doo doo doo
Mommy Shark doo doo doo doo doo doo
Mommy Shark!
Grandpa Shark doo doo doo doo doo doo
Grandpa Shark doo doo doo doo doo doo
Grandpa Shark doo doo doo doo doo doo
Grandpa Shark!
Grandma Shark doo doo doo doo doo doo
Grandma Shark doo doo doo doo doo doo
Grandma Shark doo doo doo doo doo doo
Grandma Shark!

```

Try it online!
> 2 votes

# Answer
# Jelly, 51 bytes

```
;“¤⁾ċ»;“¡N³»ẋ6¤;”¶ẋ3;;“ß<Ė»
“þɗ“¡þ"“£H$“æf⁵“æeⱮ»Ç€Y

```

Try it online!

Jelly isn't the best for string manipulation. Still pretty good.

If you expand out the strings to their ungolfed form, the code looks like this:

```
;“ Shark”;“ doo”ẋ6¤;“¶”ẋ3;;“ Shark!”
“Baby“Daddy“Mommy“Grandpa“Grandma”Ç€Y

```

(The string compression was done using user202729's compressor).

```
;“ Shark”;“ doo”ẋ6¤;“¶”ẋ3;;“ Shark!”   Helper Link; take a string and format it into a stanza
;“ Shark”                              Append " Shark" to the string
         ;                             Join
                  ¤                    Previous links as a single nilad
          “ doo”                       " doo"
                ẋ6                            repeated 6 times
                   ;“¶”                Append a newline
                       ẋ3              Repeat 3 times
                         ;             Append the string
                          ;“ Shark!”   Append " Shark!"
“Baby“Daddy“Mommy“Grandpa“Grandma”Ç€Y  Main link
“Baby“Daddy“Mommy“Grandpa“Grandma”     ["Baby", "Daddy", "Mommy", "Grandpa", "Grandma"]
                                  Ç€   For each of these words, format it into the stanza with that family position
                                    Y  Join by newlines

```
> 2 votes

# Answer
# Farm, ~~1157~~ 897 bytes

<sup>-260 bytes: apparently only `cock a doodle doo` needs spaces..</sup>

No sharks on my farm:

```
cock a doodle doomoocotmoobzzcoucoumewmewmewmewmewmewmewgobblehihihimoopiuarfarfarfarfarfarfarfrouuuleomoopiumoosquealhihihimewmooleoarfarfarfrouuuleomoomoocotmoopiuarfarfarfmooleoarfarfarfarfmoomoocoucouarfarfarfssscoinsssgruntcoinblatcoinssscoinblatcoinssscoinblatmoosssgruntmooblatarfarfarfarfarfarfsssmoogruntmoogruntmoogruntgruntcoincoincoinmewblatmoosssmooblatmoosssmooblatcoinmewblatcoinsssgruntcoinblatcoinssscoinblatcoinssscoinblatmoosssgruntmooblatcotarfgruntsssmewblatmoosssmooblatmoogobblesquealmewmoopiuarfmoopiumooroararfmooarfarfarfarfarfarfarfarfarfarfmoohihihimooarfarfmooarfarfarfmoopiumoosssmewmooarfcoinblatroararfarfarfmoomoohihihimooleoarfarfrouuuleomooleomooleoarfarfmooarfarfarfarfarfarfarfarfarfmoomoohihihipiumooleoarfarfarfmoopiuarfarfarfmoomewmoopiumooleoarfarfarfarfarfmooroararfarfarfarfarfarfmooarfarfarfarfarfarfarfarfarfarfmoohihihimoomewmewmewsssmooblathihihihowl

```

Try it online!

---

<sub>†: Could be 9 less by using `cocorico` over `cock a doodle doo`..</sub>
> 2 votes

# Answer
## Javascript, ~~125~~ 123 bytes

```
['Baby','Daddy','Mommy','Grandpa','Grandma'].flatMap(x=>[...[,,,].fill(' doo'.repeat(6)),'!'].map(y=>x+' Shark'+y)).join`
`

```

Try it online!
> 2 votes

# Answer
# Kotlin **121 bytes**

```
"Baby Daddy Mommy Grandpa Grandma".split(" ").map{(println(("${"$it Shark${" doo".repeat(6)}\n".repeat(3)}$it Shark!")))}

```

Try it online!
> 2 votes

# Answer
# Befunge-93, 527 bytes

```
vv          <<
3v       v,<           v   v     v
0>" ybaB">:| p
<v         <^6#
         v,< 1
>>"krahS">:| "
 v06$      <0<v,,"!"*25
        v,<>^"$v       <
 >"ood ">:|^_^3         v,<
 ^0_v#:-1$< : \>" yddaD">:|
^   >$52*,1-^ "^0$ <      >
^             v     v      < v,<>
>">":62*1p62*#"1+1p^>" ymmoM">:|
^p-1:*27"1"p61<     0    >     >^
v p1-1*46">"p6<     $     v      <v,<
>"6"72*:p    #p     ^     >"dnarG">:|
v     p1*39">"<          ^  ,,,"pa "<
>"v"72*82*p            >$0^
v   p*28*48"m"<
>"@"72*6p              ^

```

Try it online!

I didn't really try to golf it much, I just wanted it to work. It does, and I'm pretty proud of it. I used the "p" command heavily to reuse a lot of code.
> 2 votes

# Answer
# , 85 bytes

```
echo('Shark'(,&'!',~(24$' doo')(3#,:)@,~])@,~]);.2'Baby Daddy Mommy Grandpa Grandma '

```

Try it online!

Note: This assumes a blank line between stanzas is ok. If that's not the case, prepending `,/` to my solution for +2 bytes.
> 1 votes

# Answer
# Attache, 79 bytes

```
$Baby'$Daddy'$Mommy'$Grandpa'$Grandma+" Shark":>Print@{(_+" doo"*6+lf)*3+_+"!"}

```

Try it online!

An attempt at compressing the above iteration array is `NTS@N=>Split[S@FromBase[Ords@")!-ZOW]NE.kK3(*F(a3\\z6fXD_\\yEM"-32,95],"00"]`, which is significantly longer than the trivial encoding above. Compressing the string using base conversion in its entirety would likely come out to be longer.

## Alternatives

**81 bytes:** `Print@{(_+" doo"*6+lf)*3+_+"!"}=>($Baby'$Daddy'$Mommy'$Grandpa'$Grandma+" Shark")`

**82 bytes:** `Output!{(_+" doo"*6+lf)*3+_+"!"}=>($Baby'$Daddy'$Mommy'$Grandpa'$Grandma+" Shark")`

**86 bytes:** `Output!(""'3&(" doo"*6+lf)'"!")&Join=>($Baby'$Daddy'$Mommy'$Grandpa'$Grandma+" Shark")`

**87 bytes:** `Output!(""'3&(" doo"*6+lf)'"!")&Join@`+&" Shark"=>$Baby'$Daddy'$Mommy'$Grandpa'$Grandma`
> 1 votes

# Answer
# Perl 5, 84 bytes

```
print (map{join(" doo"x6,("\n$_ Shark")x4),"!"}qw(Baby Daddy Mommy Grandpa Grandma))

```

Try it online!
> 1 votes

# Answer
# VBA (Excel), ~~152~~ 118 bytes

-34 bytes. Thanks @TaylorScott

Using Immediate Window.

~~`a=Split("Baby Daddy Mommy Grandpa Grandma"):b=" Shark":c=" doo":For d=0To 19:?a(Int(d/4))b &IIf((d+1)Mod 4=0,"!",Join(Split(String$(6,"."),"."),c)):Next`~~

```
a=Split("Baby Daddy Mommy Grandpa Grandma"):b=" Shark":For d=0To 19:?a(d\4)b;IIf((d+1)Mod 4,[Rept(" doo",6)],"!"):Next

```
> 1 votes

# Answer
# Clean, 134 bytes

```
import StdEnv,Text
r=repeatn
f=join"\n"[e+" Shark"+concat s\\e<-split" ""Baby Daddy Mommy Grandpa Grandma",s<-r 3(r 6" doo")++[["!"]]]

```

Try it online!
> 1 votes

# Answer
# F# (.NET Core), 179 bytes

```
["Baby";"Daddy";"Mommy";"Grandpa";"Grandma"]|>Seq.map(fun i->([0..2]|>Seq.map(fun _->i+" Shark doo doo doo doo doo doo")|>String.concat "\n")+"\n"+i+" Shark!")|>String.concat "\n"

```

Try it online!

No input, export to a string and to std output in a console.

# 145 bytes

```
for i in["Baby";"Daddy";"Mommy";"Grandpa";"Grandma"]do(for _ in[0..2]do printfn"%s"(i+" Shark doo doo doo doo doo doo"));printfn"%s"(i+" Shark!")

```

Try it online!

No input, export to std output
> 1 votes

# Answer
# F# (.NET Core), ~~160~~ 156 bytes

```
let c,r,s=String.concat,List.replicate," Shark"
let p n=r 3(c" "(n+s::r 6"doo"))@[n+s+"!"]
["Baby";"Daddy";"Mommy";"Grandpa";"Grandma"]|>Seq.collect p|>c"
"

```

Try it online!

And based on @aloisdg version, I get this one:

# F# (.NET Core), ~~130~~ 129 bytes

```
let p,d=printfn"%s Shark%s"," doo doo"
for i in["Baby";"Daddy";"Mommy";"Grandpa";"Grandma"]do(for _ in"123"do p i (d+d+d));p i"!"

```

Try it online!

Gaining 1 more char by changine \[0..2\] by "123" wich is also a sequence of 3 items...
> 1 votes

# Answer
## groovy, 96 bytes

```
'Baby Daddy Mommy Grandpa Grandma'.split().any{n="$it Shark";println((n+" doo"*6+'\n')*3+n+'!')}

```

Try it online!
> 1 votes

# Answer
# brainfuck, ~~627~~ ~~593~~ 573 bytes

```
Initialise Array with "Baby\0Daddy\0Mommy\0Grandpa\0Grandma"
Loop runs 71 times
++[++++++++++++++++++
    Get array cells to approximately correct values
    >>>+>>+++++>>+++++>>-->>>>+>>+++++>>+++++>>+++++>>-->>>>+>>-->>-->>-->>-->>>>+>>-->>+++++>>-->>+++++>>-->>+++++>>>>+>>-->>+++++>>-->>+++++>>-->>+++++
    [[<<]<<]>
]
Finish getting cells to correct values
>>>---->>->>>>++++++++>>+>>-->>->>++>>++>>++++++++>>+>>+++++++>>-->>---->>---->>++++++++>>+>>+>>+>>->>--->>++>>->>->>+>>+>>+>>->>--->>++>>---->>-
Inject ones between each cell in the array
[-<+<]>[>>]+

Initialise an exclamation mark; newline; and the string " Shark"
>>>+++++++++++[+++++++
    >------->+>>+>----->+++>+++>---->+++
    <<<<<<<<<
]
>->-->>--->++>->-------->-->++
[<]
Go to the end of the "Baby" Array to loop
<<<<<<[
    >>>
    Loop 3 times
    +++[-
        Go to the first value of the baby array
        <<<[<<]>>>
        Print the word out
        [.>>]
        Go to the shark array
        >[>>]>>>>>
        Print " Shark"
        [.>]
        <[<]
        Loop 6 times
        ++++++[-
            Print a space
            >.
            Change the 'a' in " Shark" to a 'd' and print
            >>>+++.---
            Change the 'r' in " Shark" to an 'o' and print twice
            >---..+++
            <<<<<
        ]
        Print newline
        <<.
        <
    ]
    Go to start of baby array
    <<<[<<]>>
    Print and consume the first string in the array
    ->[.[-]>->]
    Go to shark string
    >[>>]>>>>>
    Print " Shark"
    [.>]
    <[<]
    Print "!\n"
    <.<.
    <<<<
]

```

-20B thanks to Jo King

Try it online!
> 1 votes

# Answer
# T-SQL, 151 bytes

```
SELECT REPLACE(a.value+' Shark'+b.value,'Q',REPLICATE(' doo',6))
FROM STRING_SPLIT('Baby,Daddy,Mommy,Grandpa,Grandma',',')a,STRING_SPLIT('Q,Q,Q,!',',')b

```

Line break for readability only.

SQL's built-in function names are annoyingly long.

`STRING_SPLIT` works in SQL 2016 and later.

Order isn't 100% guaranteed without an `ORDER BY`, but this seemed to work in my testing.
> 1 votes

# Answer
# Japt `-R`, ~~58~~ 57 bytes

```
`BabysDaddysMommysGÎÀpGÎÀµ`qÅË±` Srk` +` ºo`³²+R ³+D+'!

```

Run it online
> 1 votes

# Answer
# Underload, ~~93~~ 89 bytes

```
(Grandma)(Grandpa)(Mommy)(Daddy)(Baby)(~( Shark)*:( doo)::**:**(
)*::**S(!
)*S):^:^:^:^:^

```

Since Underload is really good at duplicating and concatenation with strings, I decided to give this a go.

Saved 4 bytes by re-arranging things.

Try it online!

# Explanation

```
(Grandma)  Pushes 'Grandma'
(Grandpa)  Pushes 'Grandpa'
(Mommy)  Pushes 'Mommy'
(Daddy)  Pushes 'Daddy'
(Baby)   Pushes 'Baby'
(  Add the next bit of code to the stack
~  Swaps so the name of the Shark (eg: Baby) is on the top of the stack
( Shark)  Pushes ' Shark' to the stack
*  Concatenates ' Shark' to the name of the Shark
:  Duplicates the top of the stack
( doo)  Pushes ' doo'
::**:*  Turns it into ' doo doo doo doo doo doo'
*  Concatenates it to the '[name] Shark'
(<Newline>)*  Concatenates a newline to the string, making it '[Name] Shark doo doo doo doo doo doo[Newline]'
::**   Duplicates it twice
S  Outputs the first three lines of the stanza
(![Newline])*S Concatenates '![Newline]' to the '[Name] Shark' string and prints it
)  Ends the code being added to the stack
:^:^:^:^:  Runs the code in the bracket 5 times, for the 5 different stanzas

```
> 1 votes

# Answer
# Babylang, 2866 bytes

```
aaag aaag gagu aaag aaag aaag aaag aaag aaag aaag aaag aaag aaag aaag aaag aaag aaag aaag aaag aaag aaag gaga gaga gaga aaag gaga gaga aaag aaag aaag aaag aaag gaga gaga aaag aaag aaag aaag aaag gaga gaga uuug uuug gaga gaga gaga gaga aaag gaga gaga aaag aaag aaag aaag aaag gaga gaga aaag aaag aaag aaag aaag gaga gaga aaag aaag aaag aaag aaag gaga gaga uuug uuug gaga gaga gaga gaga aaag gaga gaga uuug uuug gaga gaga uuug uuug gaga gaga uuug uuug gaga gaga uuug uuug gaga gaga gaga gaga aaag gaga gaga uuug uuug gaga gaga aaag aaag aaag aaag aaag gaga gaga uuug uuug gaga gaga aaag aaag aaag aaag aaag gaga gaga uuug uuug gaga gaga aaag aaag aaag aaag aaag gaga gaga gaga gaga aaag gaga gaga uuug uuug gaga gaga aaag aaag aaag aaag aaag gaga gaga uuug uuug gaga gaga aaag aaag aaag aaag aaag gaga gaga uuug uuug gaga gaga aaag aaag aaag aaag aaag gagu gagu gugu gugu guga gugu gugu guga gaga guga gaga gaga gaga uuug uuug uuug uuug gaga gaga uuug gaga gaga gaga gaga aaag aaag aaag aaag aaag aaag aaag aaag gaga gaga aaag gaga gaga uuug uuug gaga gaga uuug gaga gaga aaag aaag gaga gaga aaag aaag gaga gaga aaag aaag aaag aaag aaag aaag aaag aaag gaga gaga aaag gaga gaga aaag aaag aaag aaag aaag aaag aaag gaga gaga uuug uuug gaga gaga uuug uuug uuug uuug gaga gaga uuug uuug uuug uuug gaga gaga aaag aaag aaag aaag aaag aaag aaag aaag gaga gaga aaag gaga gaga aaag gaga gaga aaag gaga gaga uuug gaga gaga uuug uuug uuug gaga gaga aaag aaag gaga gaga uuug gaga gaga uuug gaga gaga aaag gaga gaga aaag gaga gaga aaag gaga gaga uuug gaga gaga uuug uuug uuug gaga gaga aaag aaag gaga gaga uuug uuug uuug uuug gaga gaga uuug gagu uuug gugu aaag gugu guga gaga gagu gaga gaga guga aaag gaga gaga gaga aaag aaag aaag aaag aaag aaag aaag aaag aaag aaag aaag gagu aaag aaag aaag aaag aaag aaag aaag gaga uuug uuug uuug uuug uuug uuug uuug gaga aaag gaga gaga aaag gaga uuug uuug uuug uuug uuug gaga aaag aaag aaag gaga aaag aaag aaag gaga uuug uuug uuug uuug gaga aaag aaag aaag gugu gugu gugu gugu gugu gugu gugu gugu gugu guga gaga uuug gaga uuug uuug gaga gaga uuug uuug uuug gaga aaag aaag gaga uuug gaga uuug uuug uuug uuug uuug uuug uuug uuug gaga uuug uuug gaga aaag aaag gagu gugu guga gugu gugu gugu gugu gugu gugu gagu gaga gaga gaga aaag aaag aaag gagu uuug gugu gugu gugu gagu gugu gugu guga gaga gaga gaga gagu guuu gaga gaga guga gaga gagu gaga gaga guga gaga gaga gaga gaga gaga gagu guuu gaga guga gugu gagu gugu guga aaag aaag aaag aaag aaag aaag gagu uuug gaga guuu gaga gaga gaga aaag aaag aaag guuu uuug uuug uuug gaga uuug uuug uuug guuu guuu aaag aaag aaag gugu gugu gugu gugu gugu guga gugu gugu guuu gugu guga gugu gugu gugu gagu gugu gugu guga gaga gaga uuug gaga gagu guuu gagu uuug guga gaga uuug gaga guga gaga gagu gaga gaga guga gaga gaga gaga gaga gaga gagu guuu gaga guga gugu gagu gugu guga gugu guuu gugu guuu gugu gugu gugu gugu guga

```
> 1 votes

# Answer
# GolfScript, 70 bytes

```
"Baby
Daddy
Mommy
Grandpa
Grandma"n/{" Shark"+" doo"6*n++...-25<"!"n}/

```

Try it online!

### Explanation:

```
"Baby
Daddy
Mommy
Grandpa
Grandma"n/                                       Push shark names, then split by newline
          {                               }/     For each name:
           " Shark"+                                 Concatenate with Shark
                    " doo"6*n++                      add doo * 6 then newline
                               ...                   Duplicate line 3 more times
                                  -25<               Cut off the "doo"s
                                      "!"n           Add "!"

```
> 1 votes

# Answer
# Rockstar, ~~151~~ 125 bytes

```
cut "Baby,Daddy,Mommy,Grandpa,Grandma" in N with ","
while N
roll N in S
let L be S+" Shark"+" doo"*6+"
"
say L*3+S+" Shark!"

```

Try it here (Code will need to be pasted in)
> 1 votes

# Answer
# Vyxal, 48 bytes

```
`÷Ċ ₈Ȧ Mummy ∆ƛpa ∆ƛma`⌈` Ẏ꘍`+ƛ3(` doo`6*+,)\!+,

```

Try it Online!

A mess.

```
`...`⌈                         # Names, split on newlines
      `...`+                   # Append ' Shark' to each
            ƛ                  # Foreach...
             3(          )     # Three times
               ` doo`6*+,      # Append six doos and output
                          \!+, # Append a ! and output

```
> 1 votes

# Answer
**C (compiled with VC++ (Visual Studio 2017)) 536Bytes**

```
#include "stdafx.h"
#define d "doo "
#define p(x) printf(x);
#define n p("\n")
#define b p(f[i])p(" Shark ")
#define l(x,y) for(int x=0;x<y;x++)
void main(){const char*f[]={"Baby","Daddy","Mommy","Grandpa","Grandma"};l(i,5){l(k,3){b;l(j,6)p(d)n}b;p("\b!\n")}}

```

this is my naive try: it started from the "good version" where everything is done the neat and tidy way and i just removed the blanks, semicolons where possible and curly braces if possible. i changed main from int to void in order to be able to leave out the return Statement in the end if using a different Compiler (say gcc) the stdafx.h can be ommitted (visual Studio throws an error though (or i just dont know how to do it better...)) although then the use of printf means you either have to include stdio.h instead (=1byte win) or you have to use a Compiler flag to add this to the build path although not mentioned in the Code.... if its no dealbreaker if the exclamation mark is one space away from Baby Shark then the \b can be ommitted (=2 Byte win)
> 0 votes

# Answer
# Wolfram Language (Mathematica), 145 bytes

Nothing special, still thinking of a shorter method.

```
a={"Baby","Daddy","Mommy","Grandpa","Grandma"};c=" Shark";b=c<>StringJoin@Table[" doo",6];Do[Do[Print[a[[i]]<>b],3];Print[a[[i]]<>c<>"!"];,{i,5}]

```

Try it online!
> 0 votes

# Answer
# Emacs Lisp, 177 bytes

```
(defmacro w()`(princ(concat i" Shark doo doo doo doo doo doo\n")))
(defmacro z()`(princ(concat i" Shark!\n")))
(loop for i in'("Baby""Daddy""Mommy""Grandpa")do(and(w)(w)(w)(z)))

```
> 0 votes

# Answer
# C# (Visual C# Interactive Compiler), 139 bytes

```
"Baby Daddy Mommy Grandpa Grandma".Split().ToList().ForEach(x=>{string a=" doo",m=x+$" Shark{a+a+a+a+a+a}\n";Write(m+m+m+x+" Shark!\n");});

```

Try it online!

Any thoughts on improvements? I started aiming for a Linq-based solution with a `SelectMany` but the deferred execution failed me, along with `string.join` and `return x;` being quite verbose syntax
> 0 votes

# Answer
# Swift 4, 149 bytes

```
var s=" Shark";for i in["Baby","Daddy","Mommy","Grandpa","Grandma"]{for _ in 0...2{print(i+s+(0..<6).map({_ in" doo"}).reduce("",+))};print(i+s+"!")}

```

Try it online!
> 0 votes

# Answer
# Wolfram Language (Mathematica), 95 bytes

```
Do[Print[a," Shark"<>If[i>3,"!",Table[" doo",6]]],{a,{Baby,Daddy,Mommy,Grandpa,Grandma}},{i,4}]

```

Try it online!
> 0 votes

# Answer
# ink, ~~114~~ ~~113~~ 110 bytes

```
-(h)~temp t="{Baby|Daddy|Mommy|Grand{ma|pa}} Shark"
-(l){t}<>{l%4<1:
!
{h>5:->END}->h
}
-(d)\ doo{d%5:->d}
->l

```

Try it online!

# Explained

```
-(h)                                                   // A gather, we can jump here and keep track of how many times we've visited.
~temp t="{Baby|Daddy|Mommy|Grand{ma|pa}} Shark"        // The sequence takes on the next value each time it's visited, and we can nest them. Save into local variable t
-(l){t}<>{l%4<1:                                       // Print t and no newline, then if the number of times we've been here is divisible by 4...
!                                                      // Print an exclamation mark
{h>5:->END}->h                                         // Go to h, or halt if we've already been there more than 5 times
}
-(d)\ doo{d%5:->d}                                     // Print " doo" until we've done it a number of times that is a multiple of 5
->l                                                    // Go to l to print the next line

```
> 0 votes

# Answer
# Wren, ~~110~~ 108 bytes

```
Fn.new{["Baby","Daddy","Mommy","Grandpa","Grandma"].map{|i|((i=i+" Shark")+" doo"*6+"
")*3+i+"!"}.join("
")}

```

Try it online!
> 0 votes

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


title: Interpret underload

text:
# Question
Title: Interpret underload
## The challenge

Interpret the stack-based programming language underload.

The stack is a stack of strings that can be concatenated together.

Each underload program is a string of some of these instructions:

* `~`: Swap the top two elements of the stack.
* `:`: Duplicate the top element of the stack.
* `!`: Discard the top element of the stack.
* `*`: Concatenate the top two elements of the stack together.
* `(x)`: Push the string between the parenthesis to the stack. Parentheses can nest within strings, so `(a(bc)d)` should push the string `a(bc)d` to the stack, not `a(bc`.
* `a`: Enclose the top element of the stack in parenthesis.
* `^`: Pop the top element of the stack, and append it the program, directly after this instruction.
* `S`: Pop the top element of the stack and print it.

## Test cases

```
(Hello, world!)S
Hello, world!

(!@#$%^&*())S
!@#$%^&*()

(a)(b)~SS
ab

(a)(b)!S
a

(a)(b)*S
ab

(a)aS
(a)

(b)(a)^S
(b)

(a(:^)*S):^
(a(:^)*S):^

```

## Input

The input will be a string, either through STDIN, as an argument to a function, or however your programming language takes input.

You can assume the input will have matched parenthesis and will not attempt to run invalid instructions.

## Output

The output will also be a string.

This is code-golf, so the shortest answer in bytes is wins!

# Answer
# Python 3, ~~243~~ ~~242~~ 238 bytes

```
s=input()
q=[]
P=q.pop
d=w=i=0
while s[i:]:
 c=ord(s[i]);i+=1
 if 40==c:d+=1;w=[i,w][d>1]
 elif d:x=41==c;d-=x;q+=[s[w:i-1]][d:]*x
 else:y=P();exec("q+=y,y q+='(%s)'%y, q+=P()+y, print(end=y) y s=s[:i]+y+s[i:] q+=y,P()".split()[c%20%9%7])

```

Try it online!

**Pseudo Code:**

```
read program from STDIN into s
initialize
  empty stack q
  parenthesis nesting level d
  string start index w
  instruction pointer i

while the program has instructions left:
  get current instruction; increment instruction pointer

  if current instruction c is '(':
    increment parenthesis nesting level d
    update string start index if new nesting level is 1

  elif we are in a string:
    if the current command is ')':
      decrement nesting level d
      push string to stack if we reached level 0

  otherwise
    execute the code for the current command

```
> 9 votes

# Answer
# JavaScript (Node.js),  ~~237~~  221 bytes

*Saved 8 bytes thanks to @tsh*

```
f=([c,...s],S=p=[O=o=''])=>c?((n=Buffer(c)[0],n-40?n-41?p:--p||!S.push(o):p++)?o+=c:eval("o=''0(q=1,1)+q)0q=1,q)/1/s=[...1,...s]/01,1)0`(${1})`)/O+=1".replace(/\d/g,n=>+n?'S.pop()':'/S.push(').split`/`[n%15%11]),f(s,S)):O

```

Try it online!

### Commented

For readability, let's assign the list of commands to an explicit variable `cmd`:

```
cmd =
  "o=''0(q=1,1)+q)0q=1,q)/1/s=[...1,...s]/01,1)0`(${1})`)/O+=1"
  .replace(/\d/g, n => +n ? 'S.pop()' : '/S.push(')
  .split`/`

```

This expands to:

```
[
  "o=''",                          // non-nested closing parenthesis
  'S.push((q=S.pop(),S.pop())+q)', // '*' (concatenate)
  'S.push(q=S.pop(),q)',           // ':' (duplicate)
  'S.pop()',                       // '!' (drop)
  's=[...S.pop(),...s]',           // '^' (append to the program)
  '',                              // not used
  'S.push(S.pop(),S.pop())',       // '~' (swap)
  'S.push(`(${S.pop()})`)',        // 'a' (enclose)
  'O+=S.pop()'                     // 'S' (print)
]

```

The main code now reads as:

```
f = (                      // f is a recursive function taking:
  [ c,                     //   c   = next character
       ...s ],             //   s[] = array of remaining characters
  S =                      //   S[] = stack
  p = [                    //   p   = counter of opened parentheses
    O =                    //   O   = output string
    o = ''                 //   o   = current string
  ]                        //
) =>                       //
  c ?                      // if c is defined:
    (                      //
      (                    //   parentheses processing:
        n = Buffer(c)[0],  //     n = ASCII code of c
        n - 40 ?           //     if c is not an opening parenthesis:
          n - 41 ?         //       if c is not a closing parenthesis:
            p              //         yield p
          :                //       else:
            --p ||         //         pre-decrement p
           !S.push(o)      //         push o to the stack if p = 0
        :                  //     else:
          p++              //       post-increment p
      )                    //   end of parentheses processing
      ?                    //   if the above is truthy (i.e. we are
                           //   currently within a string definition):
        o += c             //     append c to o
      :                    //   else:
        eval(              //     evaluate the command which is indexed
          cmd[n % 15 % 11] //     by (n mod 15) mod 11
        ),                 //
      f(s, S)              //   recursive call to f
    )                      //
  :                        // else:
    O                      //   we're done: return the final output

```
> 9 votes

# Answer
# Stax, ~~88~~ 72 bytes

```
ï9╓╩¢▬'D└⌡○♠↨ó•ó♀▒m5E■V\╖O|é░xÄ9ª╝╬K╝╝∩1◄3`-2*♫▓☼╤?÷°ZôyZ┘¿{ClñI▀«╛■ß«R9

```

Run and debug it

I thought this would be simple with a stack based language. I was wrong.

Fixed a bug which caused `()` to immediately halt the program.

## Explanation

```
w # while top of stack isn't empty:
 yB # remove first char of program
 sY # store rest of program in register Y
 sc40= # is first char a '('?
 { # if true:
  d1y # delete char, push 1 and program
  { # take chars while the following returns true
   c.()# # is current char in "()"?
   {]"(^)v"|tl} #if so, if (, increment the 1 otherwise decrement
   {d}? # otherwise delete the char
   c copy the 1
  }h
  sdc%^Na)Yd # remove length + 1 chars from the program, store in Y
 }
 { # otherwise, execute stack command:
  sd] # delete copy of input
  "~s:c!d*+Sp^""y+Yd"97.:{3l+ # underload to stax translation array
  :t # translate the current char to stax
  l  # execute
 }?
 y # push y at the end(if empty, ends the program)

```
> 7 votes

# Answer
# Haskell, 322 bytes

Function is `l []`.

```
l(s:t:v)('~':x)=l(t:s:v)x
l(s:t)(':':x)=l(s:s:t)x
l(_:s)('!':x)=l s x
l(s:t:v)('*':x)=l((s++t):v)x
l(s:t)('a':x)=l(('(':s++")"):t)x
l(s:t)('^':x)=l t(s++x)
l(s:t)('S':x)=s++l t x
l t('(':x)=h t 0""x
h t 0a(')':x)=l(reverse a:t)x
h t n a(')':x)=h t(n-1)(')':a)x
h t n a('(':x)=h t(n+1)('(':a)x
h t n a(c:x)=h t n(c:a)x

```
> 5 votes

# Answer
# Retina, 157 bytes

```
.{/^S/&*>,G1`
^((\^)|[S!])(.*)¶(.*)|^:(.*(¶.*))
$#2*$4$3$5$6
^((~)|\*)(.*)¶(.*)(¶.*)
$3$5$#2*¶$4
^\((((\()|(?<-3>\))|[^()¶])*)\)(.*)
$4¶$1
^a(.*¶)(.*)
$1($2)

```

Try it online! Link includes test suite. Explanation:

```
.

```

Don't output the stack at the end of the program.

```
{

```

Repeat until the program has been processed (assuming no invalid instructions).

```
/^S/&*>,G1`

```

If the next instruction is `S` then print the top of the stack (this does not pop the stack yet).

```
^((\^)|[S!])(.*)¶(.*)|^:(.*(¶.*))
$#2*$4$3$5$6

```

If the next instruction is `S` or `!` then discard the top of the stack, but if it is `\^` then prepend it to the remainder of the program, while if it is `:` then duplicate the top of the stack.

```
^((~)|\*)(.*)¶(.*)(¶.*)
$3$5$#2*¶$4

```

If the next instruction is `~` then swap the two elements of the stack otherwise if it is `*` then join then together (this needs the elements to be swapped first, so the functions are combined here.)

```
^\((((\()|(?<-3>\))|[^()¶])*)\)(.*)
$4¶$1

```

If the next instruction is a `(` then push a (presumably) balanced string until the matching `)`. (If there aren't any `)`s then the interpreter will give up while if there aren't enough `)`s then the interpreter will match until the last one.)

```
^a(.*¶)(.*)
$1($2)

```

If the next instruction is an `a` then wrap the top of the stack in `(` and `)`.
> 5 votes

# Answer
# JavaScript (V8), 189 bytes

```
f=([C,...P],X=T=L='',Y,...S)=>C?eval(`f(P,${L*(L-=C=='('?-1:C==')')?'X+C,Y':`
^P.unshift(...X)&&Y
~Y,X
:X,X,Y
!Y
*Y+X
a'('+X+')',Y
S(T+=X,Y)
('',X,Y
)X,Y`.match(`
[${C}](.*)`)[1]},...S)`):T

```

Try it online!

```
f=(
[C,...P], // C = Current command; P = Following program
X= // X, Y = Top 2 of stack; S = Remaining stack
T= // Output
L='', // Current brackets level
Y,...S
)=>C? // Is program not finished?
// Recursive call fol following command
eval(`f(P,${
L*(L-=C=='('?-1:C==')')? // If currently we are in brackets
'X+C,Y': // We append this character to the top element of stack
// Otherwise, based on different command (1st letter each line)
// we execute different codes here
// And the the result is whatever placed on top of stack
`
^P.unshift(...X)&&Y
~Y,X
:X,X,Y
!Y
*Y+X
a'('+X+')',Y
S(T+=X,Y)
('',X,Y
)X,Y`.match(
// We use thi regex to get codes we need execute
`
[${C}](.*)`)[1]
},...S)` // Remaining stack
):T // Everything done, output goes here

```
> 4 votes

# Answer
# Haskell, ~~272~~ 252 bytes

```
([]?)
s?('(':r)|l<-1%r=(take(l-1)r:s)?drop l r
(x:s)?('^':r)=s?(x++r)
(x:s)?('S':r)=x++s?r
s?(c:r)=s!c?r
s?e=e
(x:y:s)!'~'=y:x:s
(x:s)!':'=x:x:s
(_:s)!'!'=s
(x:y:s)!'*'=(y++x):s
(x:s)!'a'=('(':x++")"):s
0%r=0
n%(c:r)=1+(n+sum[1|c=='(']-sum[1|c==')'])%r

```

Try it online!

The relevant function is `([]?)`, which takes an Underload program as a `String` as input and returns a `String` as output.

There is already an interesting Haskell answer, make sure to go upvote that as well (once it's fixed)! ~~I decided to post my own answer because, well, I finally found a use for the `Monad` instance of `(,) a`!~~ Yeah, I knew it couldn't last...
> 3 votes

# Answer
# Underload, 1 byte

```
^

```

**Try it online!**

If we assume the input program is put on the stack as an element (`(PROGRAM)`), then all that is required is to run that program!

*Note:* In the TIO, the header and footer wrap the "Code" section in parentheses, making it not run, but instead become an element at the top of the stack. Then at the end of the footer is the `^` which runs the code.

---

*This is only a joke/non-competing answer, since although interpreting languages in themselves isn't always trivial/boring, in this case it really is.*
> 3 votes

# Answer
# CJam, 80 bytes

```
{`(;);EDero}:S{[\\]`(;);"} {"/~+~}:B{a`"[]"Eer~}:Cq"()~:!*^a":D"{}\_;B~C":Eer~];

```

**Try it online!**

Could probably be a fair bit smaller ;)

---

### How it works

The interpreter is split into two parts: first, we define helper functions; then, we convert the Underload program into a CJam program and run it.

**Conversion**

```
q"()~:!*^a":D"{}\_;B~C":Eer

```

```
q                                Reads in the Underload program as a string
 "()~:!*^a"  "{}\_;B~C"  er      Replaces "(" with "{", ")" with "}", etc
           :D          :E        We take the opportunity to define these strings as D and E,
                                 since we have to "unreplace" when we print

```

**Helper functions**

We call the printing function `S` so we can avoid having to replace characters when `S` comes up in the Underload program.

```
{`(;);EDero}:S

```

```
{          }:S   Define a function named S
 `               Since the elements are represented as blocks, we have to turn the block into a
                 string
  (;);           On top of that, all the blocks are surrounded by 1 too many parentheses when  we
                 turn them into strings, so we remove those
      EDer       We translate backwards into Underload by "unreplacing" the special characters
          o      And then print and pop the string

```

We call the concatenation function `B` (for no particular reason).

```
{[\\]`(;);"} {"/~+~}:B

```

```
 [\\]                     Make an array with ONLY the top two elements of the stack
     `(;);                And turn it into a string (remembering to remove the square brackets
                          we got when we turned it into an array)
          "} {"/          The only gap between two curly brackets is between the two elements
                          that we want to merge, so we split along that gap
                ~+~       Then we merge and turn it back into a block

```

We call the array-enising function `C` (we unfortunately cannot use `a` as lowercase letters are reserved for language-defined functions)

```
{a`"[]"Eer~}:C
 a`               Array-enise our block in CJam and turn it into a string
   "[]"Eer        Replace the array characters with "{}" (luckily the extra characters
                  in E are ignored)
          ~       Convert it from a string to a block

```

**Running the converted program (& cleanup)**

It takes 1 character to run the converted program after we've made it: `~`.

After this we need to clean up our functions, since they are sitting on the stack and *will* be printed if we don't get rid of them. We do this by collecting everything left on the stack and popping it: `];`.
> 3 votes

# Answer
# Jelly, 93 bytes

```
“Ṫ,Ṫ;@“0ịṭ“Ṗ“Ṫ;@Ṫṭ“Ṫ⁾()jṭ“ṪȮṛ”W€“~:!*aS”żẎy
Żi@þØ(Ä_/Ṣ⁼Ø.ƊƝœp;1ÇṾ;”ṭWƊƭ€ṖẎ
ṪÇß}v⁼”^$?@ƒ
WÇṛ“”

```

Try it online!

This feels far too long!

A full program taking an Underload program as it’s argument and printing the output to STDOUT. In principle, translates the program to a series of Jelly chains and executes them, with special handling for the `^` command.
> 2 votes

# Answer
# Charcoal, 87 bytes

```
≔⪪⮌Ｓ¹θＷθ≡⊟θ~ＦＥ²⊟υ⊞υκ:⊞υ§υ±¹!≔⊟υδ*⊞υ⪫⮌Ｅ²⊟υω(⊞υ⭆⊖Ｌ⌊ΦＥθ…⮌θ⊕λ›№κ)№κ(⊟θa⊞υ⪫()⊟υ^Ｆ⪪⮌⊟υ¹⊞θκS⊟υ

```

Try it online! Link is to verbose version of code. Explanation:

```
≔⪪⮌Ｓ¹θ

```

Reverse the input and split it into characters so that it can be processed more easily.

```
Ｗθ≡⊟θ

```

Loop over each character in turn.

```
~ＦＥ²⊟υ⊞υκ

```

If it's a `~` then pop the top two elements from the stack and push them again, swapping them.

```
:⊞υ§υ±¹

```

If it's a `:` then duplicate the top element of the stack.

```
!≔⊟υδ

```

If it's a `!` then discard the top element of the stack.

```
*⊞υ⪫⮌Ｅ²⊟υω

```

If it's a `*` then concatenate the top two elements of the stack. (Annoyingly the elements pop in the wrong order.)

```
(⊞υ⭆⊖Ｌ⌊ΦＥθ…⮌θ⊕λ›№κ)№κ(⊟θ

```

If it's a `(` then find the shortest unbalanced prefix and push the characters up to the unbalanced `)` to the stack. (The `)` doesn't get removed but unrecognised characters get ignored anyway.)

```
a⊞υ⪫()⊟υ

```

If it's an `a` then wrap the top of the stack in `()`s.

```
^Ｆ⪪⮌⊟υ¹⊞θκ

```

If it's a `^` then push the top of the stack to the input.

```
S⊟υ

```

If it's a `S` then pop and print the top of the stack.
> 2 votes

---
Tags: code-golf, interpreter, underload
---


title: It almost works (Robbers' Thread)

text:
# Question
Title: It almost works (Robbers' Thread)
Cops' Thread

Your challenge is to find an uncracked, unsafe cop on the cops thread, and find an input value for which their code does not do as specified by the challenge.

You must use values within the bounds specified by the cop and the challenge - if a float breaks their program but they specified integers only, it's not a valid crack.

Use any submission on the specified challenge to find the correct value for any input - you probably want to check this against another submission.

# Scoring

Your score is the number of cops you have cracked, with higher score being better.

# Answer
# Python by Sisyphus for Is this number a prime?

\\$ 110728750366081 = 37 \times 41 \times 71 \times 661 \times 673 \times 2311 \\$ is wrongly recognized as a prime.

Try it online!

Sisyphus implemented the Solovay-Strassen primality test, which is based on a theorem by Euler which states for any prime number \\$p\\$ and any integer \\$a\\$:

$$ a^{p-1\over2} \equiv \left({a \over p}\right) \mod p, $$

where \\$\left({a \over p}\right)\\$ is the Jacobi symbol. The primality test usually draws a few random numbers for \\$a\\$ and assumes \\$p\\$ is a prime if the equality was satisfied for all \\$a\\$.
Because randomness doesn't work very well with , the long constant hardcodes a fixed set of values for \\$a\\$:

```
2, 3, 5, 7, 11, 13, 17, 19, 11617, 15493, 16433, 25919, 31091, 31469, 49307, 55001, 55399, 65071

```

For a given \\$a\\$ there exist composite numbers that satisfy the equivalence, these are called *Euler-Jacobi Pseudoprime* to base \\$a\\$.
To solve the challenge, one needs to a find a single positive integer that is a *Euler-Jacobi Pseudoprime* to all the bases. Bruteforcing this turned out to be infeasible, but this article mentions that some Carmichael numbers are *Euler-Jacobi Pseudoprime* to some base. By filtering a list of Carmichael numbers from this site¹, I was able to find a few solutions:

```
110728750366081 37*41*71*661*673*2311
237382308072001 29*101*127*337*631*3001
549022047900481 29*31*199*857*1381*2593
815369599393441 179*5741*6673*118903
1777021736490001 71*79*199*461*3453451
2409992788323121 29*67*499*20693*120121
5514474572006401 1051*2521*11551*180181
6036890513068801 43*71*101*40129*487873
9704292238761121 79*113*521*631*937*3529
14988701359951201 191*241*271*401*1051*2851
23456937465858961 37*43*71*103*181*821*13567
23880657211210801 23*61*109*157*271*937*3917
26055899070788161 31*173*433*1777*2437*2591
28365866503643761 43*53*137*281*443*457*1597
30908877197436001 421*601*1429*1709*50021
33834184755920641 29*37*71*73*97*547*114661
45561504118095001 211*421*751*3571*191251
51176905599093121 29*31*43*67*137*6427*22441
64612622789870401 97*181*277*647*691*29717
83629862695874881 181*881*953*4789*114913
132132263067090001 41*131*647*47501*800473
162098861806081201 71*421*2393*11047*205141
219842309289002401 23*29*71*151*337*3851*23689
283029750046243201 47*101*113*691*21841*34961
308601054690500881 29*37*41*331*691*4621*6637
314618527970346601 991*1093*3511*3571*23167
317711413912838401 43*53*73*79*113*3361*63649
397597753071953281 73*211*241*271*8317*47521
406954063186624801 29*37*41*191*3037*3221*4951
507180584040530401 89*163*281*397*463*743*911
511311312146194561 37*79*131*353*577*1361*4817
594232587298120681 29*71*127*1163*1171*1668629
650151107946325441 547*6553*35491*5110561
682696543350931201 315011*882029*2457079
685726732138361761 67*331*397*487*1567*102061
738294418360350721 89*353*5897*14081*283009
794134562259598561 23*79*89*157*241*2341*55441
806936176399473121 53*137*157*2731*4409*58787
830121613337016001 73*109*34651*53353*56431
963141865421809921 23*43*61*113*193*353*617*3361
```

¹The files are not actually gzipped, they are just plain text files
> 17 votes

# Answer
# Jelly by caird coinheringaahing for Is it double speak?

```
ṾḊṖŒœE

```

Try it online!

Uneval doesn't always surround the string in quotes. Since Jelly cannot escape string delimiters (and even if it could, the escape characters would cause it to fail), `““` unevaluates to `”“,”“` (literal character  followed by literal character ), which is not even an even-length string.
> 7 votes

# Answer
# Jelly by caird coinheringaahing for Is it double speak?

Original code:

```
ṾḊṖ⁼2/Ạ

```

Crack:

```
'

```

The explanation described removing quotes, so I just tried quotes.

Edit: Based on several other cracks by fireflame241 and Jonathan Allen that I only sniped by a matter of seconds, any odd-length string will also result in a crack.

Try it online!
> 3 votes

# Answer
# Jelly by caird coinheringaahing for Make a ;# interpreter

For `n > 127`, `;` repeated `n` times, then `#`.

Original: Try it online!

Broken: Try it online!
> 3 votes

# Answer
# Taxi by Stephen for Draw an asterisk triangle

```
9

```

Be sad online
> 3 votes

# Answer
# Javascript by Redwolf Programs for Is this even or odd?

```
x=>{var b=[...x.toString(2)].reverse()+"";try{eval.call(window,(t=y=>y?t(y/256n)+String.fromCharCode(Number(y%256n)):"")(x))}catch{};return +[...b][0]}

```

Crack input:

```
968040030946052874125008971077898749420224656625100629300118076307717369397814550869471412902654978373500023349257848576032587637596801109818665n

```

Outputs 0, which is wrong because the given number is odd.

This is the result of `f(s)` where `f` and `s` are

```
f=s=>[...s].map(c=>BigInt(c.charCodeAt())).reduce((x,y)=>x*256n+y)
s='Object.defineProperty(Array.prototype,0,{get:_=>0,set:_=>_})'

```

The payload basically fixes the index 0 of every single `Array` as 0 by defining the `0` property of `Array.prototype`. The getter returns 0 and the setter does nothing.

Does not work in Chrome console for security reasons, but you can try out the following full code by copy-pasting into an MDN demo window such as one on this page. The whole page will malfunction after the code runs, so be sure to close the tab after seeing the result :P

```
z=x=>{var b=[...x.toString(2)].reverse()+"";try{eval.call(window,(t=y=>y?t(y/256n)+String.fromCharCode(Number(y%256n)):"")(x))}catch{};return +[...b][0]}
f=s=>[...s].map(c=>BigInt(c.charCodeAt())).reduce((x,y)=>x*256n+y)
s='Object.defineProperty(Array.prototype,0,{get:_=>0,set:_=>_})'
console.log(n=f(s))
console.log(z(n))
console.log([10][0]) // bonus; shows what the code does

```

Output:

```
968040030946052874125008971077898749420224656625100629300118076307717369397814550869471412902654978373500023349257848576032587637596801109818665n
0
0

```
> 3 votes

# Answer
# Vyxal by A username for Stack Exchange Vote Simulator

```
C⁽꘍R:£80>[¥₁-±N|0

```

Try it Online!

Input of `^v`.

I don't think this even works for most of the test cases.
> 2 votes

# Answer
# Vyxal by Aaron Miller for Simple cat program

Any string - implicit output is with a trailing newline, so this is invalid no matter what.
> 2 votes

# Answer
# JavaScript by Redwolf Programs for "Hello, World!"

Input: `90071992547409929007199254740992`

Try it online!

Since all numbers in JavaScript are floating point, once numbers get big enough, adding and subtracting from them gets kinda weird.
> 2 votes

# Answer
# Vyxal by Wasif for Least Common Multiple

```
[2,1,2]

```

Or similar

Try it Online!
> 2 votes

# Answer
# Rattle by Daniel H., 3 bytes

```
|!p

```

Try it Online!

Fails for input `.1`. It seems that `|` just outputs the input but `p` will evaluate it? I am not sure exactly how this language works.
> 2 votes

# Answer
# Python 3 by *Gavin S. Yancey*, Is this number a prime?

The input `77833763775941059` is a prime, but evaluates as `False` in the answer given.

```
x=int(input())
print(x>1 and next(d for d in range(2,x+1)if x/d==x//d)==x)

```

Try it online!

`x/d==x//d` is the obvious culprit here. It's supposed to act like `x%d==0`, but due to precision issues it starts to falter for primes at around 17 digits.
> 2 votes

# Answer
# Python 3 by pajonk for Convert YYYYMM to MMMYY

Month 09 just outputs `'SER'` instead of `'SEP'`.

Try it online!
> 1 votes

# Answer
# Vyxal by A username for Find the first word starting with each letter

Original Code (40 bytes):

```
kBð\_9ɾṅṠ↔⌈:£ƛh⇩⅛¥ƛh⇩;¼ḟ¥$i=[|¤;;';ðvp∑Ṫ

```

Try it Online!

Crack:

Any word repeating without change.

example: `test test`, or `.test test` results in `test test`, while it should return `test`
> 1 votes

# Answer
# Jelly by Jonathan Allan for Generate Recamán's sequence

Input of `1024`.

Try it online!

As the challenge asks for a sequence involving some sort of recursion, I tried a large input (if something breaks early it probably will be carried on) and compared with correct answers in the challenge.

As pointed by @Stephen, the code actually breaks around input of `58`.
> 1 votes

# Answer
# Python 3 by Gavin S. Yancey for Is this number a prime?

Input is `1`. The program given loops forever on that input, and, since all programs are required to terminate, it is not a valid answer.

The challenge given even explicitly states that answers have to handle `1` as composite.
> 1 votes

# Answer
# Python by dingledooper for DDoouubbllee ssppeeaakk!!

```
'()'*200000

```

Try it online!

(that is, 200000 pairs of left right brackets in a row)

This is an application of Python Bug 5765 where a stack overflow can be caused by a large number of chained function calls. This doesn't work in modern versions of Python 3.
> 1 votes

# Answer
# Python by StardustGogeta for Simple cat program

Try it online!
> 0 votes

---
Tags: code-challenge, cops-and-robbers
---


title: When Fibonacci meets the Queens

text:
# Question
Title: When Fibonacci meets the Queens
*(inspired by Helka's response to my random pairing of "chess" and "Fibonacci" tags in chat)*

---

### Fibonacci

The Fibonacci numbers are one of the more well-known sequences in mathematics, where each number is composed by adding the two previous numbers together. Below is a definition of the zero-indexed sequence:

```
f(0) = 0
f(1) = 1
f(n) = f(n-1) + f(n-2)

```

This results in the sequence `0, 1, 1, 2, 3, 5, 8, 13, 21, ...` (OEIS link). In this challenge, we'll be focusing on only the strictly-positive values (so `1, 1, 2, 3, ...`), and you can choose zero-indexing or one-indexing, but please state which in your submission.

The Fibonacci numbers can be used for a tiling of the plane, by using squares that are successive `f(n)` in size, and aligning their edges together. The tiling is done in a counter-clockwise fashion, by placing squares in the pattern "right-up-left-down" from the current square. An example of this partial tiling for `f(8)=21`, with the starting square highlighted in blue, is as follows:

You can see the `f(1)=1` as the starting square (highlighted in blue), the `f(2)=1` square placed to the *right* of it, the `f(3)=2` square placed *up* from there, the `f(4)=3` square placed *left* and so on. The next square would be `f(9)=21+13=34` and would be placed to the bottom. This is the partial tiling method we'll be using in this challenge.

---

### The Queens

In the game of chess, the most powerful piece is the queen because it can move any number of spaces horizontally, vertically, or diagonally. In the below board diagram, the squares with a black circle show where the queen can move:

We'll define the term **coverage** as

> The percentage of squares that the queen can move to versus the total number of squares, given the queen's particular position on an empty board, and including the queen's own starting position.

For the example moves above, the queen's coverage is `28/64 = 43.75%`. If the queen was in the upper-right `h8` square, the coverage would be `22/64 = 34.375%`. If the queen was in `e7`, the coverage would be `24/64 = 37.5%`.

---

### The Challenge

We're going to use the Fibonacci tiling demonstrated above as our chess board for this challenge. You'll be given two positive integers as input, `n` and `x`:

* The `n` represents how large the tiling is. The example tiling above, with the `21` square on the left, is a board of size `n = 8` since `f(8) = 21` (when zero-indexed).
* The `x` represents which of the Fibonacci squares is used for the queen(s) placement, for calculating the coverage. The queens are placed one-at-a-time on each square in that particular Fibonacci square tile, and the total coverage is the summation of the individual (unique) coverage.

For example, here is an image of `n = 8` (the same tiling as above) and `x = 4` (corresponding to the `f(4) = 3` square, shaded blue). By placing a queen one-at-a-time into each of those nine blue squares, the queens can (combined) cover every square that's shaded orange. The total coverage in this example is therefore `309/714 = 43.28%`.

Quite obviously, any time that `n = x`, the coverage is going to be `100%` (for example, with `n=8` and `x=8`, you can see that every square on the entire board is going to be covered at least once). Conversely, with a suitably large `n` and `x=1` or `x=2`, the coverage is going to approach (but never reach) `0%` (for example, with `n=8` and `x=1`, the coverage is a paltry `88/714 = 12.32%`).

Given two such input numbers, you must output the coverage percentage, accurate to two decimal places. Please specify how your code handles rounding.

---

### Rules

* The input and output can be given in any convenient format, but must be accurate to two decimal places. Please specify how your code handles rounding.
* Assume no other pieces are on the board or otherwise interfere with the moves.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

---

### Examples

```
n = 8, x = 4
43.28

n = 8, x = 8
100 or 100.00

n = 8, x = 1
12.32

n = 4, x = 1
66.67

n = 4, x = 2
60 or 60.00

n = 5, x = 3
75 or 75.00

n = 5, x = 1
47.5 or 47.50

```

# Answer
# APL(Dyalog Unicode), 61 bytes SBCS

```
{2⍕100×(+/÷≢)∨⌿⊃∊⍤1⍥{⍉↑(⊢,+/,-/)¨⍸⍵}/1 0⌈{⌽⍉⍺,⍣(≢⍵)⍪⍵}/⌽⍺=⍳⍵}

```

Try it on APLgolf!

A pretty nice challenge for APL. This is an infix function that takes `x` on its left and `n` on its right, and returns the string representation of the rounded percentage. A full program would be 59 bytes (though I don't like using that I/O format because writing tests is cumbersome):

```
2⍕100×(+/÷≢)∨⌿⊃∊⍤1⍥{⍉↑(⊢,+/,-/)¨⍸⍵}/1 0⌈{⌽⍉⍺,⍣(≢⍵)⍪⍵}/⌽⎕=⍳⎕

```

### How it works

Constructs a boolean matrix representing the grid in question where 1 means a queen, and counts all the cells that share their row, column, diagonal, or anti-diagonal with some 1 cell.

```
{⌽⍉⍺,⍣(≢⍵)⍪⍵}/⌽⍺=⍳⍵    Part 1: construct the matrix; ⍺←x, ⍵←n
              ⌽⍺=⍳⍵    A boolean vector of length n with x-th from the end
                       marked as 1
{           }/    Reduce from right to left:
   ⍺,⍣(≢⍵)⍪⍵      Attach a square filled with ⍺ on the left of current matrix ⍵
 ⌽⍉               Rotate clockwise once
                  Reduction gives an enclosed matrix

∊⍤1⍥{⍉↑(⊢,+/,-/)¨⍸⍵}/1 0⌈    Part 2: Find possible Queen moves
                     1 0⌈    Get an all-ones matrix and the original matrix
   ⍥{              }/    Apply to each matrix:
                 ⍸⍵      Get all coordinates of ones
       (⊢,+/,-/)¨        For each coord [r, c], get [r, c, r+c, r-c]
                         (rownum, colnum, anti-diag-num, diag-num)
     ⍉↑                  Matrixify and transpose
∊⍤1    For each row, convert each number on its left side as 1 if
       it appears on the right on the same row
       The result is a 4-row matrix with each column representing a cell,
       where a 1 means that cell is reachable by moving in specific direction

2⍕100×(+/÷≢)∨⌿⊃    Part 3: Calculate average
               ⊃    Disclose the enclosed matrix
            ∨⌿     Boolean OR of each column
      (+/÷≢)       Average (reachable cells ÷ all cells)
2⍕100×             Percentage rounded to 2 decimal places

```
> 5 votes

# Answer
# VB.NET, (.NET 4.5), ~~1238~~ 1229 bytes

*-9 bytes thanks to @totallyhuman*

```
Function A(n,x)
Dim g=New List(Of List(Of Long))
g.Add(New List(Of Long))
g(0).Add(1)
For i=2To n
Dim b=1
If i>2Then
Dim w=0,y=1
b=w+y
For j=3To i
w=y
y=b
b=w+y
Next
End If
Select Case i Mod 4
Case 1
For j=1To b
Dim l=New List(Of Long)
For k=1To b
l.Add(i)
Next
g.Add(l)
Next
Case 2
For Each r In g
For j=1To b
r.Add(i)
Next
Next
Case 3
For j=1To b
g.Insert(0,New List(Of Long))
For k=1To b
g(0).Add(i)
Next
Next
Case 0
For Each r In g
For j=1To b
r.Insert(0,i)
Next
Next
End Select
Next
For i=0To g.Count-1
Dim c=g(i)
For j=0To c.Count-1
Dim e=c(j)
If e=x Then
For k=1To Math.Max(g.Count,g(0).Count)
If j-k>=0AndAlso c(j-k)<>x Then c(j-k)=0
If i-k>=0AndAlso g(i-k)(j)<>x Then g(i-k)(j)=0
If j+k<c.Count AndAlso c(j+k)<>x Then c(j+k)=0
If i+k<g.Count AndAlso g(i+k)(j)<>x Then g(i+k)(j)=0
If i-k>=0AndAlso j-k>=0AndAlso g(i-k)(j-k)<>x Then g(i-k)(j-k)=0
If i-k>=0AndAlso j+k<c.Count AndAlso g(i-k)(j+k)<>x Then g(i-k)(j+k)=0
If i+k<g.Count AndAlso j-k>=0AndAlso g(i+k)(j-k)<>x Then g(i+k)(j-k)=0
If i+k<g.Count AndAlso j+k<c.Count AndAlso g(i+k)(j+k)<>x Then g(i+k)(j+k)=0
Next
End If
Next
Next
Dim hits=0
For Each r In g
For Each c In r
If c=x Or c=0Then hits+=1
Next
Next
Return Math.Round(hits*100/(g.Count*g(0).Count),2)
End Function

```

Simulation of the problem statement. I start by creating the grid, looping through each new fibonacci number to increase the square size. I store the index in each cell, so that it's easy to find where the queens will go in the next step.

Then, I find every cell that should have a queen in it, and mark each threatened square with a zero. I skip the cells where the queens are so that I don't have to worry about backtracking.

At the end, I count up the cells that are cleared, and the cells with queens, and then divide it by the total number of spaces. Multiply by 100 to get the percent, and round to the nearest two decimal places.
> 2 votes

# Answer
# Python 2, ~~524~~ 499 bytes

```
def Q(n,x):
 global w,h,f;f,R,L=0,range,len
 for d in R(n):s=x-1==d;f=f or[[s]];w=L(f[0]);W,H=R(w),R(L(f));exec"for j in "+("W:f.append([s]*w)","f:\n\tfor k in H:j.append(s)","W:f.insert(0,[s]*w)","f:\n\tfor k in H:j.insert(0,s)","f:0")[d%4-(d==0)]
 w,h=L(f[0]),L(f);l=0,1,-1
 for Y in R(h):
	for X in R(w):exec("""def F(u,v,x,y):
 while(u==v==0)==0<=x<w!=0<=y<h:f[y][x]=1+(f[y][x]!=1);x+=u;y+=v
for s in l:
 for t in l:F(s,t,X,Y)""","")[f[Y][X]!=1]
 q=w*h;return(q-sum(j.count(0)for j in f))*100./q

```

Try it online!

Defining a function that takes in both the tiling size `n` and the queen's fibonacci square number `x`. The ouput percentage is porperly rounded to two decimal places (in the footer, where all output is taking place).

`f` is a two-dimensional array containing the board information being initiated to `0`. Then, the fibonacci chess board is calculated and populated with queens where queens shall be. Those queens are then moved to every place they can be moved; all positions are counted and printed as a percentage of the entire board.
> 2 votes

# Answer
# Mathematica 11.1, 336 bytes, 1-based

```
R=Rectangle[#,+##]&;f=Fibonacci;o=Join@@Outer[##,1]&;r=RegionUnion;s=RegionMeasure;p[1]={0,0};p[i_]:=p[i-1]+{{-f@i,-f[i-2]},{0,-f@i},{f[i-1],0},{f[i-1]-f@i,f[i-1]}}[[i~Mod~4+1]];t[i_]:=r[R[p@#,f@#]&/@Range@i];k[n_,x_]:=Round[100s@RegionIntersection[r[R[#,f@x]&/@((#+p@x)&/@o[1##&,o[List,{-1,0,1},{-1,0,1}],Range[2f@n]])],t@i]/s@t@i,.01]

```

Usage: `k[n, x]`. Pay attention that the function is 1-based. Rounding is achieved by `Round[100x,0.01]`

Basically, `p[i]` is a function of determining position of each square. And area is calculated by upper-level functions like `RegionIntersection`, `RegionUnion`, `RegionMeasure`
> 1 votes

---
Tags: code-golf, chess, fibonacci
---


title: Decompress an integer, Jelly style

text:
# Question
Title: Decompress an integer, Jelly style
Jelly has compressed string literals, using the `“...»` delimiters. The way these work is by interpreting the `...` as a base-250 integer, \\$n\\$, then repeatedly divmod-ing this integer until it reaches \\$0 \newcommand{\d}\[2\]{ \left( \left\lfloor \frac {#1} {#2} \right\rfloor, #1 \text{ mod } #2 \right) }\\$, building up the decompressed version as it goes by indexing into dictionaries and printable ASCII.

Jelly has 2 dictionaries, "short" and "long". "Short" contains \\$20453\\$ words of 5 letters or shorter. "Long" contains \\$227845\\$ words with 6 or more letters.

As the exact method is rather complicated, I'll work through how \\$n\\$ is decompressed:

* First, we divmod \\$n\\$ by \\$3\\$: \\$n, m = \d n 3\\$. We then call \\$m\\$ the *mode*.
* If the mode is \\$0\\$:
    + Divmod \\$n\\$ by \\$96\\$, yielding \\$n, c = \d n {96}\\$
    + Add the \\$c\\$th character in the printable ASCII range ( to `~`) to the decompressed string. If \\$c\\$ is \\$95\\$ yield a newline instead of **0x7F**
* If the mode is \\$1\\$:
    + If \\$n\\$ is even, use the "long" dictionary and replace \\$n\\$ with \\$\frac n 2\\$
    + If \\$n\\$ is odd, use the "short" dictionary and replace \\$n\\$ with \\$\frac {n-1} 2\\$
    + Then, take the length \\$l\\$ of the dictionary (\\$20453\\$ for "short", \\$227845\\$ for "long"), calculate \\$n, i = \d n l\\$ and retrieve the \\$i\\$th element of the dictionary, the *word*
    + If the decompressed string is not empty, prepend a space to the word. Finally, append the word to the decompressed string
* If the mode is \\$2\\$:
    + Calculate a *flag* \\$f\\$ as \\$n, f = \d n 3\\$ and update \\$n\\$
    + If \\$n\\$ is even, use the "long" dictionary and replace \\$n\\$ with \\$\frac n 2\\$
    + If \\$n\\$ is odd, use the "short" dictionary and replace \\$n\\$ with \\$\frac {n-1} 2\\$
    + Then, take the length \\$l\\$ of the dictionary (\\$20453\\$ for "short", \\$227845\\$ for "long"), calculate \\$n, i = \d n l\\$ and retrieve the \\$i\\$th element of the dictionary, the *word*
    + If the flag doesn't equal \\$1\\$, swap the case of the first character of the word
    + If the flag doesn't equal \\$0\\$ and the decompressed string is not empty *or* the flag equals \\$0\\$ and the decompressed string is empty, prepend a space to the word
    + Finally, append the word to the decompressed string
* If \\$n\\$ is non-zero, go to the first step with the new value of \\$n\\$

---

We can work through an example, using \\$n = 46886323035539\\$:

* First, we divmod by \\$3\\$: \\$n = 15628774345179, m = 2\\$.

As the mode is \\$2\\$, we calculate \\$n\\$ and \\$f\\$ as \\$n = 5209591448393, f = 0\\$. \\$n\\$ is odd, so we're using the "short" dictionary and \\$n\\$ becomes \\$2604795724196\\$.

Calculate the index and the updated value of \\$n = \left\lfloor \frac {2604795724196} {20453} \right\rfloor = 127355191\\$ and \\$i = 2673\\$. The \\$2673\\$th word in the "short" dictionary is `Caird`, so we call that our word.

As \\$f \ne 1\\$, we swap the case of the first character of the word: `caird`. However, \\$f = 0\\$ and the decompressed string is empty, so we don't prepend a space. Finally, we append `caird` to the (empty) decompressed string, yielding `d = 'caird'`

As \\$n = 127355191\\$, which is non-zero, we go to the first step again
* Now, `d = 'caird'` and \\$n = 127355191\\$. Divmod by \\$3\\$ to get \\$n = 42451730, m = 1\\$.

As the mode is \\$1\\$ and \\$n\\$ is even, we're going to use the "long" dictionary this time around and \\$n\\$ becomes \\$21225865\\$

We calculate the index into the dictionary as \\$n = \left\lfloor \frac {21225865} {227845} \right\rfloor = 93\\$ and \\$i = 36280\\$. The \\$36280\\$th element of the "long" dictionary is `coinhering`, so we set that as our word.

As `d` is non-empty, we prepend a space to our word, then append it to `d`: `d = 'caird coinhering'`

As \\$n = 93\\$, which is non-zero, we go to the first step again
* Now, `d = 'caird coinhering'` and \\$n = 93\\$. Divmod by \\$3\\$ to get \\$n = 31, m = 0\\$

As the mode is \\$0\\$, we calculate \\$n\\$ and \\$c\\$ as \\$n = 0, c = 31\\$. The \\$31\\$st ASCII character (alternatively, the character with ordinal \\$63\\$) is `?`

We add `?` to the end of `d`, resulting in `d = 'caird coinhering?'` and \\$n = 0\\$

As \\$n = 0\\$, we are done, and we return `caird coinhering?` as our decompressed string

---

Alternatively, here is a version of the `sss` function adjusted slightly.

## Task

You are to take a positive integer \\$n\\$ as input and output the decompressed string that \\$n\\$ maps to. You may also take the two dictionaries ("short" and "long") as input if you wish. The dictionaries can be found on TIO or in the Jelly repo

You will never be given an input \\$n\\$ outside the native bounds of integers in your language, but your program must *theoretically* work for arbitrarily large integers

This is , so the shortest code in bytes wins

## Test cases

```
n			out
1			Aachen
2			aachen
3			!
47			Aah
218			aaronical
250			Abdul
745			abdominoplasties
7180			auto
8106			. aahs
364038195		Q unconfine
396478210		SoddyAberration
592528345		insulting abature
4060289999		Shool< aalborg
6079656777		CcircuityAachen
2402785962		njX abac
1192732966		flongAllel
69526673848		Kansu4Abderian
7240502929952		Eyehook% arval
7300618740196341	g noninterchangeableu mahwa
98944394632073037	/;streetwards Harz aachen
8092569718755799474	epos sporran@ Apriorism
11508828911594644653	/,e Waterbirdanelasticities
11209288138354511564	 eale Thuya&decokes		 	(note the leading space)
11683582443091721078	 Saveable! duly babbliest		(note the leading space)
13365392696538596641	tambourinists}Battu0abaca

```

Additionally, make sure your program works for \\$n = 8609941742042387534416\\$:

```
this
has
newlines

```

and also for \\$n = 16505187\\$:

```
a
b

```

And the outputs for \\$1 \le n \le 100\\$ (one per line): Try it online!

# Answer
> 12 votes
# JavaScript (Node.js),  ~~173 170~~  163 bytes

Expects `([ long_dic, short_dic ])(n)`, where the dictionaries are arrays of words and **n** is a BigInt.

```
d=>F=(n,C)=>n?(B=Buffer,(g=k=>x=+[n%(n/=k=BigInt(k),k)])(3)?(q=x^2||g(3),b=B(d[g(2)][g(d[x].length)]),b[-q%2]^=32,q%3>0^C?' '+b:b):B([g(96)^95?x+32:10]))+F(n,1):''

```

Try it online!

### Commented

```
d =>                        // outer function taking d[] = dictionaries
F = (n, C) =>               // inner function taking n and a flag C
n ?                         // if n is not equal to 0:
  ( B = Buffer,             //   B = alias for Buffer
    ( g = k =>              //   g is a helper function taking a divisor k
      x = +[                //     it computes and returns x = n modulo k
        n % (               //     and updates n to floor(n / k) afterwards
          n /=              //
            k = BigInt(k),  //     k is first converted to a BigInt
          k                 //     but x is converted back to a Number
        )                   //
      ]                     //
    )(3) ?                  //   extract the mode; if it's not 0:
      ( q =                 //     q = flag; we force q = 3 in mode 1
          x ^ 2 || g(3),    //     otherwise, it's extracted from n
        b = B(              //     b is a Buffer:
          d[g(2)]           //       select the relevant dictionary
          [g(d[x].length)]  //       and extract the relevant word from it
        ),                  //     end of Buffer
        b[-q % 2] ^= 32,    //     if q is even, toggle the case of the 1st char.
        q % 3 > 0 ^ C ?     //     if (q mod 3 != 0) XOR C is true:
          ' ' + b           //       append a space and the word
        :                   //     else:
          b                 //       just append the word
      )                     //
    :                       //   else (mode 0):
      B([                   //     use a Buffer to generate a character:
        g(96) ^ 95 ? x + 32 //       extract the character ID and add 32
                   : 10     //       or force a line-feed if it's 95
      ])                    //     end of Buffer
  )                         //
  + F(n, 1)                 //   append the result of a recursive call
:                           // else (n = 0):
  ''                        //   stop the recursion

```

# Answer
> 5 votes
# Jelly, 11 bytes

Obligatory Jelly answer.

```
ḃØ⁵ịØJ⁾“»jV

```

**Try it online!**

### How?

```
ḃØ⁵ịØJ⁾“»jV - Link: integer, n
ḃ           - convert (n) to bijective base:
 Ø⁵         -   250
   ị        - index into:
    ØJ      -   Jelly's code-page
      ⁾“»   - list of characters = "“»"
         j  - join -> "“...»"
          V - evaluate as Jelly code

```

# Answer
> 3 votes
# Python 3, 245 bytes

```
def f(n,s,l,i=0):
	t=""
	while n:
		if n%3:
			if n%3>1:f=n//3%3;n//=9
			else:f=-1;n//=3
			d=[l,s][n%2];w=d[n//2%len(d)];t+=((t!="")^(f>0))*" "+[w[0].swapcase(),w[0]][f%2]+w[1:];n//=2*len(d)
		else:t+=chr((n//3%96+22)%117+10);n//=288
	return t

```

Try it online!

Pretty poorly optimized; working on a better approach.

---
Tags: code-golf, integer, compression, jelly
---


title: Find the Matrix Power

text:
# Question
Title: Find the Matrix Power
# Problem

Create a program or function that can calculate the result of a matrix raised to the *n*th power. Your code will take an arbitrary square matrix *A* and a non-negative integer *n*, and return a matrix with the value *A**n*.

## Restrictions

Built-in functions that compute the matrix power and matrix product are not allowed.

The rest of the standard rules for code-golf apply.

# Explanation

Given a square matrix *A*, the value of *A**n* = *A A ⋯ A* (repeated matrix product of *A* with itself, *n* times). If *n* is positive, the standard just mentioned is used. When *n* is zero, the identity matrix with the same order of *A* is the result.

# Goal

This is code-golf and the shortest code wins.

# Test Cases

Here, *A* is the input matrix, *n* is the input integer, and *r* is the output matrix where *r* = *A**n*.

```
n = 0
A = 62 72
    10 34
r =  1  0
     0  1

n = 1
A = 23 61 47
    81 11 60
    42  9  0
r = 23 61 47
    81 11 60
    42  9  0

n = 2
A =  12  28 -26  3
     -3 -10 -13  0
     25  41   3 -4
    -20 -14  -4 29
r = -650 -1052  -766 227
    -331  -517   169  43
     332   469 -1158 -53
    -878  -990   574 797

n = 4
A = -42 -19  18 -38
    -33  26 -13  31
    -43  25 -48  28
     34 -26  19 -48
r = -14606833  3168904 -6745178  4491946
      1559282  3713073 -4130758  7251116
      8097114  5970846 -5242241 12543582
     -5844034 -4491274  4274336 -9196467

n = 5
A =  7  0 -3  8 -5  6 -6
     6  7  1  2  6 -3  2
     7  8  0  0 -8  5  2
     3  0  1  2  4 -3  4
     2  4 -1 -7 -4 -1 -8
    -3  8 -9 -2  7 -4 -8
    -4 -5 -1  0  5  5 -1
r =  39557  24398 -75256 131769  50575   14153  -7324
    182127  19109   3586 115176 -23305    9493 -44754
    146840  31906 -23476 190418 -38946   65494  26468
     42010 -21876  41060 -13950 -55148   19290   -406
     44130  34244 -35944  34272  22917  -39987 -54864
      1111  40810 -92324  35831 215711 -117849 -75038
    -70219   8803 -61496   6116  45247   50166   2109

```

# Answer
# Jelly, ~~17~~ ~~16~~ 15 bytes

```
Z×'³S€€
LṬ€z0Ç¡

```

Try it online!

Permalinks with grid output: test case 1 | test case 2 | test case 3 | test case 4 | test case 5

### How it works

```
LṬ€z0Ç¡  Main link. Arguments: A (matrix), n (power)

L        Get the length l of A.
 Ṭ€      Turn each k in [1, ..., l] into a Boolean list [0, 0, ..., 1] of length k.
   z0    Zip; transpose the resulting 2D list, padding with 0 for rectangularity.
         This constructs the identity matrix of dimensions k×k.
     Ç¡  Execute the helper link n times.

Z×'³S€€  Helper link. Argument: B (matrix)

Z        Zip; transpose rows and columns of B.
   ³     Yield A.
 ×'      Spawned multiplication; element-wise mutiply each rows of zipped B (i.e.,
         each column of B) with each row of A.
         This is "backwards", but multiplication of powers of A is commutative.
    S€€  Compute the sum of each product of rows.

```
> 5 votes

# Answer
# MATL, 20 bytes

```
XJZyXyi:"!J2$1!*s1$e

```

**Try it online!**

### Explanation

This avoids the matrix multiplication by doing it manually, using element-wise multiplication with broadcast followed by vectorized sum. Specifically, to multiply matrices `M` and `N`, both of size *s*×*s*:

1. Transpose `M`. Call the resulting matrix `P`.
2. Permute the dimensions of `N` such that `N` is "turned" with a rotation axis along the first dimension, giving an *s*×1×*s* 3D array, say `Q`.
3. Multiply each element of `P` times each element of `Q`, with implicit broadcast. This means that `P` is automatically replicated *s* times along the third dimension, and `Q` is replicated *s* times along the second, to make them both *s*×*s*×*s*, before the actual element-wise multiplication takes place.
4. Sum along the first dimension to yield a 1×*s*×*s* array.
5. Squeeze the leading singleton dimension out, to produce an *s*×*s* result.

Commented code:

```
XJ      % take matrix A. Copy to clipboard J
ZyXy    % generate identity matrix of the same size
i:      % take exponent n. Generate range [1 2 ... n] (possibly empty)
"       % for each element in that range
  !     %   transpose matrix with product accumulated up to now (this is step 1)
  J     %   paste A
  2$1!  %   permute dimensions: rotation along first-dimension axis (step 2)
  *     %   element-wise multiplication with broadcast (step 3)
  s     %   sum along first dimension (step 4)
  1$e   %   squeeze out singleton dimension, i.e. first dimension (step 5)
        % end for. Display

```
> 5 votes

# Answer
## APL, 32 31 chars

```
{⍺=0:(⍴⍵)⍴1⍨1+≢⍵⋄+.×⍨⍣(⍺-1)⊣⍵}

```

Left argument the power to raise to, right argument the matrix. The hardest (most space consuming) bit is building the identity matrix for the case where the desired exponent is 0. The actual computation is based on the fact that the generalised inner product (`.`) with `+` and `×` as operands is effectively the matrix product. This combined with the power  operator ("repeat") forms the meat of the solution.
> 4 votes

# Answer
# K (ngn/k), 14 bytes

```
{y(+/x*)'/=#x}

```

Try it online!

-2 bytes thanks to @coltim on the k tree. The inner train multiplies x on the right side of the current matrix (instead of left side).

Why `(+/x*)'` is also a matmul:

```
(+/(e f;g h)*)' (a b;c d)
( (+/(e f;g h)*) a b; (+/(e f;g h)*) c d )
( +/ (ae af;bg bh) ; +/ (ce cf;dg dh) )
((ae+bg) (af+bh); (ce+dg) (cf+dh))

```

# K (ngn/k), 16 bytes

```
{y(+/'x*\:)/=#x}

```

Try it online!

Original solution. Takes `[matrix; n]` and computes `matrix^n`.

### How it works

```
{y(+/'x*\:)/=#x}  x:matrix; y:n
            =#x   Identity matrix of size of x
 y(       )/      Repeat y times:
      x*\:        Multiply each row of x to each column of current matrix
   +/'            Sum each to get the matrix product

```

Why `+/'*\:` is a matmul:

```
(a b;c d) *\: (e f;g h)
multiply-eachleft expands to
(a b * (e f;g h) ; c d * (e f;g h))
atomic application gives
((ae af
  bg bh)
 (ce cf
  dg dh))
so applying +/' on this will give the result of matmul.

```
> 4 votes

# Answer
## Sage, 112 bytes

```
lambda A,n:reduce(lambda A,B:[[sum(map(mul,zip(a,b)))for b in zip(*B)]for a in A],[A]*n,identity_matrix(len(A)))

```

Try it online

Explanation:

The inner lambda (`lambda A,B:[[sum(map(mul,zip(a,b)))for b in zip(*B)]for a in A]`) is a straightforward implementation of matrix multiplication. The outer lambda (`lambda A,n:reduce(...,[A]*n,identity_matrix(len(A)))`) uses `reduce` to compute the matrix power by iterated matrix multiplication (using the aforementioned homemade matrix multiplication function), with the identity matrix as the initial value to support `n=0`.
> 2 votes

# Answer
# Julia, ~~90~~ ~~86~~ 68 bytes

```
f(A,n)=n<1?eye(A):[A[i,:][:]⋅f(A,n-1)[:,j]for i=m=1:size(A,1),j=m]

```

This is a recursive function that accepts a matrix (`Array{Int,2}`) and an integer and returns a matrix.

Ungolfed:

```
function f(A, n)
    if n < 1
        # Identity matrix with the same type and dimensions as the input
        eye(A)
    else
        # Compute the dot product of the ith row of A and the jth column
        # of f called on A with n decremented
        [dot(A[i,:][:], f(A, n-1)[:,j]) for i = (m = 1:size(A,1)), j = m]
    end
end

```

Try it online! (includes all but the last test case, which is too slow for the site)

Saved 18 bytes thanks to Dennis!
> 2 votes

# Answer
# Python 2.7, ~~158~~ 145 bytes

The worst answer here, but my best golf in Python yet. At least it was fun learning how to do matrix multiplication.

Golfed:

```
def q(m,p):
 r=range(len(m))
 if p<1:return[[x==y for x in r]for y in r]
 o=q(m,p-1)
 return[[sum([m[c][y]*o[x][c]for c in r])for y in r]for x in r]

```

Explanation:

```
#accepts 2 arguments, matrix, and power to raise to
def power(matrix,exponent):
 #get the range object beforehand
 length=range(len(matrix))
 #if we are at 0, return the identity
 if exponent<1:
  #the Boolean statement works because Python supports multiplying ints by bools
  return [[x==y for x in length] for y in length]
 #otherwise, recur
 lower=power(matrix,exponent-1)
 #and return the product
 return [[sum([matrix[c][y]*lower[x][c] for c in length]) for y in length] for x in length]

```
> 2 votes

# Answer
## Julia, 27 24

```
a$n=round.(exp(log(a)n))

```

I am not sure what is allowed, but...

```
julia> a
5×5 Matrix{Int64}:
 35  18  40  37  77
 31   5  45  23  73
 62  67  29  85  97
 20   9  83  70  65
  2  13  53  59  52

julia> round.(exp(log(a)5)) ≈ a^5
true

```

24 thanks to @MarcMush.
> 2 votes

# Answer
# Jelly, 11 bytes

```
L=þ`Zḋþ³ƊƓ¡

```

Try it online!

A more modern update to Dennis' answer, be sure to give that an upvote.

Additionally, this is a 9 byte answer that takes the dimensions of the matrix as the first 2 command line args and the matrix as the third.

Both take the power via STDIN.

## How it works

```
L=þ`Zḋþ³ƊƓ¡ - Main link. Takes A on the left
L           - Length of A, L
   `        - Using L as both arguments:
  þ         -   Create an LxL matrix, where the element at (i,j) is:
 =          -     Does i = j?
               This creates an identity matrix LxL
         Ɠ  - Read an integer from STDIN, n
        Ɗ ¡ - Do the following n times:
    Z       -   Transpose
       ³    -   Yield A
      þ     -   Pair all rows of the transposed matrix with the rows of A and, over each row:
     ḋ      -     Dot product

```
> 2 votes

# Answer
## JavaScript (ES6), 123 bytes

```
(n,a)=>[...Array(n)].map(_=>r=m(i=>m(j=>m(k=>s+=a[i][k]*r[k][j],s=0)&&s)),m=g=>a.map((_,n)=>g(n)),r=m(i=>m(j=>+!(i^j))))&&r

```

I had a 132 byte version using `reduce` but I was just mapping over `a` so often that it turned out to be 9 bytes shorter to write a helper function to do it for me. Works by creating the identity matrix and multiplying it by `a` longhand `n` times. There are a number of expressions that return `0` or `1` for `i == j` but they all seem to be 7 bytes long.
> 1 votes

# Answer
# Python 3, 147 bytes

```
def f(a,n):
 r=range(len(a));r=[[i==j for j in r]for i in r]
 for i in range(n):r=[[sum(map(int.__mul__,x,y))for y in zip(*a)]for x in r]
 return r

```

Try it online!
> 1 votes

# Answer
# R, 49 bytes

```
f=function(m,n)`if`(n,m%*%f(m,n-1),diag(nrow(m)))

```

Recursive function that takes a `m`atrix and the power `n` to raise it to. Recursively calls `%*%`, which computes the dot-product. The initial value for the recursion is the identity matrix of the same size as `m`. Since `m %*% m = m %*% m %*% I`, this works just fine.
> 1 votes

# Answer
# Python 3, 128 bytes

```
def f(A,n):r=range(len(A));return n and[[sum(A[i][j]*x[i]for i in r)for j in r]for x in f(A,n-1)]or[[i==j for i in r]for j in r]

```

Try it online!
> 1 votes

# Answer
# Python 2, 131 bytes

```
f=lambda M,n:n and[[sum(map(int.__mul__,r,c))for c in zip(*f(M,n-1))]for r in M]or[[0]*i+[1]+[0]*(len(M)+~i)for i in range(len(M))]

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 11 bytes

```
²āDδQ¹Føδ*O

```

Try it online! Footer formats output as a grid.

`²āDδQ` pushes the identity matrix to the stack:
`²ā` range from 1 to the length of the second input
`DδQ` equality table with itself

`¹F` iterate first input times:
`øδ*O` multiply current matrix with input matrix:
`ø` transpose current matrix
`δ*` 3d multiplication table with input and transposed matrix
`O` sum along last axis
> 0 votes

---
Tags: code-golf, math, matrix, linear-algebra
---