title: This isn't rocket science

text:
# Question
Title: This isn't rocket science
Write a program or function that takes in a single-line string. You can assume it only contains printable ASCII. Print or return a string of an ASCII art rocket such as

```
  |
 /_\
 |E|
 |a|
 |r|
 |t|
 |h|
 |_|
/___\
 VvV

```

with the input string written from top to bottom on the fuselage. In this case the input was `Earth`. The height of the rocket (including flames) is always the length of the string plus five.

Each line in the output may have up to two trailing spaces and there may be a single optional trailing newline. **The shortest code in bytes wins.**

## More Examples:

```
[empty string]

  |
 /_\
 |_|
/___\
 VvV

a

  |
 /_\
 |a|
 |_|
/___\
 VvV

|0

  |
 /_\
 |||
 |0|
 |_|
/___\
 VvV

\/\

  |
 /_\
 |\|
 |/|
 |\|
 |_|
/___\
 VvV

 _ _ [note trailing space]

  |
 /_\
 | |
 |_|
 | |
 |_|
 | |
 |_|
/___\
 VvV

    [4 spaces]

  |
 /_\
 | |
 | |
 | |
 | |
 |_|
/___\
 VvV

SPACEY

  |
 /_\
 |S|
 |P|
 |A|
 |C|
 |E|
 |Y|
 |_|
/___\
 VvV

```

# Leaderboard

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

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

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

# Answer
> 53 votes
# Excel VBA, ~~142~~ ~~179~~ ~~175~~ ~~160~~ 155 bytes

**Instruction:**

Set the worksheet of Excel where cell A1 is input and column C as the output. ~~Set the text alignment in column C to center~~. Write and run the following code in the Immediate Window:

```
[C1]="|":[C2]="/_\":T=[A1]&"_":For i=1To Len(T):Cells(i+2,3)="|"&Mid(T,i,1)&"|":Next:Cells(i+2,3)="/__\":Cells(i+3,3)="VvV":[C:C].HorizontalAlignment=-4108

```

**Ungolfed the code:**

```
Sub R()
    [C1] = "|"
    [C2] = "/_\"
    T = [A1]&"_"

    For i = 1 To Len(T)
        Cells(i + 2, 3) = "|" & Mid(T, i, 1) & "|"
    Next

    Cells(i + 2, 3) = "/__\"
    Cells(i + 3, 3) = "VvV"
    [C:C].HorizontalAlignment = -4108   'Set the text alignment in column C to center
End Sub

```

**Output:**

**Note:** The font and the color are just a personal choice.

---

*15 bytes saved due to edc65's suggestion. Thanks.*

*5 bytes saved due to Taylor Raine's suggestion. Thanks.*

# Answer
> 32 votes
## Perl 6, 75 bytes

```
"  |\n /_\\".say;" |$_|".say for slurp.chomp.comb;" |_|\n/___\\\n VvV".say;

```

# Answer
> 25 votes
# JavaScript (ES6), 54

Straightforward

```
x=>`  |
 /_\\
 |${[...x+'_'].join`|
 |`}|
/___\\
 VvV`

```

**Test**

```
f=x=>`  |
 /_\\
 |${[...x+'_'].join`|
 |`}|
/___\\
 VvV`

function update() {
  O.textContent=f(I.value)
}

update()
```

```
<input id=I value='hello' oninput='update()'><pre id=O></pre>
```

# Answer
> 17 votes
## Actually, 40 bytes

```
"/___\
 VvV",'_o"|
 |"j'|o" |"+"  |
 /_\

```

Yes, those newlines are supposed to be there.

Try it online!

Explanation:

Newlines are represented by `\n` for easier formatting

```
"/___\\n VvV",'_o"|\n |"j'|o" |"+"  |\n /_\
"/___\\n VvV"                                create the bottom of the rocket
             ,'_o                            get input, append a "_" (for the last section before the jets)
                 "|\n |"j                    insert "|\n |" between every pair of characters
                         '|o                 append "|"
                            " |"+            prepend " |"
                                 "  |\n /_\  create the nose cone

```

# Answer
> 16 votes
# C, ~~83~~, 82 bytes

```
F(char*c){for(puts("  |\n /_\\");*c;printf(" |%c|\n",*c++));puts(" |_|\n/___\\\n VvV");}

```

Test main:

```
int main() {
  F("");
  F("a");
  F("|0");
  F("\\/\\");
  F(" _ _ ");
  F("    ");
  F("SPACEY");
}

```

# Answer
> 11 votes
# Python 2, ~~93~~ ~~66~~ ~~62~~ 61 bytes

A FGITW. Can probably be heavily golfed. Suggestions welcome.

**Edit:** 27 bytes thanks to Mego. 4 bytes thanks to TheBikingViking. 1 byte thanks to user3030010.

Try It Online!

```
lambda x:r"""  |
 /_\
 |%s|
/___\
 VvV"""%"|\n |".join(x+"_")

```

# Answer
> 10 votes
# PHP, ~~73~~ ~~72~~ ~~69~~ 62 bytes

```
  |
 /_\
 |<?=join('|
 |',str_split($argv[1]._))?>|
/___\
 VvV

```

Takes the string to print on the fuselage as the first argument from the command line when the script is called.

Improvements:

1. Saved a byte by replacing \n with a real LF newline in the first argument of `join`.
2. Saved three more bytes by appending the rocket base with a single underscore to the input
3. Thanks to Ismael Miguel: Saved 7 more bytes by taking advantage of the fact that PHP used to be the "Hypertext preprocessor" so you can output as much text as you want and start the code somewhere in the middle.

Try it online!

This was fun! :-)

Sample calls:

```
php rocket.php ""
php rocket.php EARTH
php rocket.php "This is a very long rocket"

```

# Answer
> 9 votes
## Haskell, 58 bytes

```
f s="  |\n /_\\\n |"++((:"|\n |")=<<s)++"_|\n/___\\\n VvV"

```

# Answer
> 9 votes
# Ruby, ~~57~~ 55 bytes

-2 bytes by @ValueInk
-5 bytes by assuming that there is no newline in the input, as suggested by @manatwork. Newline-less input can be provided for example with `echo -n`, like `echo -n hey | ruby rocket.rb`.

```
puts'  |
 /_\
 |'+gets.chars*'|
 |'+'|
 |_|
/___\
 VvV'

```
Old version, assumes newline in input:

# Ruby, ~~62~~ 60 bytes

```
puts'  |
 /_\
 |'+gets.chop.chars*'|
 |'+'|
 |_|
/___\
 VvV'

```

# Answer
> 9 votes
# brainfuck, 179 bytes

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

```

Try it online!

# Answer
> 7 votes
# Retina, ~~44~~ 37 bytes

**7 bytes thanks to Martin Ender.**

```
$
_
.
¶ |$0|
$
¶/___\¶ VvV
^
  |¶ /_\

```

Try it online!

# Answer
> 7 votes
# Jelly, ~~37~~ 36 bytes

```
;”_⁾ |;Ð€ŒB;“/___\“ VvV”“  |“ /_\”;Y

```

~~Same score as existing entry, but~~ uses a fun new feature - `ŒB`, the vectorised version of `ŒḄ`, known as bounce. Bouncing is running through a list to its end and then back `x[:-1]+x[::-1]` e.g.: `bounce("codegolf") == "codegolflogedoc"`.

-1 byte thanks to Dennis (use the vectorised version of bounce)

How?

```
;”_⁾ |;Ð€ŒB;“/___\“ VvV”“  |“ /_\”;Y - argument: a string, S
                        “  |“ /_\”   - the top of the rocket ["  |", " /_\"]
;”_                                  - concatenate to make S=S+"_"
   ⁾ |;                              - concatenate to make c=" |"+c
       Ð€                            - map over right argument i.e. for c in S
         ŒB                          - bounce! With vectorisation c[:-1]+c[::-1]
                                       e.g. " |B" -> " |B| "
           ;                         - concatenate with
            “/___\“ VvV”             - the bottom of the rocket ["/___\", " VvV"]
                                  ;  - concatenate the top with everything else
                                   Y - join with line feeds

```

Test it on **TryItOnline**

# Answer
> 6 votes
# Pyke, ~~40~~ ~~37~~ 35 bytes

(Updated to work with latest version)

```
\_+2" ||
"m:"/___\
 VvV"+R"  |
 /_\

```

Try it here!

# Answer
> 5 votes
# , ~~41,~~ 39 bytes

```
ys$_òlé
òÎá|I |
Hr/$r\YO  |GpX2á_o VvV

```

Try it online!

Note that for some reason, the online interpreter was producing unexpected results, so I pushed a debug version to the online interpreter that runs a lot slower. It should produce the correct results now.

Since this program contains unprintable characters, here is a hexdump:

```
0000000: 7973 245f f26c e90a f2ce e17c 4920 7c0a  ys$_.l.....|I |.
0000010: 4872 2f24 725c 594f 2020 7c1b 4770 5832  Hr/$r\YO  |.GpX2
0000020: e15f 6f20 5676 56                        ._o VvV

```

# Answer
> 5 votes
## PowerShell v2+, ~~59~~ ~~55~~ 51 bytes

```
"  |
 /_\"
$args|% t*y|%{" |$_|"}
" |_|
/___\
 VvV"

```

Try it online!

Abuses the default `Write-Output` at end of execution to stick a newline between each element, since these are all just literal strings on the pipeline. The only "tricky" bit is a loop through each element of the input `$args` as a char-array to get the body of the rocket.

*Uses literal newlines as pointed out by ConnorLSW to save some bytes.*
*-4 more bytes thanks to Veskah.*

# Answer
> 5 votes
# R, 163 bytes

```
v=c();l="\n";for(i in 1:nchar(a<-scan(,"")))v=c(v,paste0(" |",strsplit(a,"")[[1]][i],"|",l,collapse=""));cat("  |",l," /_\\",l,v," |_|",l,"/___\\",l," VvV",sep="")

```

**Ungolfed :**

```
v=c()     #Empty vector
l="\n"    #Line break

for(i in 1:nchar(a<-scan(,"")))                  #For the number of character of the input
    v=c(v, paste0(" |",strsplit(a,"")[[1]][i],"|","\n",collapse=""))
    #This part cut the input into its letters, paste each letter between `|`'s,
    #and a line break

cat("  |",l," /_\\",l,v," |_|",l,"/___\\",l," VvV",sep="") #Puts everything in the STDOUT,
                                                           #with spaces where needed

```

I don't really like the fact I had to put some spaces in the last line, but hey !

# Answer
> 4 votes
## PHP, ~~108~~ ~~100~~ 88 bytes

-8 bytes thanks to business cat

-12 bytes thanks to YetiCGN

```
echo'  |
 /_\\
';foreach(str_split($argv[1])as$c){echo" |$c|
";}echo' |_|
/___\\
 VvV';

```

pretty straightforward

Ideone

# Answer
> 4 votes
## C#, ~~106~~ ~~97~~ ~~80~~ 74 bytes

```
s=>$@"  |
 /_\
 |{string.Join("|\n |",s.ToCharArray())}|
 |_|
/___\
 VvV";

```

I don't have C# 6 to try the above but I believe it will work

*Saved 7 bytes thanks to Kevin Cruijssen*

*Thanks to manatwork for pointing me in the right direction to save 17 bytes*

*Saved 6 bytes thanks to milk*

# Answer
> 4 votes
# C,  ~~131~~ , 121 bytes

```
#define P printf
main(){char s[99],*p=s;gets(s);P("  |\n /_\\\n");while(*p)P(" |%c|\n",*p++);P(" |_|\n/___\\\n VvV\n");}

```

# Answer
> 4 votes
# PowerShell, 70 bytes

```
"  |`n /_\`n$(([char[]]$a|%{" |$_|"})-join("`n"))`n |_|`n/___\`n VvV

```

Set $a to input.

If it has to take input other than a variable it can be piped in:

```
"Hello World"|%{"  |`n /_\`n$(([char[]]$_|%{" |$_|"})-join("`n"))`n |_|`n/___\`n VvV "}

```

Example:

```
  |
 /_\
 |H|
 |e|
 |l|
 |l|
 |o|
 | |
 |W|
 |o|
 |r|
 |l|
 |d|
 |_|
/___\
 VvV

```

# Answer
> 4 votes
# Mathematica, 50 bytes

```
"  |
 /_\\
 |"<>(#<>"|
 |"&/@#)<>"_|
/___\\
 VvV"&

```

Anonymous function. Takes a list of characters as input and returns a string as output.

# Answer
> 3 votes
# Java 10, ~~102~~ ~~99~~ 81 bytes

```
a->{var r="  |\n /_\\\n |";for(var c:a)r+=c+"|\n |";return r+"_|\n/___\\\n VvV";}

```

3 bytes saved thanks to *@Jules*.

Try it online.

**Explanation:**

```
a->{                      // Method with character-array parameter and String return-type
  var r="  |\n /_\\\n |"; //  Result-String, starting with the top part:
                          //   |
                          //  /_\
                          //  |
  for(var c:a)            //  Loop over each character in the input-array:
    r+=c                  //   Append the character to the result-String,
        +"|\n |";         //   with trailing:
                          //    |
                          //  |
  return r                //  Return the result-String,
   +"_|\n/___\\\n VvV";}  //  appended with bottom part:
                          //   _|
                          // /___\
                          //  VvV

```

# Answer
> 3 votes
# 05AB1E, ~~50~~ ~~47~~ ~~43~~ 37 bytes

```
I'_J"  |
 /_\"svy" |ÿ|"}"/___\
 VvV"»

```

Try it online!

Saved 9 bytes thanks to Adnan.

# Answer
> 3 votes
# Jelly, ~~38~~ 37 bytes

```
;”_“|“|¶”jÐ€“  |¶“/_\¶”;K;“/___\¶ VvV

```

Try it online!

Same idea as with my Pyth answer, but this can probably be golfed.

# Answer
> 3 votes
# Lua, 83, 92 bytes

`function f(x)return' |\n /_\\\n'..x:gsub('(.)',' |%1|\n')..' |_|\n/___\\\n VvV'end`

```
print('  |\n /_\\\n'..(arg[1] and arg[1]:gsub('(.)',' |%1|\n') or '')..' |_|\n/___\\\n VvV')

```

# Answer
> 3 votes
# Gema, 50 characters

```
\A=  |\n\ /_\\\n
?=\ |?|\n
\Z=\ |_|\n/___\\\n\ VvV

```

Sample run:

```
bash-4.3$ echo -n gema | gema '\A=  |\n\ /_\\\n;?=\ |?|\n;\Z=\ |_|\n/___\\\n\ VvV'
  |
 /_\
 |g|
 |e|
 |m|
 |a|
 |_|
/___\
 VvV

```

# Answer
> 3 votes
# BASH 84 70

Saved 14 thanks to manatwork

```
(cat&&echo _)|sed 's~.~ |&|\n~g;1s~^~  |\n /_\\\n~;$s~$~/___\\\n VvV~'

```

Over half of the bytes are for adding the nose, and engine.

# Answer
> 3 votes
# MATLAB, 94 bytes

```
@(s)char(['  |';' /_\';arrayfun(@(x)[' |' x '|'],s,'UniformOutput',0)';' |_|';'/___\';' VvV'])

```

Anonymous function

# Answer
> 3 votes
# GolfScript, ~~61~~ 51 bytes

My first code golf, I hope it is good enough.

```
"  |
 /_\\
"\1/.,{" |"\(\"|
"\}\*" |_|
/___\\
 VvV"

```

### Explanation

```
"  |\n /_\\\n"   # Push the rocket's head
\                # Swap the head with the user's string
1/               # The string is converted into an array
.,               # Push array length
{" |"\           # Push the rocket's body and swap
(\               # Array's first element cut out
"|\n"\           # Push rocket's body and swap
}\*              # Repeat for array length times
" |_|\n/___\\\n VvV" # Push rocket's bottom

```

Try it online!

# Answer
> 3 votes
# Vim, ~~41~~ 39 bytes

Here the `<End>` is literally the "End" key.

```
i <End>_:s/./ |&|\r/g
/___\
 VvVggxo /_\

```

Unprintables so:

```
i <End>_^O:s/./ |&|\r/g
/___\
 VvV^[ggxo /_\^[

```

# Answer
> 3 votes
# Charcoal, 22 bytes

```
↷¦|_θ__←v↖V→/↑_↑⊕Ｌθ/‖Ｂ

```

Try it online!

Needs trailing newline in input, due to how Charcoal input works.

# Answer
> 3 votes
# , 47 46 39 37 35 bytes

```
A_Ó./ |&|\r
a/___\
 VvVHO  |
 /_\

```

Try it online!

This is my first time trying to golf something. There is probably room for improvement since I don't know V, only vim.

Hexdump:

```
00000000: 415f 1bf3 2e2f 207c 267c 5c72 2f67 0a61  A_.../ |&|\r/g.a
00000010: 2f5f 5f5f 5c0a 2056 7656 1b48 4f20 207c  /___\. VvV.HO  |
00000020: 0a20 2f5f 5c                             . /_\

```

# Answer
> 3 votes
# Excel 2016+, 73 bytes

An anonymous worksheet function that takes input from cell `A1` and outputs to the calling cell

```
="  |
 /_\
 |"&Concat(Mid(A1,Sequence(Len(A1)),1)&"|
 |")&"_|
/___\
 VvV"

```

# Answer
> 3 votes
# Vyxal `C`, ~~30~~ 24 bytes

```
`|/__`:ḣṫ⁰p\|vp÷„Ḣ‛VvWøM

```

Try it Online!

*-5 bytes thanks to allxy*

## How?

```
`|/__`:ḣṫ⁰p\|vp÷„Ḣ‛VvWøM
`|/__`                     # Push string "|/__"
      :                    # Duplicate
       ḣ                   # Head extract, push a[0] and a[1:]
        ṫ                  # Tail extract, push a[:-1] and a[-1] (stack: a[0], a[1:-1], a[-1])
         ⁰p                # Prepend the input to this a[-1]
           \|vp            # For each character, prepend "|"
               ÷           # Dump, push all contents to the stack
                „          # Rotate stack left once
                 Ḣ         # Remove head
                  ‛Vv      # Push string "Vv"
                     W     # Wrap stack into a list
                      øM   # Flip brackets and palindromise each
                           # C flag centers and joins on newlines

```

# Answer
> 3 votes
# C, ~~128~~ ~~97~~ 94 bytes

```
#define P printf(
r(char*s){for(P"  |\n /_\\\n");*s;P" |%c|\n",*s++));P" |_|\n/___\\\n VvV");}

```

Un-golfed:

```
#define P printf(
/* Knock off a few bytes by abusing the preprocessor */

r(char*s) { /* Function r (for rocket) accepting a string */
    for( /* For loop */
        P "  |\n /_\\\n"); /* BEFORE entering loop, print the top part */
        *s; /* Loop until the null at the end of the string is encountered */
        P " |%c|\n",*s++) /* Print a middle section for each char */
    );
    P " |_|\n/___\\\n VvV"); /* Print the bottom part */
}

```

After realizing that I have completely forgotten about `puts()` due to its usual uselessness (I always use `printf()`), I finally got it under 90 bytes, only to realize that someone else had beaten me to it:

```
r(char*s){for(puts("  |\n /_\\");*s;printf(" |%c|\n",*s++));puts(" |_|\n/___\\\n VvV");}

```

# Answer
> 2 votes
# Pyth, 38 bytes

```
j++"  |
 /_\\"jR_B" |"+Q\_"/___\\
 VvV

```

Try it online. Test suite.

# Answer
> 2 votes
# Scala, 97 94 77 bytes

```
print("  |\n /_\\\n"+args(0).map{" |"+_+"|\n"}.mkString+" |_|\n/___\\\n VvV")

```

# Answer
> 2 votes
**Python 3, ~~78~~ 75 Bytes**

```
w="  |\n /_\\"
for i in input(): w+="\n |"+i+"|"
w+="\n |_| \n/___\\ \n VvV"
print(w)

```

Thanks @ValueInk for spotting that I could lose 3 bytes by clearing the `input` function of arguments.

# Answer
> 2 votes
# Kotlin, 68 bytes

```
{"""  |
 /_\${it.replace(Regex("."),"\n |\$0|")}
 |_|
/___\
 VvV"""}

```

Pretty straightforward. Uses multiline string and a regex replacement. This is a lambda with `(String)->String` type. Test:

```
fun main(args: Array<String>) {
    val function : (String)->String = {"""  |
 /_\${it.replace(Regex("."),"\n |\$0|")}
 |_|
/___\
 VvV"""}
    println(function(" _ _ "))
}

```

# Answer
> 2 votes
# S.I.L.O.S, ~~157 154~~ 143 bytes

```
pL   |
def p print : lbl L Line
pL  /_\
loadL :
a = 256
:a
x = get a
if x c
GOTO e
:c
p  |
pChar x
pL |
a + 1
if x a
:e
pL  |_|
pL /___\
p  VvV

```

It should be fairly readable. Feel free to try it online!

# Answer
> 2 votes
# R, 116 bytes

**Golfed**

```
write(c("  |"," /_\\",sapply(strsplit(scan(,""),"")[[1]],function(y)paste0(" |",y,"|"))," |_|","/___\\"," VvV"),1,1)

```

**Ungolfed**

```
write(                                             # Write to console
      x = c("  |"," /_\\",                         # Add in stock rocket part
        sapply(X = strsplit(scan(,""),"")[[1]],    # Take in rocket part specification, split string, loop over all specs
               FUN = function(y) {
                 paste0(" |",y,"|"))               # Custom build rocket body
                },
        " |_|","/___\\"," VvV"),                   # Add stock parts
      file = 1,                                    # Print to console
      ncolumns = 1)

  |
 /_\
 |s|
 |t|
 |r|
 |s|
 |p|
 |l|
 |i|
 |t|
 |!|
 |_|
/___\
 VvV

```

# Answer
> 2 votes
## GNU sed, ~~54~~ ~~49~~ 48 bytes

This was my first answer to a challenge on this site. The solution is simple, mainly printing, so I spent some time making sure that it can't be golfed anymore.

```
s:.:\n |&|:g
s::  |& /_\\&:
a\ |_|\n/___\\\n VvV

```

**Try it online!**

Fast forward half a year later, I rewrote the script, used a trick for good measure and golfed it down to 1 byte shorter. Now that's progress!

**Explanation:** the pattern space at each step is mentioned for clarity, given the input example "GO"

```
s:.:\n |&|:g
   # turn each input char into a section of the rocket (\n |G|\n |O|)
s::  |& /_\\&:
   # 's::' is a trick; the search part is actually the one from the previous 's'
   #command, i.e. a char. Only the first char, '\n', the modifier 'g' is not
   #inherited. The replace part is the head of the rocket. (  |\n /_\\n |G|\n |O|)
a\ |_|\n/___\\\n VvV
   # append the tail of the rocket, plus implicit printing at the end

  |
 /_\
 |G|
 |O|
 |_|
/___\
 VvV

```

# Answer
> 2 votes
# Lua, 69 68 bytes

```
print([[  |
 /_\
]]..(...):gsub('.',' |%0|\n')..[[ |_|
/___\
 VvV]])

```

Should work with Lua 5.1 - 5.3 (tested with 5.3).

I don't have enough rep to comment on nolan's answer, but this is quite similar.

I'm using `[[long string]]` syntax to save a few bytes by avoiding needing to escape newlines and backslashes.

`gsub` doesn't need to specify a capture because `%0` can be used. (Actually, `%1` still works without a capture as well, but this isn't strictly documented.)

I also trimmed away the input validation; not sure why it was there -- an empty string input (as opposed to empty input) will work fine. Handling a missing `arg[1]` can be done more briefly just by `(arg[1]or''):gsub(...)` anyway, although at this point it is briefer just to switch to `io.read()` and get the input from stdin. Anyway, `...` is a shorter way to get command-line input (even if parens are needed).

# Answer
> 2 votes
# Perl 6, 51 bytes

```
{"  |
 /_\\
 {("|$_|
"for |.comb,'_')}/___\\
 VvV"}

```

A lambda that takes a string as argument, and returns a string.

try it online

# Answer
> 2 votes
# R, 101 bytes

This is an improvement on Frédéric's answer. I eliminated the variable definition, the for-loop, and the need for the `sep=""` argument.

```
cat("  |\n /_\\\n",sapply(strsplit(scan(,""),""),function(x)paste0("|",x,"|\n")),"|_|\n/___\\\n VvV")

```

Ungolfed:

```
cat("  |\n /_\\\n",                      # Print top of rocket
    sapply(
      strsplit(scan(,""),""),            # Take stdin and convert to list of chars
      function(x)paste0("|",x,"|\n")),   # Print letters
    ,"|_|\n/___\\\n VvV")                # Print bottom and FLAMES

```

I'm sure that there is still some improvement possible.

# Answer
> 2 votes
# Dyalog APL, 50 bytes

```
↑'/___\' ' VvV',⍨'  |' ' /_\',↓' ','|',⍨'|',⍪⍞,'_'

```

OK, so it may not be the shortest submission, but it *is* the only one that carries the name of a real rocket manufacturer:

```
  |
 /_\
 |A|
 |P|
 |L|
 |_|
/___\
 VvV

```

TryAPL online!

# Answer
> 2 votes
## \>\<\>, 60 bytes

```
'  |'a' /_\'av
a$v?(0:i'|| '<
'r\~'_'$a'/___\'a' VvV
 o>l?!;

```

Pretty simple really. lots of strings, the newlines are annoying.

Try it online

```
  |
 /_\
 |>|
 |<|
 |>|
 |_|
/___\
 VvV

```

# Answer
> 2 votes
# Swift, 99 byte

```
let f:(String)->String={$0.characters.reduce("  |\n /_\\\n"){$0+" |\($1)|\n"}+" |_|\n/___\\\n VvV"}

```

Use like this:

```
print(f("Some String"))

```

Result:

```
  |
 /_\
 |S|
 |o|
 |m|
 |e|
 | |
 |S|
 |t|
 |r|
 |i|
 |n|
 |g|
 |_|
/___\
 VvV

```

# Answer
> 2 votes
## Perl, 51 bytes

**50 bytes code + 1 for `-p`.**

```
s/./$&|
 |/g;s~^~  |
 /_\\
 |~;s~$~_|
/___\\
 VvV~

```

### Usage

```
perl -pe 's/./$&|
 |/g;s~^~  |
 /_\\
 |~;s~$~_|
/___\\
 VvV~' <<< earth
  |
 /_\
 |e|
 |a|
 |r|
 |t|
 |h|
 |_|
/___\
 VvV

```

```
perl -pe 's/./$&|
 |/g;s~^~  |
 /_\\
 |~;s~$~_|
/___\\
 VvV~' <<< ''
  |
 /_\
 |_|
/___\
 VvV

```

```
perl -pe 's/./$&|
 |/g;s~^~  |
 /_\\
 |~;s~$~_|
/___\\
 VvV~' <<< '0|'
  |
 /_\
 |0|
 |||
 |_|
/___\
 VvV

```

# Answer
> 2 votes
# Dart, 80 bytes

```
g(s)=>'  |\n /_\\\n${s.split('').map((s)=>' |$s|\n').join()} |_|\n/___\\\n VvV';

```

Running it through

```
main()=>print(g("Jasper"));

```

Gives:

```
  |
 /_\
 |J|
 |a|
 |s|
 |p|
 |e|
 |r|
 |_|
/___\
 VvV

```

# Answer
> 2 votes
# CJam, 38 bytes

```
"  |
 /_\
 |"q'_+"|
 |"*"|
/___\
 VvV"

```

Try it online!

**Explanation**

Nothing fancy, pretty straightforward.

```
"  |\n /_\\n |"                              Push the top of the rocket
               q'_+                          Push the input and append an underscore
                   "|\n |"*                  Join the characters of the input with the sides
                           "|\n/___\\n VvV"  Push the bottom of the rocket

```

# Answer
> 2 votes
# Common Lisp, ~~85~~ 74 bytes

```
(lambda(s)(format t"  |
 /_\\
~{ |~a|
~} |_|
/___\\
 VvV"(coerce s'list)))

```

Try it online!(I added some bytes to call this anonymous function)

For changing part we take input as string.

```
~{ |~a|         ;we loop through all characters of string
    ~}          ;printing characters from list
(coerce s'list) ;string is converted into list of characters later used by above loop

```

# Answer
> 2 votes
# Keg, 52 characters

```
?(\|'\| \
)\\\_\/ \
\|  ^\
 \|\_\|\
\/\_\_\_\\\
 VvV

```

Only tricky point is that Keg has no strings, the input is pushed to stack character by character. So the processing order is: read input (`?`) and turn it into middle section, append top section reversed, reverse them all (`^`), append bottom section.

(Note that the interpreter (TIO implementation?) does not support absolutely no input. Empty input is specified as single newline, which will not be processed anyway.)

Try it online!

# Answer
> 2 votes
# C - 84 Bytes

```
f(char*s){puts("  |\n /_\\");while(*s)printf(" |%c|\n", *s++);puts(" |_|\n/___\\\n VvV");}

```

**Ungolfed**

```
f(char* s)
{
    puts("  |\n /_\\");

    while(*s)
        printf(" |%c|\n", *s++);

    puts(" |_|\n/___\\\n VvV");
}

```

**Explanation**

Function that receives a string prints it into the ascii-rocket. Tested on GCC, generates some warnings if not compiled with -std=c89.

# Answer
> 2 votes
# MathGolf, 36 bytes

```
ù  |ÿ /_\è'_▐û |\+mñn'/ÿ___\+ÿ VvV]n

```

Input as a list of characters.

Try it online.

**Explanation:**

```
ù  |          # Push string "  |"
ÿ /_\         # Push string " /_\"
è             # Push the inputs as string-array
 '_▐         '# Append a trailing "_"
    û |\+     # Prepend " |" in front of each string
         mñ   # Palindromize each string in the list
           n  # Join it with newline delimiter
'/           '# Push string "/"
  ÿ___\       # Append string "___\": "/___\"
ÿ VvV         # Push string " VvV"
]             # Wrap the entire stack into a list
 n            # Join it with newline delimiter
              # (after which the entire stack is output implicitly)

```

# Answer
> 2 votes
# K (ngn/k), ~~65~~ 60 bytes

```
`0:"  |\n /_\\";{`0:" |",x,"|"}'$1:0;`0:" |_|\n/___\\\n VvV"

```

Try it online!

-5 bytes thanks to Razetime!

First ever K answer! May not be perfect, but it's pretty good!

Explaination:

```
`0:"  |\n /_\\" / Print the top of the rocket
{`0:" |",x,"|"} / Print " |$x|"
'$1:0; / For each character in the user input
/ Note: ';' is important because without it
/ the console will also output `(:: :: ...)`
`0:" |_|\n/___\\\n VvV" / Print the end of the rocket

```

# Answer
> 1 votes
# Haskell, ~~67 63~~ 59 bytes

```
(++"_|\n/___\\\n VvV").("  |\n /_\\\n |"++).(>>=(:"|\n |"))

```

Thanks to Damien it's now essentially the same as xnor's answer, just in point-free notation. Ideone it!

# Answer
> 1 votes
## C#, ~~130~~ ~~111~~ 95 bytes

```
s=>{var a="  |\n /_\\\n";foreach(var c in s)a+=" |"+c+"|\n";a+=" |_|\n/___\\\n VvV";return a;};

```

*Saved 16 bytes thanks to Kevin Cruijssen*

# Answer
> 1 votes
## Batch, 128 bytes

```
@echo off
set s=%1_
echo   ^|
echo  /_\
:l
echo  ^|%s:~0,1%^|
set s=%s:~1%
if not "%s%"=="" goto l
echo /___\
echo  VvV

```

# Answer
> 1 votes
# Javascript (using external lib - Enumerable) (84 bytes)

```
n=>" |\n /_\\\n"+_.From(n).WriteLine(x=>" |"+x+"|")+(n?"\n":'')+" |_|\n/___\\\n VvV"

```

Link to lib: https://github.com/mvegh1/Enumerable

Code explanation: Pretty straight forward. Just boilerplates the rocketship template (top and bottom), and concats the fuselage string in the middle. Whats eating up a lot of bytes is the check if the input is truthy, because for an empty string it's wrong to add a newline to the beginning of the bottom template

I love how the native JS answer blows this away...

# Answer
> 1 votes
## Perl, ~~65~~ 60 bytes

```
say'  |
 /_\\';say" |$_|"for split'',<>;say' |_|
/___\
 VvV'

```

Needs -E to use say, input should be piped in in order to not have a trailing newline. Notice that there's a space at the beginning of the second and fourth lines. Takes advantage of being able to use literal new lines in Perl to save a byte over using \n in each of the cases

Thanks to @manatwork for saving 5 bytes!

# Answer
> 1 votes
## Neoscript, 76 bytes

```
{s|"  |
 /_\\
"+(s as Array):map({e|" |"+e+"|
"}):fuse()+" |_|
/___\\
 VvV"}

```

`{s|...}` declare a lambda and `as` is the casting operator.

# Answer
> 1 votes
**MUMPS: 94 bytes**

To get some more variety in here. I tried to solve this in C by declaring main as an array of integers that were compiled machine code but it was still too big, especially on a 64 bit machine.

```
r
 r x w !,"  |",!," /_\",! f i=1:1:$L(x) w " |",$E(x,i),"|",!
 w " |_|",!,"/___\",!," VvV" q

```

# Answer
> 1 votes
# MATL, ~~47~~ ~~42~~ 41 bytes

```
95h"' |'@yPhh]v'   /|_ \'2ew'/ _V_v_V\'2e

```

Try it online!

# Answer
> 1 votes
# Clojure (83 bytes)

```
#(str "  |\n /_\\\n |" (clojure.string/join "|\n |" (str % \_)) "|\n/___\\\n VvV")

```

And here's a rocket for you:

```
  |
 /_\
 |W|
 |e|
 |l|
 |c|
 |o|
 |m|
 |e|
 | |
 |t|
 |a|
 | |
 |E|
 |a|
 |r|
 |f|
 |_|
/___\
 VvV

```

# Answer
> 1 votes
# Javascript (ES5), 109 89 Bytes)

```
function(n){s=" |\n /_\\\n |";for(i=0;c=n[i++];)s+=c+"|\n |";return s+"_|\n/___\\\n VvV"}

```

Ungolfed:

```
function a(n){
var str="  |\n /_\\\n";
for(var i=0;i<n.length;i++){
str+=" |"+n[i]+"|\n";
}
return str+" |_|\n/___\\\n VvV";
}

```

EDIT: Saved 20 Bytes thanks to manatwork!

# Answer
> 1 votes
# Java 8, ~~132~~ ~~109~~ ~~107~~ 96 Bytes

```
i->"  |\n /_\\ \n"+i.chars().mapToObj(c->" |"+(char)c+"|")
                            .collect(joining("\n"))+"\n |_|\n/___\\\n VvV"

```

# Answer
> 1 votes
## Racket 82 bytes

```
(display"  |\n /_\\\n")(for((i s))(printf" |~a|~n"i))(display" |_|\n/___\\\n VvV")

```

Ungolfed:

```
(define (f s)
  (display "  |\n /_\\\n")
  (for((i s))
    (printf " |~a|~n"i))
  (display" |_|\n/___\\\n VvV"))

```

Testing:

```
(f "Racket")

```

Output: A Rocket by Racket!

```
  |
 /_\
 |R|
 |a|
 |c|
 |k|
 |e|
 |t|
 |_|
/___\
 VvV

```

# Answer
> 1 votes
# Python 3, 83 Bytes

```
s=input("")
print("  | \n /_\\")
for c in s:print(" |"+c+"|")
print("/___\\\n VvV")

```

# Answer
> 1 votes
# Excel VBA, <sub>~~105~~ ~~103~~ ~~102~~ ~~84~~</sub> 82 Bytes

Anonymous VBE Immediate Window function that takes input of type `Variant/String` from cell `[A1]` and outputs a rocket to the VBE immdiate window

**Golfed:**

```
?"  |":?" /_\":For i=0To[Len(A1)]:?" |"Mid([A1&"_"],i+1,1)"|":Next:?"/___\":?" VvV

```

**Output:**

```
[A1]="NASA.XLSM"
?"  |":?" /_\":For i=0To[Len(A1)]:?" |"Mid([A1&"_"],i+1,1)"|":Next:?"/___\":?" VvV
  |             '  <- Output
 /_\
 |N|
 |A|
 |S|
 |A|
 |.|
 |X|
 |L|
 |S|
 |M|
 |_|
/___\
 VvV

```

# Answer
> 1 votes
# Perl 5, 55+1 (-p flag)=56 bytes

```
s/(.)/\n |$1|/g;$_="  |  \n /_\\ $_ |_| \n/___\\\n VvV"

```

Takes string as a single line (with trailing newline) from stdin.

# Answer
> 1 votes
# SOGL V0.12, ~~27~~ 24 bytes

```
yQŗ4δ⁾≥‘π0ρ9³‘OΓ,{Ƨ |ΚΓO

```

Try it Here!

# Answer
> 1 votes
# 05AB1E, 27 bytes

```
S'|ì»"|
/_
ÿ
|_
/__
Vv".∞.c

```

Try it online!

## Explanation

```
S          # Split input into seperate characters
 '|ì»      # Prepend '|' to each and join by newline
     "|    # Half the rocket, where 'ÿ' is replaced by the processed input
/_
ÿ
|_
/__
Vv"
   .∞.c    # Intersected mirror and centralize

```

# Answer
> 1 votes
# Google Sheets, <sub>~~61~~</sub> 59 Bytes

Anonymous worksheet function that takes input from range `[A1]` and outputs a rocket to the calling cell

```
="  |
 /_\
"&RegExReplace(A1&"_","(.)"," |$1|
")&"/___\
 VvV

```

Example Output given `[A1]="Google`

```
  |
 /_\
 |G|
 |o|
 |o|
 |g|
 |l|
 |e|
 |_|
/___\
 VvV

```

# Answer
> 1 votes
# Jstx, 42 bytes

```
♀◘ááⁿ▄εá»▀▄84♀☺áⁿE►âD85♀►áⁿ▀ⁿ▄ε»▀▀▀▄▄εá╓÷╓

```

Explanation

```
♀◘ááⁿ▄εá»▀▄         # Push literal   |\n /_\
8                   # Print the first stack value, then a newline.
4                   # Enter an iteration block over the first stack value and push the iteration element register at the begining of each loop.
♀☺áⁿ                # Push literal  |
E                   # Push the difference of the second and first stack values.
►â                  # Push literal |
D                   # Push the sum of the second and first stack values.
8                   # Print the first stack value, then a newline.
5                   # End an iteration block.
♀►áⁿ▀ⁿ▄ε»▀▀▀▄▄εá╓÷╓ # Push literal  |_|\n/___\\n VvV

```

Try it online!

# Answer
> 1 votes
# Python 3.7, ~~79~~ 77 Bytes

```
o='  | \n /_\\\n'
for c in input()+"_":o+=f' |{c}|\n'
print(o+'/___\\\n VvV')

```

-2 bytes thanks to Value Ink

# Answer
> 1 votes
# Oracle SQL, 77 bytes

```
select'  |
 /_\
'||regexp_replace(x,'(.)',' |\1|
')||' |_|
/___\
 VvV'from t;

```

It works with an assumption that input string is stored in a table t(x), e.g.

```
with t(x) as (select 'Earth' from dual)

```

Test in SQL\*Plus

```
SQL> set pages 0
SQL> with t(x) as (select 'Earth' from dual)
  2  select'  |
  3   /_\
  4  '||regexp_replace(x,'(.)',' |\1|
  5  ')||' |_|
  6  /___\
  7   VvV'from t;
  |
 /_\
 |E|
 |a|
 |r|
 |t|
 |h|
 |_|
/___\
 VvV

```

# Answer
> 1 votes
# Pip, ~~71~~ ~~69~~ ~~64~~ 61 bytes

```
f:"|"u:C95Ps.s.fP" /_\"Fi,#a{Ps.f.a@i.f}P" |_|"P"/___\"" VvV"

```

Try it online!

\[Try it online!\]\[TIO-jyx4p3hj\]

```
f:"|"
u:C95
a:q
Ps.s.f
P" /_\"
F i ,#a{
    Ps.f.a@i.f     make the fuselage
}
P" |_|"
P"/___\"
" VvV"

```

nothing fancy happening here.

# Answer
> 1 votes
# C#, 159 bytes

```
public class P{public static void Main(string[]a){var f="";foreach (char c in a[0]){f+=" |"+c+"|\n";}System.Console.Write(@"  |
 /_\
"+f+@" |_|
/___\
 VvV");}}

```

Try Online

# Answer
> 1 votes
# Ruby, 85 bytes

```
puts"  |\n /_\\";gets.split('').append('_').each{|a|puts" |#{a}|"};puts"/___\\\n VvV"
```

Attempt This Online!

# Answer
> 0 votes
# JavaScript 63

```
s=>`  |\n /_\\\n${(s+'_').replace(/./g," |$&|\n")}/___\\\n VvV`

```

executed using `s("test")` for example.

# Answer
> 0 votes
# SpecBAS - 95 bytes

```
1 input a$: ?"  |"'" /_\"
2 for i=1 to len a$:? " |";a$(i);"|":next i
3 ?" |_|"'"/___\"'" VvV"

```

The apostrophe moves the cursor down a line, and `?` is shorthand for `PRINT`

# Answer
> 0 votes
# R, 148 bytes

```
f=function(b){cat("  |\n /_\\\n |",paste(as.character(unlist(strsplit(c(b,"_"),''))),collapse='|\n |'),"|\n/___\\\n VvV",sep="")}
f(commandArgs(T))

```

If above code is in sample.R file then run from command line

```
Rscript sample.R "GOKUL"

```

**Output:**

```
  |
 /_\
 |G|
 |O|
 |K|
 |U|
 |L|
 |_|
/___\
 VvV

```

# Answer
> 0 votes
## GNU sed, 53 bytes

```
1i\  |\n /_\\
s:.: |&|\n:g;s:$: |_|:g;$a\/___\\\n VvV

```

With GNU sed, you can omit the initial \ for the a command, so it is one byte less:

```
1i\  |\n /_\\
s:.: |&|\n:g;s:$: |_|:g;$a/___\\\n VvV

```

# Answer
> 0 votes
# sed, 51 bytes

```
s/$/_/
s/./ |&|\n/g
s!.*!  |\n /_\\\n&/___\\\n VvV!

```

Each line from stdin produces a new rocket on stdout.

# Answer
> 0 votes
# Dart, ~~110~~ 106 bytes

```
r(var s){s=s+'_';var o='  |\n /_\\\n',i=0;while(i<s.length)o=o+' |'+s[i++]+'|\n';return o+'/___\\\n VvV';}

```

**Try it out**

*EDIT: Saved 4 bytes, thanks!*

# Answer
> 0 votes
## dc, 55 bytes

Building a rocket with the **d**esck **c**alculator:

```
?[  |
 /_\
]n[[ |]nn[|
]nz0<R]sRz0!=R[ |_|
/___\
 VvV]p

```

Because dc interprets input as commands, our string's characters are assumed to be already on the stack and the code is acting more like a function accessing its arguments.

**Example run:**

```
me@LCARS:/PPCG$ dc -f rocket_science.dc
[A][S][A][N] #the stack is LIFO, so the arguments (characters) are in reverse order
  |
 /_\
 |N|
 |A|
 |S|
 |A|
 |_|
/___\
 VvV

```

# Answer
> 0 votes
# RProgN, 59 Bytes

```
'  |
 /_\' p '.' ' |%1|
' R "
$" '' R p ' |_|
/___\
 VvV' p

```

## Explination

```
'  |        #
 /_\'       # Build the top of the rocket
p           # Print it.
            # Input is taken implicitly.
'.' ' |%1|  # v
' R         # Replace each character with " |ITSELF|" followed by a newline.
"           # v
$" '' R  # Snip the last newline.
p           # Print the new body.
            #
' |_|       #
/___\       #
 VvV'       # Build the lower segment.
 p          # Print.

```

Try it Online!

# Answer
> 0 votes
# Crystal, 89 bytes

```
x=gets.to_s.chomp;y="  |
 /_\\
";x.each_char{|c|y+=" |#{c}|
"};puts y+" |_|
/___\\
 VvV"

```

Ungolfed:

```
input = gets
if !input
  STDERR.puts "Couldn't get input from stdin!"
  exit 1
end
puts <<-'END'
  |
 /_\
END
input.chomp.each_char do |char|
  puts " |#{char}|\n"
end
puts <<-'END'
/___\
 VvV
END

```

Example usage

Input: `Hello, world!`

Output:

```
  |
 /_\
 |H|
 |e|
 |l|
 |l|
 |o|
 |,|
 | |
 |w|
 |o|
 |r|
 |l|
 |d|
 |!|
 |_|
/___\
 VvV

```
* Actual newlines instead of `\n` to save 1 byte per newline
* `String#each_char` instead of `String#chars.each` to save 1 byte
* Temporary `y` variable instead of multiple `puts` calls to save a few bytes
* As Crystal is statically typed and `gets` can return `nil`, I had to find a way to workaround that. `not_nil!` raises an exception on runtime if the value is `nil` and otherwise just returns it, however, the `Nil` class also implements `to_s` (that returns a 0-length string) which is 4 characters (as opposed to 8). String also implements `to_s` (just returns itself), so this is a 4 characters shorter way to shut the compiler up.

# Answer
> 0 votes
# Pyth, 44 bytes

```
js[c2"  |  /_\\"m:" |_|"\_dzc3" |_| /___\ VvV

```

Try it online!

# Answer
> 0 votes
# Perl 5, ~~47~~ 46 + 1 (`-n`) = 47 bytes

```
s/./ |$&|
/g;say"  |
 /_\\
$_ |_|
/___\\
 VvV"

```

Try it online!

# Answer
> 0 votes
# Jq 1.5, 47 bytes

```
"  |
 /_\\"," |\((./"")[])|"," |_|
/___\\
 VvV"

```

Expanded

```
 "  |
  /_\\"             # Head

," |\((./"")[])|"   # Expand |x| with \(interpolation) for each
                    # value from (./"") split of input string by ""
," |_|
 /___\\
  VvV"              # Tail

```

Try it online!

# Answer
> 0 votes
# Ruby, 53 bytes

```
->s{'  |
 /_\
 |'+(s+?_).chars*'|
 |'+'|
/___\
 VvV'}

```

Try it online!

# Answer
> 0 votes
# , ~~52 46~~ 45 bytes

```
2 4|.'___\/','VvV',' |','/_\','|'(,.,.[),&'_'

```

Try it online!

# Answer
> 0 votes
# Bean, 51 bytes

xxd-style hexdump:
```
00000000: 56d8 8100 d7d0 80c3 cf20 5da3 7800 2080  VØ..×Ð.ÃÏ ]£x. .
00000010: 7b56 5881 0158 8102 a0a0 fc8a a0af dfdc  {VX..X..  ü. ¯ßÜ
00000020: 8aa0 7cfc 8aa0 7cfc 8aaf dfdf dfdc 8aa0  . |ü. |ü.¯ßßßÜ.
00000030: d6f6 56                                  ÖöV

```

Try it online!

## Equivalent JavaScript (ES6), 51 bytes

```
`  |
 /_\\
 |${[...a,'_'].join`|
 |`}|
/___\\
 VvV`

```

### Explanation

A full program taking the implicit first line of input as `a`, it pushes the string `'_'` onto the array to build the last section of the fuselage. This answer is essentially a compilation of edc65's answer into Bean.

# Answer
> 0 votes
# \>\<\>, 52 bytes

```
" ||"i:0(?\$a
__/"a$"_"~/>o<"  |"a" /_\"ar"VvV "a"\_

```

Try It Online

Adds everything to the stack before printing.

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), 126 bytes

```
	OUTPUT('O',6)
	O ='  |'
	O =' /_\'
	S =INPUT '_'
R	S LEN(1) . X REM . S	:F(O)
	O =' |' X '|'	:(R)
O	O ='/___\'
	O =' vVv'
END

```

Try it online!

Input requires a single trailing newline.

# Answer
> 0 votes
# Yabasic, 86 bytes

A script that takes input from STDIN and output to the console.

```
Input""s$
?"  |
 /_\\"
For i=0To Len(s$)?" |",Mid$(s$+"_",i+1,1),"|"Next
?"/___\
 VvV"

```

Try it online!

# Answer
> 0 votes
# Pascal (FPC), 130 bytes

```
var s:string;c:char;begin writeln('  |'#10' /_\');read(s);for c in s do writeln(' |',c,'|');writeln(' |_|'#10'/___\'#10' VvV')end.

```

Try it online!

Colouring doesn't work correctly because of `\'` :)

`#10` represents character with ascii code 10 which is a newline.

Basic program flow here: write the top of the rocket, read input, print a row for each character in input (`for ... in` loop added by FPC), write the bottom of the rocket.

# Answer
> 0 votes
## Perl 5, 46 + 3 (`-nlF` flag) = 49 bytes

```
say'  |
 /_\
',(map" |$_|
",@F,_),'/___\
 VvV'

```

Try it online.

# Answer
> 0 votes
# 05AB1E, 25 bytes

```
'|„/_©¤IìS'|ì`®¤«„Vv».º.c

```

Try it online or verify all test cases.

**Explanation:**

```
'|      '# Push string "|"
„/_      # Push string "/_"
   ©     # Store it in variable `®` (without popping)
¤        # Get the last character of this string (without popping the string itself): "_"
 Iì      # Prepend the input in front of this "_"
         #  i.e. "Bob" → "Bob_"
   S     # Convert it to a list of characters
         #  → ["B","o","b","_"]
    '|ì '# Prepend a "|" in front of each character
         #  → ["|B","|o","|b","|_"]
       ` # Push all those strings separated to the stack
®        # Push variable `®`: "/_"
 ¤«      # Append it's last character to itself: "/__"
„Vv      # Push string "Vv"
»        # Now join all strings on the stack by newlines
         #  → "|
         #     /_
         #     |B
         #     |o
         #     |b
         #     |_
         #     /__
         #     Vv"
 .º      # Intersected mirror this entire string (towards the right)
         #  → "|
         #     /_\
         #     |B|
         #     |o|
         #     |b|
         #     |_|
         #     /___\
         #     VvV"
   .c    # And then centralize the string (adding leading spaces where necessary)
         #  → "  |
         #      /_\
         #      |B|
         #      |o|
         #      |b|
         #      |_|
         #     /___\
         #      VvV"
         # (after which the result is output implicitly)

```

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), 133 bytes

```
	OUTPUT('O',6)
	O ='  |'
	O =' /_\'
	I =INPUT
S	I LEN(1) . X REM . I	:F(E)
	O =' |' X '|'	:(S)
E	O =' |_|'
	O ='/___\'
	O =' VvV'
END

```

Try it online!

Always funny to see the shape of the rocket in these answers.

Only interesting thing here is `OUTPUT('O',6)`, which sets `O` to be the `OUTPUT` variable into unit number 6, which is STDOUT.

# Answer
> 0 votes
# Python 3, 81 bytes

```
lambda x:"  |\n /_\\\n%s/___\\\n VvV"%''.join([" |%s|\n"%t for t in list(x+'_')])

```

Try it online!

# Answer
> 0 votes
# Stax, 25 bytes

```
æ¢ïÆn£╗ù♂»Σ√m3,^╝}.Σ8Æ╤º⌡

```

Run and debug it

# Answer
> 0 votes
# perl6 - 69

```
say "  |\n /-\\\n |{@*ARGS.comb.join("|\n |")}|\n |_|\n/___\\\n VvV"

```

# Answer
> 0 votes
# 33, 75 69 bytes

-6 bytes because I remembered \n is a thing.

```
"  |\n /_\\"pi1bzst' | |'j[2ktNpNitclz1aztstcjz]" |_|\n/___\\\n VvV"p

```

Try it online hopefully coming soon

Explanation:

```
"  |\n /_\\"pi                     | Print the first part of the rocket
-----------------------------------|
1bzs                               | Get the first command-line argument
            j[       clz1aztstcjz] | For each character in it
     t' | |'  2k                   | - Put it in the fuselage "| |"
                NpNi               | - If it is not null, print it (Null checking is due to the way loops work in 33)
-----------------------------------|
" |_|\n/___\\\n VvV"p              | Print the bottom of the rocket

```

# Answer
> 0 votes
# GolfScript, 53 bytes

```
"  |\n /_\\"n@0$1/\;{" |"\"|\n"}/" |_|\n/___\\\n VvV"

```

Try it online!

```
"  |\n /_\\"n        ascii art
@                    rotate so input is on top
0$1/                 split input into elements of size 1
\;                   swap top elements, pop top (input)
{" |"\"|\n"}/        now the top element is the input array so for each we push the left pipe, swap, then push the right pipe
" |_|\n/___\\\n VvV" ascii art

```

# Answer
> 0 votes
Python 3, 86 bytes

code-golf:

```
n=input();print('  |\n / \ ')
for l in n:print(' |'+l+'|')
print(' |_|\n/___\ \n VvV')

```

normal:

<pre><code>n = input()
print('  |')
print(' / \')

for l in n:
    print(' |' + l + '|')

print(' |_|')
print('/___\')
print(' VvV')
```
</code></pre>

# Answer
> 0 votes
# GNU AWK, 74 bytes

```
BEGIN{RS=".|";print"  |\n /_\\"}END{print" |_|\n/___\\\n VvV"}$0=" |"RT"|"

```

Try it online!

AWK was made for this kind of problem.

The `BEGIN` pattern do things before the input is read. Changing the default `RS` variable to `".|"` makes AWK read the input one character at a time (i.e., as the `/./` regex).

`RT` is exclusive to GNU AWK, being the text of the `RS` captured by the regex.

The `END` pattern do things after the input is finished.

---
Tags: code-golf, string, ascii-art
---


# Question
Title: Split given integer into a given number of integers, each within given bounds
# Input variables:

(Names are just examples, they don't need to be named like this)

* `GrandTotal` \- integer to divide
* `SplitCount` \- number of output integers required
* `UpperLimit` \- highest valid value for any one output integer
* `LowerLimit` \- lowest valid value for any one output integer

# Valid Output:

Outout must be a random set of `SplitCount` integers, each between `UpperLimit` and `LowerLimit` (your language's RNG is fine), the sum of which is `GrandTotal`.

The output should be uniformly random in that any valid output should be equally likely. For example input of \[8,3,4,2\] has the following six valid outputs:

1. 2,3,3
2. 3,2,3
3. 3,3,2
4. 2,2,4
5. 2,4,2
6. 4,2,2

Each output should have, therefore, 1/6 chance of occurring.

The order of the output matters: 5,8,7 is not an equal set to 5,7,8. Both outputs must be equally likely if either is possible.
<sub>(This does mean that output where all three integers are the same is less likely output to one where all three are different: Given `GrandTotal`=6, `SplitCount`=3, `UpperLimit`=4, `LowerLimit`=1, a set including 1, 2 and 3 can appear in 6 different configurations, while a set of all 2s can only appear in one, making it 6 times as likely that *one of* the varied sets will appear, rather than the set of 3 2s.)</sub>

# Valid Input:

Any input variables should work, assuming that the following is true

1. `UpperLimit` * `SplitCount` \>= `GrandTotal`
2. `LowerLimit` * `SplitCount` \<= `GrandTotal`
3. all input variables are positive integers.

## Tie-Breaker

Submissions that accept invalid input but return output as though it was the closest valid input would win a tie-breaker. (eg `GrandTotal`=10, `SplitCount`=2, `UpperLimit`=3, `LowerLimit`=2 returning \[5,5\] treats the `UpperLimit` variable as though it was the lowest valid input, rather than what it was.) Closest here means change as few variables as possible, and change those variables by the smallest possible integer. Ideally, change the latest possible variable(s) (here, `SplitCount` could have been changed to make input valid, but `UpperLimit` is a later variable.)

# Sample in-out range

| GrandTotal | SplitCount | UpperLimit | LowerLimit | Possible Output Range |
| --- | --- | --- | --- | --- |
| 11 | 2 | 7 | 4 | 4,7;5,6;6,5;7,4 |
| 8 | 3 | 11 | 2 | 2,3,3;3,2,3;3,3,2;2,2,4;2,4,2;4,2,2 |
| 13 | 2 | 8 | 4 | 8,5;7,6;6,7;5,8 |
| 16 | 2 | 8 | 4 | 8,8 |
| 16 | 2 | 10 | 4 | 10,6;9,7;8,8;7,9;6,10 |
| 16 | 4 | 10 | 4 | 4,4,4,4 |

# Answer
# 05AB1E, 8 bytes

```
ŸIãʒOQ}Ω

```

Inputs in the order `UpperLimit,LowerLimit,SplitCount,GrandTotal`.

Try it online or verify all test cases (without the ).

**Explanation:**

```
Ÿ       # Take the first two (implicit) inputs and push a list in the range
        # [LowerLimit,UpperLimit]
 Iã     # Create all combinations of a size of the third input SplitCount using
        # the cartesian product
   ʒ    # Filter this list of lists by:
    O   #  Sum the list
     Q  #  Check if it's equal to the fourth (implicit) input GrandTotal
   }Ω   # After the filter: pop and leave a random list
        # (which is output implicitly as result)

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 49 bytes

```
RandomChoice@Pick[t=Range@##3~Tuples~#2,Tr/@t,#]&

```

Try it online!

Input `[GrandTotal, SplitCount, LowerLimit, UpperLimit]`.
> 3 votes

# Answer
# Python 3.8 (pre-release), 116 bytes

*-12 bytes thanks to `Jitse`*

Accepts input in the form of `GrandTotal,SplitCount,UpperLimit,LowerLimit`.
Returns a randomly picked range, as a tuple, from a list of possible ranges.

```
lambda g,s,u,l:r.choice([p for p in i.product(range(l,u+1),repeat=s)if sum(p)==g])
import random as r,itertools as i

```

Try it online!
> 2 votes

# Answer
# Burlesque, 49 bytes

```
r@s1Js2rzjCBf{++g2==}f{{g1j~[}al}sa-.3 0x/rn1.+si

```

Try it online!

```
r@s1          # Range from lowerLimit to upperLimit and save to 1
Js2           # Duplicate grandTotal and save to 2
rz            # Range [0, grandTotal]
jCB           # Combinations of SplitCount
f{++g2==}     # Filter for sum == grantTotal
f{{g1j~[}al}  # Filter for all elements in range
sa-.3 0x/rn   # Generate infinite list of random numbers [0, len)
1.+si         # Take 1 and select it

```
> 1 votes

# Answer
# Bash, 164 bytes

```
echo>0
seq 1 $2|xargs -I, sh -c "rm ,;seq $4 $3|xargs -i sh -c \"<\$((,-1)) sed s/^/{}\ />>,\""
<$2 tr \  +|sed s/+$//|bc|pr -mt $2 -|grep $1$|cut -d\	 -f1|shuf -n1

```

Try it online!
> 0 votes

# Answer
# JavaScript (ES6), 85 bytes

Expects `(count, lower, upper)(total)`.

```
(n,a,b)=>g=(t,k=n,s=t,...o)=>k?g(t,k-1,s-=q=a-Math.random()*(~b+a)|0,...o,q):s?g(t):o

```

Try it online!

(NB: The function is likely to stack overflow on some test cases. The above test includes some extra recovery code.)
> 0 votes

# Answer
# Charcoal, 34 bytes

```
ＮθＮηＮζ≔⊕⁻ＮζεＩ‽ΦＥＸεη⁺﹪÷ιＸε…⁰ηεζ⁼Σιθ

```

Try it online! Link is to verbose version of code. Takes input in the order GrandTotal, SplitCount, LowerLimit, UpperLimit. Explanation:

```
ＮθＮηＮζ

```

Input the grand total, split count and lower limit.

```
≔⊕⁻Ｎζε

```

Input the upper limit and calculate the length of the inclusive range from the lower limit to the upper limit.

```
Ｉ‽ΦＥＸεη⁺﹪÷ιＸε…⁰ηεζ⁼Σιθ

```

Generate the Cartesian product of the split count number of inclusive ranges, filter out those whose sum isn't the desired grand total, and output one uniformly at random.
> 0 votes

---
Tags: code-golf, random, integer-partitions
---


title: Rotational symmetry of string

text:
# Question
Title: Rotational symmetry of string
A rotation "is made by splitting a string into two pieces and reversing their order". An object is symmetrical under an operation if the object is unchanged after applying said operation. So, a "rotational symmetry" is the fact that a string remains unchanged after "rotation".

Given a non-empty string `s` consisting of only letters from `a` to `z`, output the highest order of the rotational symmetry of the string.

Testcases:

```
input        output
a            1
abcd         1
abab         2
dfdfdfdfdfdf 6

```

This is . Shortest answer in bytes wins. Standard loopholes apply.

# Answer
## Retina, 15 bytes

```
(^.+?|\1)+$
$#1

```

Try it online!

Matches the entire string by repeating a substring (shorter substrings are prioritised due to the ungreedy `.+?`) and replaces the entire string with the number of repetitions we used.
> 8 votes

# Answer
# Jelly, 3 bytes

```
ṙJċ

```

Try it online!
> 6 votes

# Answer
# 05AB1E, 8 bytes

```
gGDÀ})QO

```

Try it online!

**Explanation**

```
gG  }      # len(input)-1 times do:
  D        # duplicate
   À       # rotate left
     )     # wrap result in a list
      Q    # compare each to input for equality
       O   # sum

```
> 3 votes

# Answer
# Prolog (SWI), 64 bytes

```
A+B:-findall(X,(append(X,Y,A),append(Y,X,A)),[_|Z]),length(Z,B).

```

Try it online!

Defines a predicate `+/2` that takes a string (in the form of a list of character codes) as its first argument (`A`) and sets its second argument (`B`) to the order of the highest order symmetric rotation.

## Explanation

This program uses the fact that the set of symmetric rotations on a string are a cyclic group and so the order of the set of symmetric rotations is equal to the order of the highest order symmetric rotation. Thus the program is able to calculate the desired result by finding the total number of symmetric rotations on the input string.

### Code Explanation

The majority of the heavy lifting is done by a call to the `findall/3` predicate. The `findall/3` predicate finds all the different possible values for the first argument (`X` in this case) such that the expression given as the second argument is true (`(append(X,Y,A),append(Y,X,A))`, more on that later). Finally it stores each of these possible values of `X` as a list in the final argument (`[_|Z]`).

The expression passed into `findall/3` as the second arugment, `(append(X,Y,A),append(Y,X,A))` uses the `append/3` predicate to specify that `X` concatenated with some yet undefined `Y` must be equal to `A`, the input string, and that the same `Y` concatenated with `X` must also be equal to `A`. This means that `X` must be some prefix of `A` such that if it is removed from the front of `A` and added to the back then the resulting string is the same as `A`. The set of `X`s with this property *almost* has a one-to-one correspondence with the symmetric rotations of `A`. There is always exactly one case of double counting which is caused by the fact that both the empty string and `A` are prefixes of `A` that correspond to the 0-rotation of `A`. Since the `0`-rotation of `A` is always symmetric the length of the resulting list of `X`s from `findall/3` will be one greater than the number of symmetric rotations on `A`.

To solve the double counting problem, I use pattern matching on the third argument of the `findall/3` predicate. In Prolog lists are represented as pairs of their head (the first element) and their tail (the rest). Thus `[_|Z]` represents a list whose tail is equal is equal to `Z`. This means that the length of `Z` is one less than the number of prefixes found by the `findall/3` predicate and thus equal to the number of symmetric rotations of `A`. Finally, I use the `length/2` predicate to set `B` to the length of `Z`.
> 3 votes

# Answer
## JavaScript (ES6), ~~42~~ 41 bytes

*Saved 1 byte thanks to @l4m2*

```
s=>s.length/s.match`(.+?)\\1*$`[1].length

```

### Test cases

```
let f =

s=>s.length/s.match`(.+?)\\1*$`[1].length

console.log(f("a"))            // 1
console.log(f("abcd"))         // 1
console.log(f("abab"))         // 2
console.log(f("dfdfdfdfdfdf")) // 6
```
> 2 votes

# Answer
### Python, 31 bytes

```
lambda s:len(s)/(s+s).find(s,1)

```

Find the first nonzero index of `s` in `s+s` to figure out how far we have to rotate it to get `s` back, then divide the length of `s` by that number. Based on ideas I saw elsewhere.
> 2 votes

# Answer
# Vyxal `r`, 4 bytes

```
żvǓO

```

Try it Online!

Port of Jelly answer.
> 2 votes

# Answer
# Japt, 7 bytes

```
¬x@¥UéY

```

Test it online!

### Explanation

```
 ¬ x@   ¥ UéY
 q xXY{ ==UéY}  // Expanded
Uq xXY{U==UéY}  // Variable introduction
                // Implicit: U = input string
Uq              // Split U into chars.
   xXY{      }  // Map each item X and index Y by this function, then sum the results:
       U==UéY   //   Return U equals (U rotated by Y characters).
                // Implicit: output result of last expression

```
> 1 votes

# Answer
# Haskell, 49 bytes

```
g x=sum[1|a<-[1..length x],drop a x++take a x==x]

```

Try it online!

# Haskell, 49 bytes

```
g x=sum[1|(a,_)<-zip[1..]x,drop a x++take a x==x]

```

Try it online!

## Explanation

This uses the simple solution @0' pointed out. Since the rotations of the string form a cyclic group the highest order element is the same as the size of the group thus we can get the order of the unit by finding the number of symmetric rotations.

The codes simple does a list comprehension and counts the number of rotations that preserve the original string.
> 1 votes

# Answer
# Factor, ~~42~~ 38 bytes

```
[ dup all-rotations [ = ] with count ]

```

Try it online!

Count how many rotations of the input are equal to the input.
> 1 votes

# Answer
# PHP, 66 Bytes

```
for(;strtr($a=$argn,[substr($a,0,++$i)=>""]););echo strlen($a)/$i;

```

Try it online!

# PHP, 67 Bytes

```
preg_match('#^(.+?)\1*$#',$argn,$t);echo substr_count($argn,$t[1]);

```

Try it online!
> 0 votes

# Answer
# C (gcc), 59 bytes

```
-Df(d,s)=for(d=n=strlen(s);n%d|memcmp(s,s+n/d,n-n/d);d--)

n;

```

Try it online!
> 0 votes

---
Tags: code-golf, string, abstract-algebra
---


title: Convert angle to clock time

text:
# Question
Title: Convert angle to clock time
Your task is to make a program or function that takes a nonnegative integer (or a different convenient format to represent it) that represents an angle measure in degrees from 0 to 180 (inclusive) as input and outputs every possible time (in hours and minutes; no seconds) on an analog clock where the measure of the smaller angle between the hour hand and minute hand is equal to the inputted angle measure.

# Rules

* Output can be a list of times, a string of the times with separators, or multiple outputs of times.
* The times can be formatted in any way that can be identifiable as clock times by humans, such as `hh:mm` or a list of the hours and minutes.
* The times should be from 12:00 to 11:59 (e.g. `0:00` and `22:00` are invalid outputs).
* Standard loopholes apply.
* This is , so the shortest code in bytes in each language wins.

# Test cases

```
Input    | Output
---------|------------
0        | 12:00
90       | 3:00, 9:00
180      | 6:00
45       | 4:30, 7:30
30       | 1:00, 11:00
60       | 2:00, 10:00
120      | 4:00, 8:00
15       | 5:30, 6:30
135      | 1:30, 10:30
1        | 4:22, 7:38
42       | 3:24, 8:36
79       | 3:02, 8:58
168      | 1:36, 10:24
179      | 1:38, 10:22
115      | 1:50, 10:10

```

Interestingly, there are only two possible times in hours and minutes (except for 0 and 180 degrees) for every integer (or number with a fractional part of 0.5) degree input and on an analog clock the times represent horizontally flipped images of each other.

# Answer
> 7 votes
# Jelly, 22 bytes

```
60Ḷ12p×“<¿‘Hạ/eʋƇØ°_,Ɗ

```

A monadic Link that accepts a non-negative integer in \\$\[0,180\]\\$ and yields a list of pairs of `[hour, minute]` of a twelve-hour analogue clock.

**Try it online!** Or see the test-suite.

### How?

If we label straight up (12:00) as \\$0\\$ degrees, then at a given exact minute of \\$h\\$ hours and \\$m\\$ minutes, the minute hand is at \\$\frac{360 m}{60}\\$, while the hour hand is at \\$\frac{360 h}{12}+\frac{360m}{60 \times 12}\\$ degrees. A clockwise angle between the hour hand and minute hand is, therefore:

$$A=\frac{360 h}{12}+\frac{360m}{60 \times 12}-\frac{360 m}{60}$$ $$A=30h+\frac{m}{2}-6m$$ $$A=30h-\frac{11m}{2}$$

The code makes all of the times as `[h, m]` pairs and filters them for when the absolute value of the above angle \\$A\\$ is either equal to the input or \\$360\\$ minus the input.

```
60Ḷ12p×“<¿‘Hạ/eʋƇØ°_,Ɗ - Link: integer, A in [0,180]
60                     - sixty
  Ḷ                    - lowered range -> [0..59]
   12                  - twelve
     p                 - Cartesian product -> Times = [[1,0],...,[1,59],...,[12,59]]
                     Ɗ - last three links as a monad - f(A):
                 Ø°    -   360
                   _   -   minus A
                    ,  -   paired with A -> Angles=[360-A,A]
                Ƈ      - filter keep those Times for which:
               ʋ       -   last four links as a dyad - f(Time,Angles):
       “<¿‘            -     code-page indices      = [60,11]
      ×                -     Time times [60,11]    -> [60h,11m]
          H            -     halve                 -> [30h,11m/2]
             /         -     reduce by:
            ạ          -       absolute difference -> abs(30h-11m/2)
              e        -     exists in Angles?

```

# Answer
> 4 votes
# Wolfram Language (Mathematica), 44 bytes

-2 bytes thanks to @Steffan.

```
{}⋃Mod[458{#,-#},720,60]~IntegerDigits~60&

```

Try it online!

# Answer
> 4 votes
# PARI/GP, 44 bytes

```
a->Set([[(b\60-1)%12+1,b%60]|b<-458*[a,-a]])
```

Attempt This Online!

The `%12` trick is stolen from G B's Ruby answer.

# Answer
> 3 votes
# Ruby, ~~82 79 55~~ 47 bytes

```
->d{[k=262*d,-k].map{|c|[c/60%-12+12,c%60]}|[]}

```

Try it online!

Stolen from various other answers: the angle between the two hands is increased by 1 degree after 4h22m.

# Answer
> 3 votes
# , ~~61~~ ~~60~~ 55 bytes

```
\(a,b=458*c(a,-a))unique(cbind((b%/%60-1)%%12+1,b%%60))
```

Attempt This Online!

Port of @alephalpha's answer.

Outputs as a matrix with hours in the first column and minutes in the second.

---

### , ~~84~~ 72 bytes

*Edit: -9 bytes thanks to @Kirill L..*

```
\(a)t(which(outer(1:12,0:59,\(x,y)abs(30*x-5.5*y)%in%c(a,360-a)),T))-0:1
```

Attempt This Online!

Outputs as a matrix with hours in the first row and minutes in the second.

The formula looks exactly like in Jonathan Allan's answer.

# Answer
> 2 votes
# Charcoal, 45 bytes

```
ＮθＥΦ³⁶⁰№﹪×¹¹⟦±ιι⟧³⁶⁰θ⪫Ｅ⟦∨÷ι³⁰¦¹²⊗﹪ι³⁰⟧﹪%02dλ:

```

Try it online! Link is to verbose version of code. Explanation: The angle between the hands increases by 11° every two minutes.

```
Ｎθ

```

Input the angle.

```
ＥΦ³⁶⁰

```

Loop over all times from `12:00` to `11:58` in multiples of 2 minutes.

```
№﹪×¹¹⟦±ιι⟧³⁶⁰θ

```

Keep only those times where the angle between the hands or its negation equals the input.

```
⪫Ｅ⟦∨÷ι³⁰¦¹²⊗﹪ι³⁰⟧﹪%02dλ:

```

Format the doubled number of minutes as a time.

If outputting `12:00` or `06:00` twice for inputs of `0` and `180` respectively had been legal, then for ~~41~~ 39 bytes:

```
ＮθＥ×⟦²⁶²¦⁴⁵⁸⟧θ⪫Ｅ⟦⊕﹪⊖÷ι⁶⁰¦¹²﹪ι⁶⁰⟧﹪%02dλ:

```

Try it online! Link is to verbose version of code. Explanation: The number of minutes is given by the angle multiplied by `262` or `458` (effectively modulo `720`, but this is calculated by taking the hour modulo `12`, with a zero result becoming `12`).

# Answer
> 2 votes
## JavaScript (ES6), ~~79~~ 78 bytes

Only works in locales with UTC that use the 12 hour clock.

```
f=
n=>(n%180?[262,458]:[262]).map(m=>new Date(m*n*6e4).toTimeString().slice(0,5))
```

```
<input type=number min=0 max=180 oninput=o.textContent=f(this.value|0)><pre id=o>
```

Longer version that works everywhere, except on days with DST transitions:

```
f=
n=>(n%180?[262,458]:[262]).map(m=>new Date(0,0,0,0,m*n).toLocaleString('en-US',{timeStyle:'short'}).slice(0,5))
```

```
<input type=number min=0 max=180 oninput=o.textContent=f(this.value|0)><pre id=o>
```

Longest version that always works everywhere:

```
f=
n=>(n%180?[262,458]:[262]).map(m=>new Date(m*n*6e4).toLocaleString('en-US',{timeStyle:'short',timeZone:'utc'}).slice(0,5))
```

```
<input type=number min=0 max=180 oninput=o.textContent=f(this.value|0)><pre id=o>
```

Explanation: The angle between the hands is  at `04:22` and its reflection, which correspond to `262` and `458` minutes past midnight. Any larger angle can be obtained by simply multiplying the desired angle by those two numbers of minutes.

Edit: Saved 1 byte thanks to @MatthewJensen.

# Answer
> 2 votes
# Haskell, ~~65~~ 64 bytes

```
f a=[[h,m]|h<-[1..12],m<-[0..59],elem(abs(h*30-5.5*m))[a,360-a]]

```

Try it online!

Ironically, I wrote this to try some taste of Curry, but it failed with some errors I struggle to understand. Worked in Haskell though...

Thanks to pajonk for -1.

# Answer
> 2 votes
# Vyxal `M`, 22 bytes

```
6d59Ẋ'30₀›½"*÷εkR⁰-⁰"c

```

Try it Online!

You can also run all the test cases but be prepared to wait at least a minute.

## How?

```
6d59Ẋ'30₀›½"*÷εkR⁰-⁰"c
6d                     # Push 6 doubled, which is 12 (this is to avoid having to put a space after it)
  59                   # Push 59
    Ẋ                  # Cartesian product of these two numbers, which are implicitly cast to inclusive zero ranges
     '                 # Filter this list for:
      30               #  Push 30
        ₀›             #  Push 10 + 1, which is 11. This is to avoid having to put a space before it
          ½            #  Halve to make 5.5
           "           #  Pair these two values to [30, 5.5]
            *          #  Multiply both by the current item
             ÷         #  Push both values of the multiplied pair to the sstack
              ε        #  Absolute difference of the two
               kR⁰-    #  Push 360 minus the input
                   ⁰"  #  Pair with the input
                     c #  Does this list contain the absolute difference pushed earlier?

```

# Answer
> 2 votes
# JavaScript (V8), ~~77~~ 72 bytes

-5 bytes thanks to Arnauld!

```
a=>new Set([a*262,a*458].map(m=>(m/60%12|0||12)+(m%60>9?':':':0')+m%60))

```

Try it online!

# Answer
> 1 votes
# Zsh, 81 bytes

```
>{-,}{$[x=$1*2],$[720-x]}
eval h={1..12}\;m={0..59}';<$[h%12*60-m*11]&&<<<$h:$m;'
```

Attempt This Online!

Damn floating point errors!

# Answer
> 1 votes
# Retina 0.8.2, 89 bytes

```
.+
$*_¶$&$*_
\G_
262$*
_
458$*
1{720}

D`
G`.
%`^(.{60})*(.*)
$#1:0$.2
%`^0
12
:0(..)
:$1

```

Try it online! Outputs times on separate lines but link is to test suite that joins with comma for convenience. Explanation:

```
.+
$*_¶$&$*_

```

Convert to unary twice.

```
\G_
262$*
_
458$*

```

Multiply the first copy by `262` and the second by `458`.

```
1{720}

D`
G`.

```

Reduce modulo `720` and deduplicate.

```
%`^(.{60})*(.*)
$#1:0$.2
%`^0
12
:0(..)
:$1

```

Format as a time.

# Answer
> 1 votes
# Python 3, 51 bytes

```
lambda n:{(n*i//60%-12+12,n*i%60)for i in(262,458)}

```

Try it online!

Ported from various other answers.

# Answer
> 1 votes
# 05AB1E, 25 bytes

```
12L59Ýâʒ30T>;‚*ÆÄU360α‚Xå

```

Port of *@JonathanAllan*'s Jelly answer, and the output-format is also the same: a (1 or 2-sized) list of pair(s) of \\$\[h,m\]\\$.

Try it online or verify all test cases.

**Explanation:**

```
12L           # Push a list in the range [1,12]
59Ý           # Push a list in the range [0,59]
   â          # Cartesian product of both lists to create all possible pairs
    ʒ         # Filter these pairs by:
     30       #  Push 30
     T>;      #  Push 5.5 (10 +1 /2)
        ‚     #  Pair them together
         *    #  Multiply the values in the pairs [30h,5.5m]
          Æ   #  Reduce this pair by subtracting
           Ä  #  Convert it to its absolute value
            U #  Pop and store this value in variable `X`
     360α     #  Get the absolute difference of the (implicit) input and 360
         ‚    #  Pair the (implicit) input with this 360-input
          Xå  #  Check if value `X` is in this pair
              # (after which the filtered result is output implicitly)

```

# Answer
> 1 votes
# Excel, 98 bytes

```
=LET(t,ROW(1:720)/1440,h,HOUR(t),m,MINUTE(t),a,ABS(30*h-11*m/2),FILTER(h&","&m,(a=A1)+(a=360-A1)))

```

Input is in the cell A1. Output is wherever the formula is and - usually - the cell below it.

The LET() function allows you to define variables for later reference. Here's each piece explained.

* `t,ROW(1:720)/1440` an array of time values from 0.0 to 0.5 (noon) broken into 1 minute long pieces.
* `h,HOUR(t)` an array the same length as `t` but just the hours.
* `m,MINUTE(t)` an array the same length as `t` but just the minutes.
* `a,ABS(30*h-11*m/2)` math based on other answers here.
* `h&","&m` combines the two arrays into the output format desired.
* `(a=A1)+(a=360-A1)` checks if the math matches the input angle.
* `FILTER(~,~)` returns just the outputs where the match matched the angle.

---

I also found this solution that clocks in at 103 bytes and outputs the results into a single cell.

```
=LET(h,COLUMN(A:L)-1,m,ROW(1:60)-1,a,ABS(30*h-11*m/2),TEXTJOIN("
",1,IF((a=A1)+(a=360-A1),h&","&m,"")))

```

# Answer
> 1 votes
# Desmos, ~~66~~ 61 bytes

```
i=[262,458]
f(n)=(mod(floor(in/60),-12)+12,mod(i,60)n).unique

```

Try it on Desmos!

*-5 bytes thanks to Aiden Chow*

# Answer
> 0 votes
# C#, 71 bytes

```
(int a)=>new[]{458*a,262*a}.Select(x=>((x/60+11)%12+1,x%60)).Distinct()

```

Try it online!

Based on various other answers. Like Jitse's Python 3 solution, I'm using both magic numbers 262 and 458 to get the answers in minutes, modulo 720 minutes. For the hours, I'm using the trick to add 11, take the remainder of dividing by 12, and then add 1 to get a value from 1 to 12. Since duplicate answers for 0 and 180 aren't allowed, I'm using the Distinct function from Linq.

Community guidelines for C# require a type for lambdas hence the `(int a)=>`, if untyped lambdas are OK we can make that `a=>` for a saving of 6 bytes.

---
Tags: code-golf, math, clock
---


# Question
Title: Draw an ASCII envelope based on size input
You want to send an ASCII letter to someone, but you need an envelope to put it in. Your task is to output an envelope given a size as input.

Rules:

* Given positive integer input `i`, your envelope will be `i` characters tall (not counting the top row), and `i*2` characters wide (not counting the side columns). In other words, your envelope will be `i+1` characters tall and `(i*2)+2` characters wide.
* Output **must** be in the form of text, using `\`, `/`, `_`, `|`, and .
* The flap of the envelope must be on the row above the bottom row of the envelope unless impossible (as with an envelope of size 1).
* Trailing whitespace is allowed.

Example input and output:

```
1
->
 __
|\/|

2
->
 ____
|\__/|
|____|

3
->
 ______
|\    /|
| \__/ |
|______|

4
->
 ________
|\      /|
| \    / |
|  \__/  |
|________|

```

This is a challenge, so shortest code wins!

# Answer
> 2 votes
# Charcoal, 28 bytes

```
Ｎθ←×_θ↑θ→Ｐ×_θ↓¿⊖θ«↘⊖θ←¶_»\‖Ｍ

```

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

```
Ｎθ

```

Input `i`.

```
←×_θ

```

Draw half of the bottom row of `_`s.

```
↑θ

```

Draw the left column of `|`s.

```
→Ｐ×_θ↓

```

Draw the top row of `_`s.

```
¿⊖θ«

```

If `i` is not `1`, then...

```
↘⊖θ←¶_

```

... draw the `i-1` `\`s on the left and one of the two middle `_`s, ...

```
»\

```

... otherwise overwrite the bottom `_` with a `\`.

```
‖Ｍ

```

Reflect to complete the envelope.

# Answer
> 3 votes
# 05AB1E, 41 bytes

```
i'_„|\‚ë2ÊiÍFðI×'\Nǝ}}„\_Ij¤I×©)'|ì®š}º.c

```

Try it online or verify the first few outputs.

**Expanation:**

```
i              # If the (implicit) input is 1:
 '|„|\‚       '#  Push pair of strings ["_","|\"]
ë              # Else:
 2Êi           #  If the (implicit) input is NOT 2:
    ÍF         #   Loop `N` in the range [0,input-2):
      ðI×      #    Push a string with the input amount of spaces
         '\Nǝ '#    Insert a "\" character at index `N`
     }         #   Close the loop
   }           #  Close the inner if-statement
„\_            #  Push string "\_"
   Ij          #  Pad leading spaces until the string is of a length equal to the input
     ¤         #  Push the last character (without popping): "_"
      I×       #  Repeat it the input amount of times as string
        ©      #  Store it in variable `®` (without popping)
)              #  Wrap all values on the stack into a list
 '|ì          '#  Prepend a "|" in front of each string
    ®š         #  Prepend string `®` to the list
}              # Close the outer if-else statement
 º             # Mirror each inner string
  .c           # Join by newlines and centralize
               # (adding a single leading space to the first "_"-string)
               # (after which the result is output implicitly)

```

# Answer
> 3 votes
# Python 3, ~~207~~ ~~181~~ ~~180~~ ~~177~~ ~~146~~ 130 bytes

```
lambda i,u="__",b=" ":b+u*i+"".join(f"\n|{b*x}\{(b*(i*2+~x*2),u)[x==i-2]}/{b*x}|"for x in range(i-1))+("\n|\/|",f"\n|{u*i}|")[i>1]

```

Try it online!

**To 181 bytes:** Golfed the code even more thanks to @Kevin Cruijssen.

**To 180 bytes:** -1 bytes thanks again to @Kevin Cruijssen, by replacing the `i!=1` with `i<2`.

**To 177 bytes:** Moved the whole "nonsense soup" line onto the same line as the `for` loop, thanks to @des54321's suggestion.

**To 146 bytes:** Some *major* byte-saving golfs thanks to @ElPedro.

**To 130 bytes:** More golfs by @Kevin Cruijssen, including replacing `\\` with `\`.

# Answer
> 3 votes
# Vyxal `C`, 49 bytes

```
1=[\_‛|\"|2≠[⇩ʁ(⁰Ifn\\Ȧ¤j)]‛\_⁰r:t⁰ẋ:£W\|vp¥p]vøṀ

```

Try it Online!

# Answer
> 2 votes
# Python 3.8 (pre-release), 107 bytes

```
lambda n:[' '+(a:="__"*n)]+['|%s|'%[a," "*i+f'\{"_ "[i<n-2]*2*(n+~i)}/'+" "*i][i<n-(n>2)]for i in range(n)]

```

Try it online!

-20 by @emanresuA

# Answer
> 2 votes
# Javascript, 181 177 174 Bytes

Code is split into newlines for readability, see link for 174 byte string.

```
c=n=>{
r=(d,n)=>d.repeat(n);
z='\n|';
b=r('_',n*2);
o=' '+b;
for(e=0;e<n-1;e++)y=r(' ',e),o+=z+y+'\\'+r(e!=n-2?' ':'_',n*2-2*(e+1))+'/'+y+'|';
o+=(n==1?z+'\\/|':z+b+'|');
return o;}

```

Try me online.

* Saved 4 bytes pulling `\n|` into a variable `z`
* Saved 3 bytes pulling `r(' ',e)` into `y` every loop

I'm not too happy with my performance here, especially the implicit check I had to do to get the i=1 output working, but oh well.

# Answer
> 2 votes
# Vyxal `o`, 37 bytes

```
\_*:£ðpm,ċ[ɽ‹\\꘍ṫ\_+J↲¥J\|vpvøṀ⁋|‛|\m

```

Try it Online!

```
\_*                                   # <input> copies of _
   :£                                 # Duplicate and set gregister
     ðpm,                             # Prepend a space and print mirrored
         ċ[                     |‛|\m # If it's 1, print `|\/|`, else:
           ɽ‹                         # 0...n-1
             \\꘍                      # For each, prepend that many spaces to an underscore
                ṫ   J                 # To the last...
                 \_+                  # Append an underscore
                     ↲                # Pad all of that to length n
                      ¥J              # Append the underscores that we stored in the register earlier
                        \|vp          # Prepend a | to each
                            vøṀ⁋      # Mirror and print

```

# Answer
> 1 votes
# Perl 5 \+ `-M5.10.0 -a`, 98 bytes

```
say$".__ x$_,map{'
|',/@F/*($#a=$_-1)?__ x$_.'|':"@a\\".($_<"@F"-1?'  ':__)x("@F"-$_)."/@a|"}1..$_
```

Try it online!

Currently on mobile (in a rainy field!) so I'll add an explanation later!

# Answer
> 1 votes
# 05AB1E, 68 bytes

```
ð'_IиJJÂJUX,I<F'|ðNи'\N>I<Qi'_ëð}IN-<·и'/ðNи'|JJ,}I2‹i"|\/|"ëXð'|:},

```

Try it online!

Explanation:

```
ð              Push space
'_Iи           Push I underscores (I = input)
JJÂJ           Push reverse of that
UX,            Put that in X and print it
I<F            Loop from 1 to N-1 (N = index)
  '|           Push '|' (pipe)
  ðNи          Push N spaces
  '\           Push '\' (backslash)
  N>I<Qi'_     If N+1 == I-1, push _ (underscore)
    ëð}        Otherwise push space
  IN-<·и       Pop and repeat that by (I-N-1)*2
  '/           Push '/' (slash)
  ðNи          Push N spaces
  '|           Push '|' (pipe)
  JJ,          Join and print
}
I2‹i"|\/|"     If I == 1, push '|\/|'
  ëXð'|:}      Otherwise, push X with spaces replaced with pipes
,              Print

```

---
Tags: code-golf, ascii-art
---


title: Can you Golf Golf?

text:
# Question
Title: Can you Golf Golf?
You are required to generate a random 18-hole golf course.

Example output:

```
[3 4 3 5 5 4 4 4 5 3 3 4 4 3 4 5 5 4]

```

Rules:

* Your program must output a list of hole lengths for exactly 18 holes
* Each hole must have a length of 3, 4 or 5
* The hole lengths must add up to 72 for the entire course
* Your program must be able to produce every possible hole configuration with some non-zero-probability (the probabilities of each configuration need not be equal, but feel free to claim extra kudos if this is the case)

# Answer
# k (~~18 17~~ 16 chars)

Back to the original approach, credit to CS for the improvement.

```
(+/4-){3+18?3}/0

```

Other approach (17 chars), same method as the J solution, H/T to CS

```
4+a,-a:9?2 -18?18

```

~~Old version:~~

~~```
(72-+/){18?3+!3}/0

```~~

Not susceptible to stack-overflow and runs in fixed amount of space.
> 29 votes

# Answer
# K, 28

```
{$[72=+/s:18?3 4 5;s;.z.s`]}

```
> 17 votes

# Answer
## J, 20 18 17 characters

```
(?~18){4+(,-)?9#2

```

This works in the same way as the previous answer except that the 9 random digits are either 0 or 1 and are negated before being appended. This means there are as many `-1`s as there are `1`s. Adding 4 gives me a list of `3`s, `4`s and `5`s that add up to 72 every time.

Previous answer:

```
({~?~@#)3+(,2-])?9#3

```

Generates the first 9 holes randomly `?9#3`, then copies and inverts them `(,2-])` (turns a 3 into a 5 and a 5 into a 3) to generate the final 9. This guarantees that the total will be 72 (since every 3 will have a matching 5 the average total per hole will be 4 and 4x18=72). It then randomly shuffles the result `({~?~@#)` to ensure that every combination is possible.
> 15 votes

# Answer
# Mathematica 71 68 66 60

With 6 chars saved by Tally's suggestion.

```
RandomSample@RandomChoice@IntegerPartitions[72, {18}, {3, 4, 5}]

```

> {5, 4, 3, 3, 5, 3, 5, 5, 3, 3, 4, 5, 3, 5, 4, 4, 5, 3}

All possible outcomes are possible, but they are not equally likely.

---

**Analysis**

```
IntegerPartitions[72, {18}, {3, 4, 5}]

```

produces all 10 possible partitions (combinations, not permutations) of 72 into 18 elements consisting of 3's, 4's and 5's.

---

`RandomChoice` selects one of those.

`RandomSample` returns a permutation of that choice.
> 13 votes

# Answer
## 16-bit x86 machine code under MS-DOS - 45 bytes

Hexdump:

```
0E5F576A12595188ECE44088C3E44130D8240374F400C4AAE2EF595E80FC2475DFAC0432CD29B020CD29E2F5C3

```

Base64 coded binary:

```
Dl9XahJZUYjs5ECIw+RBMNgkA3T0AMSq4u9ZXoD8JHXfrAQyzSmwIM0p4vXD

```

Actual source code with some comments:

```
 bits 16
 org 0x100

again:
 push cs               ; Save whatever CS we get.
 pop di                ; Use CS:DI as our course buffer..
 push di               ; Save for later use in the print loop
 push 18               ; We need 18 holes for our golf course.
 pop cx                ; ch = 0, cl = 18.
 push cx               ; Save for later use.
 mov ah, ch            ; Zero out ah.
generate_course:
 in al, 0x40           ; Port 0x40 is the 8253 PIT Counter 0.
 mov bl, al            ; Save the first "random" value in bl.
 in al, 0x41           ; Port 0x41 is the 8253 PIT Counter 1.
 xor al, bl            ; Add some more pseudo randomness.
 and al, 3             ; We only need the two lower bits.
 jz generate_course    ; If zero, re-generate a value, since we need only 3, 4, 5 holes.
 add ah, al            ; Sum in ah register.
 stosb                 ; Store in the course buffer.
 loop generate_course  ; Loop for 18 holes.
 pop cx                ; cx = 18.
 pop si                ; si = course buffer.
 cmp ah, 36            ; 72 holes?
 jne again             ; No, re-generate the whole course.

print:                 ; Yup, we have a nice course.
 lodsb                 ; Load the next hole.
 add al, '2'           ; Add ASCII '2' to get '3', '4' or '5'
 int 0x29              ; Undocumented MS-DOS print function.
 mov al, ' '           ; Print a space too for better readability.
 int 0x29              ; Print the character.
 loop print            ; Print the whole course.
 ret                   ; Return to the beginning of the PSP where a INT 0x20 happen to be.

```

Compile with `nasm 18h.asm -o 18h.com` and run under MS-DOS (or Dosbox), or NTVDM from a 32-bit Windows version.

Sample output:

```
4 5 4 5 4 5 3 4 3 4 3 4 4 5 4 3 5 3

```
> 13 votes

# Answer
## R - 41

```
x=0;while(sum(x)!=72)x=sample(3:5,18,T);x

# [1] 5 3 5 3 3 3 3 3 5 4 5 4 5 4 4 5 5 3

```

The algorithm is similar to @sgrieve's.
> 8 votes

# Answer
# JavaScript, ~~66~~ ~~64~~ 61 chars

Heavily inspired by TwoScoopsofPig (PHP) and Joe Tuskan (JS).

~~```
for(a=[s=0];s!=72;)for(s=i=0;i<18;s+=a[i++]=Math.random()*3+3|0);a

```~~ ~~```
for(a=[s=0];s-72;)for(s=i=0;i<18;s+=a[i++]=Math.random()*3+3|0)a

```~~
```
for(a=s=[];s;)for(i=18,s=72;i;s-=a[--i]=Math.random()*3+3|0)a

```
> 8 votes

# Answer
## GolfScript (26 chars)

```
{;0{3rand.3+@@+(}18*])}do`

```

There are some obvious similarities with Ilmari's solution, but also some obvious differences. In particular, I'm exploiting the fact that the average par is 4.
> 8 votes

# Answer
# Python 77

**Code**

```
from numpy.random import*;l=[]
while sum(l)!=72:l=randint(3,6,18)
print l

```

**Output**

```
[3 4 4 5 3 3 3 5 4 4 5 4 5 3 4 4 5 4]

```

The import really kills this solution. It uses numpy to generate a 18 numbers between 3 and 5 and keeps generating lists until the sum of the list equals 72.
> 7 votes

# Answer
## GolfScript, 27 chars

```
{;18{3.rand+}*].{+}*72-}do`

```

Uses the same rejection sampling method as sgrieve's Python solution. Thus, every valid output actually is equally likely.
> 7 votes

# Answer
# Python 2, 70 bytes

```
from random import*
print sample(([3,5]*randint(0,9)+[4]*99)[:18],18)

```
edit:

Here's another one, similar to the solution of sgrieve:

# Python 2, 73 bytes + equal probability

```
from random import*
a=[]
while sum(a)-72:a=sample([3,4,5]*18,18)
print a

```
> 7 votes

# Answer
## Q (25 characters)

Original (27)

```
while[72<>sum a:18?3 4 5];a

```

Sample output

```
4 4 3 3 4 5 4 3 4 5 5 3 5 5 5 4 3 3

```

Slightly shorter (25)

```
{72<>sum x}{x:18?3 4 5}/0

```
> 6 votes

# Answer
**Python, 128 120 116 characters**

```
import random,itertools
random.choice([g for g in itertools.product(*(range(3,6)for l in range(18))) if sum(g)==72])

```

*`import` statements are still length killers (23 characters only to import 2 function in the namespace)*

i hope you do not need the result in a near future, as this code first evaluates all possible solutions before chosing one at random. maybe the slowest solution to this problem.

i do claim extra kudos for equal probability of each configuration...
> 5 votes

# Answer
# Ruby 1.9 (62 chars)

```
a=Array.new(18){[3,4,5].sample}until(a||[]).inject(:+)==72
p a

```

# Rails (55 chars)

In the `$ rails c` REPL (in any Rails folder):

```
a=Array.new(18){[3,4,5].sample}until(a||[]).sum==72
p a

```

*Note: It works with Ruby 1.8 if you use `shuffle[0]` instead of `sample`.*
> 4 votes

# Answer
# PHP - 77 Chars

```
<?while(array_sum($a)!=72){for($i=0;18>$i;){$a[++$i]=rand(3,5);}}print_r($a);

```

Much like sgrieve's solution, this builds a list of 18 holes, checks total par, and either prints it or rejects it and tries again. Oddly enough, our two solutions are the same length.

Rather annoyingly, PHP doesn't offer array functions with any brevity of name. Array\_sum and print\_r are killing me. Suggestions welcome.
> 4 votes

# Answer
# Lisp (~~78~~ 69 chars)

~~(do((c()(mapcar(lambda(x)(+ 3(random 3)))(make-list 18))))((=(apply'+ c)72)c))~~

```
(do((c()(loop repeat 18 collect(+ 3(random 3)))))((=(apply'+ c)72)c))

```

It's rather similar to sgrieve's Python solution.

Start with c as NIL, check for a sum of 72, the `do` "increment function" for c generates a list of 18 numbers between 3 and 5, check for 72 again, lather, rinse, repeat.

It's refreshing to see `do` and `loop` nicely play golf together.
> 4 votes

# Answer
# JavaScript, ~~116~~ ~~99~~ 65 bytes

~~`for(i=0,h=[];i<18;)h[i++]=5;while(h.reduce(function(a,b){return a+b})!=72){i=Math.random()*18|0;h[i]=[3,4,4][i%3]}h;`~~

~~`h=[0];while(h.reduce(function(a,b){return a+b})-72)for(i=0;i<18;h[i++]=[3,4,5][Math.random()*3|0])h`~~

```
while(i%18||(a=[i=s=0]),s+=a[i++]=Math.random()*3+3|0,s-72|i-18)a

```
> 4 votes

# Answer
## C (123 chars) - effort on efficiency

Pipe through wc and it will generate all 44152809 solutions within 10 seconds...

```
char s[19];g(d,t){int i;if(d--){for(i=51,t-=3;i<54;i++,t--)if(t>=3*d&&t<=5*d)s[d]=i,g(d,t);}else puts(s);}main(){g(18,72);}

```

Oh, well - didn't read the question properly - but given we're generating all solutions then picking a random one with equal probability is a scripting exercise :P
> 3 votes

# Answer
# Clojure - 55

```
(shuffle(mapcat #([[4 4][3 5]%](rand-int 2))(range 9)))

```

Quite a fun trick.... exploits the mathematical structure of the problem that there must be exactly as many 3 par holes as 5 par holes.
> 3 votes

# Answer
# Python 83

```
import random as r;x=[]
while sum(x)!=72:x=[r.randint(3,5) for i in 18*[0]]
print x

```

Like sgrieve's solution, but without numpy

**Golfing Adrien Plisson's solution:** 120-\>108 characters

```
import random as r,itertools as i
r.choice([g for g in i.product(*([3,4,5,6]for l in 18*[0]))if sum(g)==72])

```

# MATLAB 53

```
x=[];
while sum(x)~=72
x=3+floor(rand(1,18)*3);
end
x

```

**Output**:

> x = 4 3 4 4 4 4 5 4 4 3 4 4 3 5 3 5 4 5
> 3 votes

# Answer
# Java (61 chars)

```
while(s!=72)for(i=0,s=0;i<18;i++)s+=3+(int)(Math.random()*3);

```

Sample output:

```
5 4 3 4 5 3 4 4 3 5 4 4 4 4 3 4 4 5

```
> 3 votes

# Answer
## CJam, ~~17~~ 14 bytes

CJam is newer than this challenge, but this is not the shortest answer anyway, so that doesn't really matter.

```
Z5]Amr*I4e]mrp

```

Test it here.

To maintain the total of 72, each `3` must be paired with `5`. So here is how it works:

```
Z5]            e# Push [3 5].
   Amr         e# Get a random number between 0 and 9.
      *        e# Repeat the [3 5] array that many times.
       I4e]    e# Pad the array to size 18 with 4s.
           mr  e# Shuffle the array.
             p e# Print it.

```
> 3 votes

# Answer
# C (94 chars)

```
int h[18],s=0,i;
while(s!=72)for(i=s=0;i<18;s+=h[i++]=rand()%3+3);
while(i)printf("%d ",h[--i]);

```

The `s=0` on line 1 may not be required, because what are the chances an uninitialized int will equal 72? I just don't like reading uninitialized values in straight C. Also, this probably requires seeding the `rand()` function.

## output

```
3 3 3 4 5 5 3 3 4 5 5 4 3 4 5 5 5 3

```
> 2 votes

# Answer
# TXR (99 chars)

```
@(bind g@(for((x(gen t(+ 3(rand 3))))y)(t)((pop x))(set y[x 0..18])(if(= [apply + y]72)(return y))))

```

This expression generates an infinite lazy list of random numbers from 3 to 5:

```
(gen t (+ 3(rand 3)))  ;; t means true: while t is true, generate.

```

The rest of the logic is a simple loop which checks whether the first 18 elements of this list add up to 72. If not, it pops an element off and tries again. The `for` loop contains an implicit block called `nil` and so `(return ...)` can be used to terminate the loop and return value.

Note that the 99 character length includes a terminating newline, which is required.
> 2 votes

# Answer
# C# (143 non-whitespace):

```
()=>{
  var n=new Math.Random().Next(10);
  Enumerable.Range(1,18)
    .Select((x,i)=>i<n?3:i>=18-n?5:4)
    .OrderBy(x=>Guid.NewGuid())
    .ForEach(Console.Write);
}

```
> 2 votes

# Answer
## Bash shell script (65 chars)

```
shuf -e `for x in {0..8}
do echo $((r=RANDOM%3+3)) $((8-r))
done`

```

(shuf comes from the GNU coreutils package. Also, thanks Gareth.)
> 2 votes

# Answer
# Haskell, 104 102 98 chars.

```
import System.Random
q l|sum l==72=print l|1>0=main
main=mapM(\_->randomRIO(3::Int,5))[1..18]>>=q

```
> 2 votes

# Answer
## Perl, 74

```
{@c=map{3+int rand 3}(0)x18;$s=0;$s+=$_ for@c;redo unless$s==72}print"@c"

```

Alternative solution:

```
@q=((3,5)x($a=int rand 9),(4,4)x(9-$a));%t=map{(rand,$_)}(0..17);print"@q[@t{sort keys%t}]"

```
> 2 votes

# Answer
## VBA - 117

VBA never wins at golf. :-)

```
Sub a()
Do Until d=72
d=0
c=""
For b=1 To 18
e=Int(3*Rnd()+3)
c=c &" " &e
d=d+e
Next
Loop
MsgBox c
End Sub

```
> 2 votes

# Answer
## APL 12

```
4+{⍵,-⍵}?9⍴2

```

Note that I have the index origin set to 0, meaning arrays start at 0. You can set this with `⎕IO←0`.
> 2 votes

# Answer
# R, 42 bytes

```
a=0;while(sum(a)-72)a=sample(3:5,18,r=T);a

```

`sample`, by default, draws evenly among the possible values (here `3 4 5`). `r=T` stands for `replace=TRUE` and allows sample with replacement.
> 2 votes

# Answer
# Python, 97

Using a different method than the rejection sampling, this picks a random list of indices of random even length and alternates adding and subtracting to the elements at these indices.

```
from random import*;a=[4]*18;d=1
for i in sample(range(18),2*randint(0,9)):a[i]+=d;d=-d
print a

```
> 1 votes

# Answer
# Clojure - 72 chars

`(some #(if(=(apply +%)72)%)(partition 18(repeatedly #(+(rand-int 3)3))))`

Would be much shorter if Clojure didn't have such flowery descriptive function names :-)
> 1 votes

# Answer
# Groovy

**126 chars**

```
def a=[];while(1){(new Random().nextInt(3)!=1&&a.size()<17?a<<3<<5:a<<4);if(a.size()==18)break};Collections.shuffle(a);print a

```

... ooooh, what a waste of chars :)

**110 chars**

```
def a=[];while(a.size()<18){(new Random().next(2)>1&&a.size()<17?a<<3<<5:a<<4)};Collections.shuffle(a);print a

```
> 1 votes

# Answer
**PowerShell - 59**

```
while(($x|measure -s).sum-ne72){$x=1..18|%{3..5|random}};$x

```
> 1 votes

# Answer
## Perl, 59

```
@a=map{3+rand 3|0}1..18 while 72!=eval join'+',@a;print"@a"

```

Not a winner by any means and could probably be improved still...

Array sum method stolen from perlmonks.
> 1 votes

# Answer
# Mathematica, 45 chars

```
NestWhile[{3, 5}~RandomInteger~18 &, {}, Tr@# != 72 &]

```
> 1 votes

# Answer
# Perl 6 (42 bytes)

```
my@a=roll 18,3..5 while 72!= [+] @a;say @a

```

Probably too long to be acceptable, but at least the solution does exist. `roll` rolls the dice containing 3, 4, and 5. This generates numbers until the sum is equal to 72. I believe it can generate any course with equal probability (in theory), but considering pseudo-random number generators, it probably doesn't.

Sample output:

```
~ $ perl6 -e 'my@a=roll 18,3..5 while 72!= [+] @a;say @a'
3 4 3 3 4 5 4 3 4 4 3 4 5 4 5 5 4 5

```
> 1 votes

# Answer
# TI-BASIC, 13 bytes

```
3+3fPart(randIntNoRep(0,17)/3

```

Outputs list of 18 integers. Meets all specs and has equal probability for each case.
> 1 votes

# Answer
# Pyth, 18 bytes

```
#Jm+3O3U18IqsJ72JB

```

## How it works:

```
#                    infinite loop
       U18           generate the list [0, 1, ..., 17]
  m    U18           map every value of this list to
   +3O3              a random number between 3 and 5
 Jm+3O3U18           and assign the resulting list to J
          I          if
           qsJ72     the sum of J == 72
                J    print J
                 B   and exit the loop

```
> 1 votes

# Answer
# CJam, 31

\[Language was created after the question was posted\]

Shamelessly long for CJam. It's basically a brute-force solution that keeps trying random configurations until it finds one that adds to 72.

```
L{;L{3mr3+_U+:U;a+}I*U72=:U!}g`

```
> 1 votes

# Answer
## Java: 389 bytes

Run by calling the `b()` function.

```
import java.util.*;public class a{Random b=new Random();int[]b(){int[]c=new int[18];int d=0;for(int i=0;i<c.length;i++){int e=g(c.length-i,d);int f=h(c.length-i,d);c[i]=i(e,f);d=d+c[i];}
return c;}
int i(int j,int k){return b.nextInt((k-j)+1)+j;}
int g(int l,int m){int n=(l-1)*5;int o=72-m;int p=o-n;return p<3?3:p;}
int h(int q,int r){int s=(q-1)*3;int t=72-r;int u=t-s;return u>5?5:u;}}

```
> 1 votes

# Answer
# Javascript, ~~148~~ 143 bytes

```
t=[];d=0;while(d<18){q=t.reduce(function(a,b){return a+b},z=0);while(!z||q+z+13-d*5<0||q+z-d*3>21)z=3+3*Math.random()|0;t.push(z);d++}alert(t)

```
> 1 votes

# Answer
## PARI/GP, 85 bytes

```
vecextract(Vec(partitions(72,[3,5],[18,18])[random(10)+1]),numtoperm(18,random(18!)))

```

This generates a random partition of 72 with 18 components ranging from 3 to 5. The probabilities are not uniform, from 1/10 for the all-4 vector to 1/171531360 for \[3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5\] and its permutations.
> 1 votes

# Answer
# 05AB1E, 16 bytes

```
[18Lε3LÌΩ}DO₆·Q#

```

Try it online!
> 1 votes

# Answer
# Vyxal, 14 bytes

```
{:ṁ4≠|18ƛ3 6r℅

```

Try it Online!

```
{              # While...
 :ṁ            # The mean of the current value
   4≠          # Isn't 4
     |         # Do...
      18ƛ      # Fill an array of 18 elements with...
         3 6r℅ # one of 3, 4, and 5.

```
> 1 votes

# Answer
# Octave, 37 bytes

```
while sum(x=2+randi(3,1,18))-72;end;x

```

It seems straight forward, (and I guess it is), but there are a few nifty tricks in here. It's 16 bytes shorter than the MATLAB answer, and I think it's hard to golf any further.

In Octave, you can initialize a variable inside a function call, or inside the `while` statement as done here. So, by doing `sum(x=2+randi(3,1,18))` I manage to continuously shuffle a vector of 18 elements with values `[3,4,5]` until the sum is 72. Instead of checking if this equals 72, we can subtract 72, and check if that's a truthy or a falsey value. Any non-zero values are considered truthy, so it will only stop when the sum is 72. In the end, the loop stops and the vector is printed.
> 0 votes

# Answer
## Seriously, 32 bytes (noncompeting)

```
35k9Ju;)@nktd9-τ4nktW;lJ`\`np@WX

```

This language post-dates this challenge. Posted to prove the need for a shuffle command and perhaps a cons command. This uses the same solution as CJam roughly:

```
35k                                 Push [5,3]
   9Ju                              Push a random number n from 1 to 9
      ;)                            Save a copy of it for later use.
        @n                          Make n copies of [5,3]
          (9-τ                      Transform n -> 2*(9-n)
              4n                    Push that many 4's
                kt                  Compile all numbers into a list.
                  W         W       Until the list is empty:
                   ;lJ`\`np@        Pop a random element from it.
                             X      Discard empty list.

```
> 0 votes

# Answer
# AHK, 76 bytes

```
Loop{
s=
t=0
Loop,18{
Random,r,3,5
s:=r " "s
t+=r
}
If t=72
Break
}
Send,%s%

```

It's of the style to just loop forever until it happens to generate a list that totals 72 strokes.
> 0 votes

---
Tags: code-golf, number, random
---