title: Carve some ASCII jewels!

text:
# Question
Title: Carve some ASCII jewels!
March 13 is recognized as National Jewel Day, which is the theme of this challenge. So, given an integer `n` where `n` is greater than 0, create an ASCII jewel. For example:

```
n = 1          n = 2             n = 3
                                       ______
                     ____             /      \
 __                 /    \            \      /
/  \                \    /             \    /
\  /                 \  /               \  /
 \/                   \/                 \/

```

The bottom is defined as the very bottom of the jewel to the highest pair of of `\/`. The rest is the top. For the above example where `n = 1`:

```
Bottom: \  /    Top:   __
         \/           /  \

```

As you can see, the bottom is made of `n + 1` layers of `\/` with `(1 * lines from the bottom) * 2` spaces in between with a maximum of `n` lines from the bottom of the jewel. If we take the second jewel (`n = 2`), we can see that:

```
 ____
/    \
\    /  2 (or n) layers from the bottom with 1*2*2 or 4 spaces in between \/
 \  /   1 layer from the bottom with 1*1*2 or 2 spaces in between \/
  \/    The bottom (0 layers) with 1*0*2 spaces or 0 spaces in between \/

```

The top is made of one pair of `/\` with `n*2` spaces in between with `n*2` underscores on top.

**Rules**

* Must be able to take in any nonzero positive integers as user input
* Must create a jewel with the specs defined above (restated here):
    + The top is made of one pair of `/\` with `n*2` spaces in between with `n*2` underscores on top.
    + The bottom is made of `n + 1` layers of `\/` with `(1 * lines from the bottom) * 2` spaces in between with a maximum of `n` lines from the bottom of the jewel.
* Trailing newlines after the jewel, or trailing spaces on each line are allowed.
* No standard loopholes allowed

**Winning Criteria**

Least bytes wins!

# Answer
# Charcoal, 17 bytes

Code:

```
ＮβＧ←β_↙↙¹→↘⁺β¹‖Ｍ→

```

Explanation:

```
Ｎβ                      # Place the input into β
   Ｇ←β_                 # Draw a line of length β with _ as the filling character
        ↙                # Move the cursor one down and one left
         ↙¹              # Draw a line from the cursor position to one position ↙
           →             # Move the cursor 1 to the right
             ⁺β¹         # Add one to the input and..
            ↘            # Create a line pointing ↘, with the size calculated above
                ‖Ｍ→     # Mirror to the right

```

A *very neat* command is `‖Ｍ`, which also automatically mirrors `/` into `\`.

Uses the **Charcoal** encoding.

Try it online!
> 27 votes

# Answer
# Python 2, 101 98 95 bytes

```
lambda n:'\n'.join([' '+'__'*n,'/'+'  '*n+'\\']+[' '*i+'\\'+'  '*(n-i)+'/'for i in range(n+1)])

```

Try it Online!

Anonymous function that takes in a positive integer and returns a string

# Python 3.6, 92 bytes (Thanks to Ben Frankel)

```
lambda n:f' {"__"*n}\n/{"  "*n}\\\n'+'\n'.join(' '*i+'\\'+'  '*(n-i)+'/'for i in range(n+1))

```

I couldn't find an online interpreter for this version, but it is a bit shorter due to f-strings in v3.6
> 8 votes

# Answer
# 05AB1E, ~~27~~ 20 bytes

```
ƒN·ð×…\ÿ/}Â¹·'_×)R.c

```

Try it online!

**Explanation**

```
ƒ                      # for N in range[0 ... n]
 N·ð×                  # push N*2 spaces
     …\ÿ/              # push the string "\ÿ/" with "ÿ" replaced by the spaces
         }             # end loop
          Â            # push a reversed copy of the top of the stack
                       # (the largest row of the bottom of the diamond)
           ¹·'_×       # push input*2 underscores
                )      # wrap the stack in a list
                 R     # reverse the list
                  .c   # join the list on newlines, padding each row to equal length

```
> 8 votes

# Answer
# PHP, 123 Bytes

```
echo($s=str_pad)(" ",$z=1+2*$a=$argv[1],_).$s("\n/",$z+1," ")."\\\n";for($i=0;$i<=$a;)echo$s($s("",$i)."\\",$z-$i++)."/\n";

```

## 143 Bytes first version

```
for(;$i<3+$a=$argv[1];$i++)echo 1-$i?str_pad("",$i?$i-2:1):"/",str_pad($i>1?"\\":"",$i<2?2*$a:2*($a-$i+2)+1,$i?" ":_),$i<2?$i?"\\":"":"/","\n";

```

Try it here!
> 7 votes

# Answer
# , ~~28~~ ~~27~~ 26 bytes

*1 bytes saved thanks to @DJMcMayhem by using `>` instead of `É`*

```
Ài__<esc>É ÙÒ r/Á\Ùr\$r/òÙlxx>

```

`<esc>` is `0x1b`

Try it online!

Hexdump:

```
00000000: c069 5f5f 1bc9 20d9 d220 722f c15c d972  .i__.. .. r/.\.r
00000010: 5c24 722f f2d9 6c78 783e                 \$r/..lxx>

```

### Explanation

Top:

```
Ài__<esc>              " Write argument times __
É<space>               " Prepend a space to the line
Ù                      " Duplicate line below cursor, cursor also moves down
Ò<space>               " Replace every character with a space
r/                     " Change the first character in the line to a /
Á\                     " Append a \ to the end of the line

```

Bottom:

```
Ù                      " Duplicate
r\                     " Change the first character in the line to a \
$r/                    " Replace the last character with a /
ò                      " Until a breaking error occurs do:
  Ù                    "  Duplicate
  lxx                  "  Remove 2 middle characters (spaces)
  >                    "  Indent by one space (implicit ending >)
                       " Implicit ending ò

```
> 6 votes

# Answer
# Röda, 71 bytes

```
f n{a=" ";[a,"__"*n,"
/",a*2*n,`\
`];seq n,0|[a*(n-_),`\`,a*2*_1,"/
"]}

```

Try it online!
> 5 votes

# Answer
## JavaScript (ES6), 80 bytes

```
f=
n=>` ${"_".repeat(n*2)}
/${s=" ".repeat(n)}${s}\\`+s.replace(/|/g,"\n$`\\$'$'/")
```

```
<input type=number oninput=o.textContent=f(this.value)><pre id=o>
```
> 5 votes

# Answer
# C, 131 bytes

```
i;f(n){for(printf(" ",i=0);i++<n*2;)printf("_");for(printf("\n/%*c\n",n*2+1,92,i=0);i++<n+1;)printf("%*c%*c\n",i,92,(n-i)*2+3,47);}

```

Try it online!
> 4 votes

# Answer
# Python 3, ~~107~~ 105 Bytes

```
n,s=int(input())," "
print(s+n*"__","/"+n*2*s+"\\",*[i*s+"\\"+2*(n-i)*s+"/"for i in range(n+1)],sep="\n")

```

Takes an int from Stdin
> 3 votes

# Answer
# MATL, 34 bytes

```
QE:qgOO(t~E3O(GQXy3*tPgEhv'_/\ 'w)

```

Try it at MATL Online!

### Explanation

```
QE:qg   % Create array [0 1 1 ... 1 1] of size2*(n+1)
OO(     % Turns last 1 into a 0: [0 1 1 ... 1 0]
t~      % Duplicate and negate: [1 0 0 ... 0 1]
E3O(    % Multiply by 2, turn last 2 into 3: [2 0 0 ... 0 3]
GQXy    % Push identity matrix of size n+1
3*      % Multiply by 3
tPgE    % Duplicate, flip, turn 3 into 2
h       % Concatenate the two matrices horizontally
v       % Concatenate all arrays vertically into a matrix
'_/\ '  % Push this string
w)      % Index (modular, 1-based) with the matrix into the string. Implicitly display

```
> 3 votes

# Answer
# PowerShell, 76, 74 bytes

```
param($n)" "+'_'*2*$n;"/$(' '*$n*2)\";$n..0|%{' '*($n-$_)+"\$(' '*$_*2)/"}

```

Note: the online example contains a bit of wrapping as a demonstration. Place in a PoSH function or script to execute.

Try it online!
> 3 votes

# Answer
# Pyth, 44 Bytes

```
+" "*Q"__"++\/**2Qd\\jm+++*d\ \\**2-Qd\ \/hQ

```

try it!

### explanation

The code consists of 3 parts:

```
+" "*Q"__"               # pretty straightforward " "+input()*"__"
++\/**2Qd\\              # d is defined as " ":  "/"+2*input()*d+"\"
jm+++*d\ \\**2-Qd\ \/hQ  # The third part is a bit more complex so I'll explain it further:

jm                   hQ  # Map some lambda function onto range(input()+1) and join the result on newlines
  +++*d\ \\**2-Qd\ \/    # Here d is the lambda argument (so I can't use it for spaces -.-)
  +++*d\ \\**2-Qd\ \/    # In Python: d*" "+"\\"+2*(Q-d)*" "+"/"

```
> 2 votes

# Answer
# Python3, 104 bytes

```
n=int(input());print(" "+"__"*n+"\n/"+"  "*n+"\\")
for i in range(n+1):print(" "*i+"\\"+"  "*(n-i)+"/")

```

The program takes an integer from STDIN and returns the jewel into STDOUT.
> 2 votes

# Answer
## Batch, 152 bytes

```
@set s=
@for /l %%i in (1,1,%1)do @call set s=  %%s%%
@echo  %s: =_%
@echo /%s%\
@set s=\%s%/
:l
@echo %s%
@if %s:~-2%==/ set s=%s:\  = \%&goto l

```

Tests:

```
n = 1
 __
/  \
\  /
 \/

n = 2
 ____
/    \
\    /
 \  /
  \/

n = 3
 ______
/      \
\      /
 \    /
  \  /
   \/

```
> 2 votes

# Answer
# Pip, 43 bytes

42 bytes of code, +1 for `-n` flag.

```
Ps.'_Xa*2P"/\"JsXa*2sX_.'\.sXa-_X2.'/M,a+1

```

Takes input as a command-line argument. Try it online!

### Explanation

Constructs the first two lines separately, then the rest of the jewel with a map operation:

```
Ps.'_Xa*2
      a*2  Cmdline arg, times 2
   '_X     That many underscore characters
 s.        Concatenated to a space character
P          Print (with newline)

P"/\"JsXa*2
        a*2  Cmdline arg, times 2
      sX     That many space characters
 "/\"J       Join the string "/\" with the above as the separator
P            Print (with newline)

sX_.'\.sXa-_X2.'/M,a+1
                  ,a+1  Numbers from 0 up to and including a
                 M      Map the following lambda function:
sX_                      Space, repeated (fn arg) times
   .'\                   Concatenate \
      .                  Concatenate:
       sXa-_              Space, repeated (a - (fn arg)) times
            X2            repeated twice
              .'/        Concatenate /
                         Print result list, newline separated (implicit, -n flag)

```

### Another solution

Also 42+1 bytes, this time with the `-l` flag:

```
Ys.tAL'_.sX2+,a.0(yALRVyRXD1-_)R0'\R1'/ZDs

```

TIO
> 2 votes

# Answer
# Pyth, 38 bytes

```
j[*yQ\_j*yQpd"/\\"jm+*\ dj*\ y-Qd"\/"h

```
> 2 votes

# Answer
# C, 115 bytes

```
#define p printf(
i;j;f(n){for(p" ");i++<n;p"__"));for(p"\n/%*c",2*n+1,92);j<=n;p"\n%*c%*c",++j,92,n*2-j*2+3,47));}

```

Try it online!

# C, 123 bytes

Though the challenge doesn't require it, at the expense of 8 bytes the function can be made reusable (the first solution saves 8 bytes by relying on the implicit initialization of global variables).

```
#define p printf(
i;f(n){for(i=0,p" ");i++<n;p"__"));for(i=0,p"\n/%*c\n",2*n+1,92);i<=n;p"%*c%*c\n",++i,92,n*2-i*2+3,47));}

```

Try it online!
> 2 votes

# Answer
**C#, 187 bytes**

I'm sure there is a more compact solution out there but this is my first attempt:

```
var a=" "+new string('_',2*n)+"\n/"+new string(' ',2*n)+"\\\n";for(int i=n;i>0;i--){a+=new string(' ',n-i)+"\\"+new string(' ',2*i)+"/\n";}a+=new string(' ',n)+"\\/";Console.Write(a);

```

Try it online..
> 2 votes

# Answer
## JavaScript (ES6), 93 bytes

```
n=>(` 0
/2\\`+`
1\\4/`.repeat(k=++n)).replace(/\d/g,c=>' _'[+!+c].repeat(c&1?k-n-2:+c+--n*2))

```

### Demo

```
let f =

n=>(` 0
/2\\`+`
1\\4/`.repeat(k=++n)).replace(/\d/g,c=>' _'[+!+c].repeat(c&1?k-n-2:+c+--n*2))

console.log(f(1))
console.log(f(2))
console.log(f(3))
```
> 1 votes

# Answer
# dc, 121 bytes

```
?d1+sa2*sb32P[0sq[lvPlq1+dsqlj>h]shlj0<h]srlbsj95svlrx2607Plbsj32svlrx[\]p0sd[ldsjlrx92Plbsjlrxlb2-sb[/]pld1+dsdla>k]dskx

```

Try it online!
> 1 votes

# Answer
# Perl 5 109 94 + 1 (for flag -p) = 95 Bytes

Try it Online!

```
$l=$_*2;$s=" "."_"x$l."\n/"." "x$l."\\\n";$s.=" "x$_."\\"." "x($l-$_*2)."/\n"for 0..$_;print$s

```

Can be run like so:

```
perl -p <name of file> <<< n

```

**Ungolfed**

```
$l=$_*2;
$s=" "."_"x$l."\n/"." "x$l."\\\n";
$s.=" "x$_."\\"." "x($l-$_*2)."/\n"for 0..$_;
print$s

```

**Explanation**

```
#Sets $l to twice the value of the input 'n'
$l=$_*2;

#Top 2 rows of jewel adding $l underscores then newline
#followed by '/' and $l spaces.  The '\\\n' is an escaped '\' and a newline
$s=" "."_"x$l."\n/"." "x$l."\\\n";

#The meat of the jewel generation.  It contains a for-loop
#that iterates from 0 to $_ (the input value 'n')
#The loop uses its iterator value ($_ (which overrides the outer $_))
#to determine how many leading spaces it needs to apply.
#Then it adds a '\' with '\\' followed by $l-$_*2 number of spaces
#(the inside of the jewel).  Again, while under the umbrella of the for-loop,
#the $_ refers to the iterator value of the for-loop.
#After the inner spaces, it goes on to add in the '/' and a new line
$s.=" "x$_."\\"." "x($l-$_*2)."/\n"for 0..$_;

#Lastly, it prints the compiled Scalar value $s.  (In Perl, Strings are Scalar values or references
print$s

```
> 1 votes

# Answer
# Vyxal, 29 bytes

```
ð₴d\_*,\/₴d\\꘍,›(n\\꘍₴nεd\/꘍,

```

Try it Online!

```
=== The top ===
ð₴d\_*,
ð       # ' '
 ₴      # Print without newline
  d     # (implicit input) doubled
   \_*  # That many underscores
      , # Output with newline
=== Line 2 ===
\/₴d\\꘍,
\/       # Forward slash
  ₴      # Print without newline
   d     # (implicit input) doubled
    \\꘍  # That many spaces, plus a backslash
       , # Output with newline
=== The rest ===
›(             # (implicit input) incremented times do...
  n            # Iteration number...
   \\꘍         # ...spaces plus a backslash
      ₴        # Print without newline
       nε      # Difference of iteration number and (implicit input)
         d.    # Doubled
          \/꘍  # That many spaces, plus a forward slash
             , # Output with newline

```
> 1 votes

# Answer
# Canvas, 12 bytes

```
_× ；＋/∔⁸╵＼∔║

```

Try it here!

right tool for the job.
> 1 votes

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


title: How much will this cost?

text:
# Question
Title: How much will this cost?
Given *N* items (0 \< *N* \<= 50) with prices (which are always integers) *P0* ... *PN-1* and given amounts of each item *A0* ... *AN-1*, determine how much the total cost will be.

### Examples

*N*: 2
*P0*: 2
*P1*: 3
*A0*: 1
*A1*: 4
Result: 14

*N*: 5
*P0*: 2
*P1*: 7
*P2*: 5
*P3*: 1
*P4*: 9
*A0*: 1
*A1*: 2
*A2*: 3
*A3*: 2
*A4*: 3
Result: 60

Remember, this is , so the code with the smallest number of bytes wins.

### Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=95128,OVERRIDE_USER=12537;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
# Actually, 1 byte

```
*

```

Try it online!

Okay, this is the shortest dot product built-in I could find. \>\_\>
> 7 votes

# Answer
# Jelly, 2 bytes

```
æ.

```

Try it online!

A built-in computing the dot product between two input vectors: if, for each **1 ≤ i ≤ n**, we buy **ai** items worth **pi** each, the formula for the total cost is **a1p1 \+ a2p2 \+ … +anpn**, which is precisely the definition of the dot product.
> 5 votes

# Answer
# Mathematica, 1 byte

```
.

```

# Usage:

```
{1, 2, 3}.{4, 5, 6}

(* 32 *)

```
> 4 votes

# Answer
# TI-Basic, 12 bytes

```
Prompt L1,L2
sum(L1L2

```
> 4 votes

# Answer
## Haskell, 17 bytes

```
(sum.).zipWith(*)

```

Multiply the lists entrywise, then sum. Shorter than importing (23 bytes)

```
import Data.Vector
vdot

```
> 3 votes

# Answer
# Python, ~~36~~ 33 bytes

```
lambda*x:sum(map(int.__mul__,*x))

```

*Thanks to @xnor for golfing off 3 bytes!*

Test it on Ideone.
> 3 votes

# Answer
# Ruby, ~~34~~ 23 + 9 = 32 bytes

+9 bytes for `-rmatrix` flag.

```
->p,a{Vector[*p].dot a}

```

See it on eval.in: https://eval.in/653676
> 2 votes

# Answer
# Pyth, 3 bytes

```
s*V

```

(s)ums the (V)ectorized (\*)product of the two input arrays.
> 2 votes

# Answer
# MATLAB / Octave, 4 bytes

```
@dot

```

This defines an anonymous function.

Try it at Ideone.
> 2 votes

# Answer
# R, ~~8~~ 18 bytes

```
sum(scan()*scan())

```

Now takes input from stdin.
> 2 votes

# Answer
# C#, 25 bytes

```
p.Zip(a,(x,y)=>x*y).Sum()

```

Sample program:

```
using System.Linq;
using Xunit;
public class Tests {
    [Fact]
    public void Cost() {
        int[] p = new [] { 2, 7, 5, 1, 9 };
        int[] a = new [] { 1, 2, 3, 2, 3 };
        int r = p.Zip(a, (x, y) => x * y).Sum();
        Assert.Equal(60, r);
    }
}

```
> 2 votes

# Answer
# Julia 1.0, 13 bytes

Building up on Donat's solution. Thanks to Chartz Belatedly for pointing out the issue with inputs

```
x/y=sum(x.*y)

```

Try it online!
> 2 votes

# Answer
# MATL, 2 bytes

```
*s

```

Try it online!

```
*     % Element-wise product of two implicit inputs
s     % Sum of array, implicitly displayed

```
> 1 votes

# Answer
# Java, 67 bytes

```
a->{int p=0;for(int i=-1;++i<a[0];)p+=a[i+1]*a[i+a[0]+1];return p;}

```

Slightly ungolfed:

```
public static int pay(int...a){
  int p=0;
  for(int i=-1;++i<a[0];){
    p+=a[i+1]*a[i+a[0]+1];
  }
  return p;
}

```
> 1 votes

# Answer
# Perl 6, 13 bytes

```
{[+] [Z*] $_}

```

Input is a list of two lists

## Example:

```
say {[+] [Z*] $_}(  ((2,7,5,1,9),(1,2,3,2,3))  );
# 60

```

## Explanation:

```
{          # bare block lambda with implicit parameter ｢$_｣

  [+]      # reduce using addition operator

    [Z*]   # reduce using zip meta-operator combined with multiplication operator

      $_   # the argument ( list of lists )
}

```
> 1 votes

# Answer
# TI-BASIC, 3 tokens

```
sum(L₁L₂

```

Input in `L₁` and `L₂`, output in `Ans`.

Usage:

```
{1,2,3→L1
{4,5,6→L2
prgmCOST

```

Output: `32`
> 1 votes

# Answer
# 05AB1E, 3 bytes

```
øPO

```

Try it online!

```
øPO  # full program
  O  # sum of...
 P   # products of...
     # (implicit) each element in...
     # implicit input...
ø    # with each element from the first sublist paired with the corresponding element from the second sublist
     # implicit output

```
> 1 votes

# Answer
# , 5 bytes

```
`%*%`

```

Try it online!

That's the dot-product built-in in R...
> 1 votes

# Answer
# JavaScript, 33 bytes

```
a=>b=>a.reduce((c,d,e)=>c+d*b[e])

```

Takes input as `([p[0],...,p[n-1])([a[0],...,a[n-1]])`.
> 1 votes

# Answer
# C, ~~58~~ 56 bytes

```
f(n,p,a,s)int*p,*a;{for(s=0;n;s+=p[--n]*a[n]);return s;}

```

Input is n: number of elements, p:array 1, a:array 2.

Somewhat un-golfed:

```
f(n,p,a,s)
    int*p,*a;
{
    for(s=0;n;s+=p[--n]*a[n]);
    return s;
}

```
> 1 votes

# Answer
# APL (Dyalog Classic), 3 bytes

```
+.×  ⍝ My code is self-documenting

```

Try it online!
> 1 votes

# Answer
# Vyxal `s`, 1 byte

```
*

```

Try it Online!

Magic.
> 1 votes

# Answer
# PHP, 46 Bytes

```
<?foreach($_GET[a]as$n)$s+=$n[0]*$n[1];echo$s;

```

48 Bytes

```
<?=array_sum(array_map(array_product,$_GET[a]));

```
> 0 votes

# Answer
# Zsh, ~~31~~ 25 bytes

Try It Online. ~~old 31 bytes~~

```
for i ($p)((S+=i*a[++j]))

```

This is the core function. The challenge didn't say anything about setting up variables or output so that's all external.
> 0 votes

# Answer
# Julia 1.0, 14 bytes

```
sum((*).(x,y))

```

Try it online!
> 0 votes

# Answer
# PowerShell, 43 bytes

```
function d($a,$b){$a|%{$r+=$_*$b[$i++]};$r}

```

Try it online!

Basically, just calculate the dot product.
> 0 votes

# Answer
# PowerShell, 36 bytes

```
param($p,$q)$p|%{$r+=$_*$q[$i++]}
$r

```

Try it online!
> 0 votes

# Answer
# BQN, 3 bytes

```
+´×

```

Try it!

dot product
> 0 votes

---
Tags: code-golf, math, number
---


# Question
Title: Convert Algebraic notation to Descriptive notation
Mr Short likes to play chess. Mr Short is also a very traditional man. Hence, Mr Short is disturbed by the recent trend of using Algebraic notation in modern chess, and he would rather use Descriptive notation, like his father and his father's father before him.

# Note

To simplify this challenge, I chose not to deal with disambiguaties (as in, when two pieces can move to the same square, or can capture the same piece.) Also there is no dealing with en passant, promotion, or Castling.

# Algebraic notation for the uninitiated

* The board squares are numbered from `a1` at the bottom left to `h8` as the top right. The letters represent the files (columns) while the numbers represent the ranks (rows). The white King is placed in the beginning of the game at the square `e1`.
* A move consists of the piece that moved + the destination square. For example, a King moving to `e2` would be `Ke2`.
* If the piece that had moved is a Pawn, the piece letter is omitted. For example, the starting move Pawn to `e4` is written as `e4`.
* If the move is a capture, then the `x` letter is inserted between the piece and the destination square. For example, a Queen capturing at `f7` is annotated as `Qxf7`.
* If the capturing piece is a Pawn, since it moves diagonally, the notation records the file the Pawn originated from. For example, when the Pawn at `c4` captures a piece at `d5`, the move is annotated as `cxd5`.
* Piece symbols are `K` for King, `Q` for Queen, `B` for Bishop, `N` for Knight, and `R` for Rook. Pawns have no symbols.
* Other annotations include `+` for check, and `#` for checkmate. A Pawn moving to f7 and giving check is `f7+`. Note lack of space.

# Descriptive notation for the uninitiated

* The files are described by the piece that starts on it. For example, what would be the `e` file in Algebraic, becomes the King file, or, for short, `K`. The other files are marked by their side, then the piece. So file `h` is the King's Rook's file, or `KR`.
* The ranks are numbered from the point of view of the moving player. What would be the fourth rank in Algebraic, is the fourth rank for white, but the *fifth* rank for black.
* It follows that the square `e4` is `K4` for the white player and `K5` for the black player. The square `f7` is `KB7` for the white player and `KB2` for the black player.
* A move is annotated by the piece moving, then a dash, then the target square. So a Pawn moving to `K4` is `P-K4`. A Queen moving to `KR5` is `Q-KR5`.
* A capture is annotated by the capturing piece, then `x`, then the captured piece. Therefore a Bishop capturing a Pawn is `BxP`. **Usually you need to mark *which* Pawn is being captured, but ignore this for sake of simplicity.**
* Piece symbols are `K` for King, `Q` for Queen, `B` for Bishop, `Kt` for Knight (note the different symbol), `R` for Rook, and `P` for Pawn.
* Other annotations include `ch` for check and `mate` for checkmate. A Pawn moving to `KB7` and giving check is `P-KB7 ch`. Note the space.

# Input

A string of algebraic notation moves, delineated by spaces. There are no move numbers. For example, the Fool's mate goes like this:

```
f3 e5 g4 Qh4#

```

Or the game Teed vs Delmar, from the same Wikipedia page:

```
d4 f5 Bg5 h6 Bf4 g5 Bg3 f4 e3 h5 Bd3 Rh6 Qxh5+ Rxh5 Bg6#

```

The Immortal game.

```
e4 e5 f4 exf4 Bc4 Qh4+ Kf1 b5 Bxb5 Nf6 Nf3 Qh6 d3 Nh5 Nh4 Qg5 Nf5 c6 g4 Nf6 Rg1 cxb5 h4 Qg6 h5 Qg5 Qf3 Ng8 Bxf4 Qf6 Nc3 Bc5 Nd5 Qxb2 Bd6 Bxg1 e5 Qxa1+ Ke2 Na6 Nxg7+ Kd8 Qf6+ Nxf6 Be7#

```

You may assume that input is always a valid game. All moves are in the correct order, and no extraneous data is present. **No moves will include disambiguation**.

For example, The Evergreen game despite being, obviously, a valid game, is not going to be input due to the 19th move, `Rad1`.

You may also assume that all input move lists start from the starting position.

# Output

A move list, with a similar format, in Descriptive notation.

For example, the Fool's mate:

```
P-KB3 P-K4 P-KKt4 Q-KR5 mate

```

Teed vs Delmar:

```
P-Q4 P-KB4 B-KKt5 P-KR3 B-KB4 P-KKt4 B-KKt3 P-KB5 P-K3 P-KR4 B-Q3 R-KR3 QxP ch RxQ B-KKt6 mate

```

The Immortal Game:

```
P-K4 P-K4 P-KB4 PxP B-QB4 Q-KR5 ch K-KB1 P-QKt4 BxP Kt-KB3 Kt-KB3 Q-KR3 P-Q3 Kt-KR4 Kt-KR4 Q-KKt4 Kt-KB5 P-QB3 P-KKt4 Kt-KB4 R-KKt1 PxB P-KR4 Q-KKt3 P-KR5 Q-KKt4 Q-KB3 Kt-KKt1 BxP Q-KB3 Kt-QB3 B-QB4 Kt-Q5 QxP B-Q6 BxR P-K5 QxR ch K-K2 Kt-QR3 KtxP ch K-Q1 Q-KB6 ch KtxQ B-K7 mate

```

This is not the simplest Descriptive notation possible, since sometimes you don't need to specify which Knight file was moved to (as in, `Q-KKt4` could be written as `Q-Kt4` since the move `Q-QKt4` is impossible.) The move `BxP` is ambiguous (which pawn: should be `BxQKtP`), but Mr Short doesn't care about that too much.

You may consider these your test cases.

Note: I wrote these by hand. If you catch any glaring mistakes, please let me know.

# Rules and Scoring

* Standard rules apply : program with output to stdout, or function. Nothing to stderr. Standard loopholes are forbidden.
* Please link to a site where we can test your code.
* Code golf: shortest code wins.

# In Conclusion

This is my first challenge, so I *probably* made some noobish errors. Feedback on the question (in the comments, obviously) is appreciated.

# Answer
> 4 votes
## Batch, 588 bytes

```
@echo off
for %%r in (a.R b.Kt c.B d.Q e.K f.B g.Kt h.R)do set %%~nr1=%%~xr&set %%~nr8=%%~xr
for %%r in (a b c d e f g h)do set %%r2=.P&set %%r7=.P
set s=
set a=
:l
set m=%1
set c=
for %%r in (ch.+ mate.#) do if .%m:~-1%==%%~xr set c= %%~nr&set m=%m:~,-1%
set/ab=(a^^%m:~-1%-1)+1,a=7-a
set p=%m:~0,1%
for %%r in (a b c d e f g h)do if %p%==%%r set p=P
for %%r in (QR.a QKt.b QB.c Q.d K.e KB.f KKt.g KR.h)do if .%m:~-2,1%==%%~xr set d=-%%~nr%b%
if %m:~-3,1%==x call set d=x%%%m:~-2%:~1%%
set %m:~-2%=.%p:N=Kt%
set s=%s% %p:N=Kt%%d%%c%
shift
if not "%1"=="" goto l
echo%s%

```

`s` is the output string. `m` is the current move (moves are taken as command-line parameters). `a` is the current player (0 for White, 7 for Black). `b` is the row as seen from the point of view of the current player. `c` is the `ch` or `mate` flag. `p` is the current piece. If there is no piece (i.e. a lowercase letter `a-h`) then `P` is substituted. (The `N` to `Kt` substitution is done later to save bytes.) The destination column is then looked up in a dictionary. However if the move is actually a capture then the destination becomes an `x` followed by the piece previously on that square. Either way the destination square is then set to the piece that just moved there. The moves are accumulated until there are no more parameters and then they are printed.

The variables `a1`...`h8` are used to store the last seen piece. The `.` prefix is there because of the way I initialise the back row; it's hard to loop over two variables at once in Batch unless I'm allowed to begin one with a `.`.

# Answer
> 1 votes
# JavaScript (Node.js), 473 bytes

```
(n,c=(X=>[...'abcdefgh'].map(a=>[...'12345678'].map(b=>X[a+b]=a<'c'|a>'f'?a<'b'|a>'g'?['R','Kt',...'BQKB','Kt','R'][--b]:'P':''))&&X)({}),g=s=>s?s=='N'?'Kt':s:'P')=>n.split` `.map((e,i)=>(Q=c[S=e.slice(I=e.search(/[a-h](?!x)/),I+2)],((c[S]=g(e.split(/[a-hx]/)[0]))+(e[Z='includes']`x`?'x'+Q:'-'+((S=e[I])>'d'?'K'+['','B','Kt','R']['efgh'.indexOf(S)]:'Q'+['R','Kt','B','']['abcd'.indexOf(S)])+((Y=e[e.search(/\d/)])&&i%2?9-Y:Y))))+(e[Z]`#`?' mate':e[Z]`+`?' ch':'')).join` `

```

Try it online!

Output is different to the testcase, but it seems like there is an error the OP made. Only 1 mistake, though.

## How

Quite simple for such a long program. Creates an object, `c`, which stores the position of every piece. Handling captures is simple, simply overwrite the square. Inside the `map` function, we assign `Q` to the target square's piece before overwriting, then refer to it when a capture is seen. If not a capture, then index into an array to find the correct file (correct me if "file" is not the right term as I'm no expert in chess) and determine the number (9-Y if black turn, Y if white term). Also a few simple invocations of `includes` and a few extra ternaries add the `ch`s and `mate`s at the end.

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


title: The next colour

text:
# Question
Title: The next colour
# Challenge

Consider the rainbow as seven colours, represented by strings as `Red Orange Yellow Green Blue Indigo Violet`.
Your task is to create a program that receives one of these colours as input and outputs next in order rainbow colour. This includes overlapping `Violet -> Red`

# Input

A string containing one of rainbow colours.

# Output

The next in order colour of the rainbow.

# Rules

* Colour names are case sensitive. They must match the case included in this post.
* The input will always be valid. Any behavior is allowed for invalid input.
* This is code golf, so the shortest amount of bytes wins!

# Example Input and Output

```
Input -> Output
Red -> Orange
Orange -> Yellow
Yellow -> Green
Green -> Blue
Blue -> Indigo
Indigo -> Violet
Violet -> Red

```

# Answer
# SOGL V0.12, 23 bytes

```
k‰³d∆|ΝμHō↑≥░δ÷f‘θ⁽,WIw

```

Try it Here!

Explanation:

```
...‘θ⁽,WIw
...‘        push "red orange yellow green blue indigo violet"
    θ       split on spaces
     ⁽      uppercase the 1st letter of every item (SOGLs dictionary only has lowercase words)
      ,W    get the inputs index in the array
        I   increment
         w  and get that item in the array, wrapping if necessary

```
> 2 votes

# Answer
# JavaScript, 68 bytes

```
s=>'RedOrangeYellowGreenBlueIndigoVioletRed'.match(s+'(.[a-z]*)')[1]

```

For input `"Red"`, this function first construct an RegExp `/Red(.[a-z]*)/` to match the string `'RedOrangeYellowGreenBlueIndigoVioletRed'` and then return the first capture result.

```
f=
s=>'RedOrangeYellowGreenBlueIndigoVioletRed'.match(s+'(.[a-z]*)')[1]

document.write('<table><tr><th>Input<th>Output')
for(i='Red';;){
document.write(`<tr><td>${i}<td>${i=f(i)}`);
if(i=='Red')break;
}
```
> 22 votes

# Answer
# Perl 5 `-p`, ~~58~~ 57 bytes

```
#!/usr/bin/perl -p
$_={(Red,Orange,Yellow,Green,Blue,Indigo,Violet)x2}->{$_}

```

Try it online!

Now that the challenge has been changed to be cyclic the regex solution

```
say RedOrangeYellowGreenBlueIndigoVioletRed=~/$_(.[a-z]+)/

```

isn't optimal anymore (due to the double `Red`)

Also 57 bytes:

```
#!/usr/bin/perl -p
$_=(Indigo,Blue,Violet,Yellow,Orange,Red,Green)[ord>>2&7]

```

Try it online!
> 9 votes

# Answer
# Python, 79 bytes

```
z="Red Orange Yellow Green Blue Indigo Violet".split()*2
dict(zip(z,z[1:])).get

```

Try it online!

Handles `Violet -> Red`. The desired function is given anonymously in the second line.

---

**80 bytes**

```
lambda x:"Red Orange Yellow Green Blue Indigo Violet Red".split(x)[1].split()[0]

```

Try it online!
> 7 votes

# Answer
# Perl 6, 56 bytes

```
{<Indigo Blue Violet Yellow Orange Red Green>[.ord/4%8]}

```

Try it online!

Exploits the fact that bits 2-4 of the ASCII codes of each color's first letter happen to map to 0-6.

```
say map (*.ord +> 2) % 8, <R O Y G B I V>
# (4 3 6 1 0 2 5)

```

Here's a nice non-competing solution that uses "purple" instead of "indigo" and "violet" (38 chars, 59 bytes):

```
{''.uninames~~m/$^a.\S+.<(\S+/}

```

Try it online!
> 7 votes

# Answer
# Ruby `-n`, ~~62~~ 60 bytes

-2 by Asone Tuhid.

```
p"RedVioletIndigoBlueGreenYellowOrangeRed"[/.[a-z]+(?=#$_)/]

```

Try it online!

Regex approach looks promising for Ruby too. However, I arrived at a shorter solution using a lookahead and directly printing the match, rather than playing with capturing groups. The list of colors is in reverse direction since lookahead is 1 byte cheaper than lookbehind.
> 5 votes

# Answer
# Red, 87 bytes

```
func[c][print first find/tail[Red Orange Yellow Green Blue Indigo Violet Red]to-word c]

```

Try it online!
> 4 votes

# Answer
# 05AB1E, 30 bytes

```
“†¾›ÈŠÛˆ¨‡—ëßigo°Íolet“#™DIk>è

```

Try it online!

**Explanation**

```
“†¾›ÈŠÛˆ¨‡—ëßigo°Íolet“          # push a string of colours
                       #         # split on spaces
                        ™        # title-case each
                         D       # duplicate
                          Ik     # get the index of the input
                            >    # increment
                             è   # get the element at that index

```
> 4 votes

# Answer
# Haskell, ~~80 71~~ 75 bytes

Thanks to Laikoni for shortening 9 bytes!

```
g x=snd(span(/=x)$words"Red Orange Yellow Green Blue Indigo Violet Red")!!1

```

Try it online!

---

Another solution, slightly more idiomatic, but I could not get it shorter:

```
data R=Red|Orange|Yellow|Green|Blue|Indigo|Violet deriving(Enum,Read,Eq)
succ.read

```

It needs to derive `Read` because of the requirement that the input is a string and at least `Eq` or `Show` in order to either test for equality or show the result.
> 3 votes

# Answer
# Java (JDK 10), 77 bytes

```
s->"Red Orange Yellow Green Blue Indigo Violet Red".split(s)[1].split(" ")[1]

```

Try it online!

## Credits
> 3 votes

# Answer
# Excel, 85 bytes

```
=CHOOSE(MOD(CODE(A1),12),"green","indigo","yellow",,,"orange","blue",,"violet","red")

```

Uses lowercase names.

Same approach, with Uppercase letters 86 bytes:

```
=CHOOSE(MOD(CODE(A1),12),"Violet","Red",,,"Green","Indigo","Yellow",,,"Orange","Blue")

```
> 3 votes

# Answer
# Vim, 59 56 53 52 Bytes

-1 byte thanks to tsh

```
2IYellow Green Blue Indigo Violet Red Orange *<Esc>**wywVp
```
> 3 votes

# Answer
## Retina, ~~65~~ 58 bytes

```
$
(.[a-z]+)
L$:`RedOrangeYellowGreenBlueIndigoVioletRed
$1

```

Try it online!

### Explanation

```
$
(.[a-z]+)

```

We start by appending `(.[a-z]+)` to the input, thereby turning it into a regex which matches the input colour, immediately followed by exactly one more colour (capturing the latter).

```
L$:`RedOrangeYellowGreenBlueIndigoVioletRed
$1

```

Now the `:` swaps the stage's input with its own regex. So the previous result becomes the regex and it's matched against the list of colours. The (single) match gets replaced with its first capturing group (i.e. the next colour in the cycle) and returned. Output at the end of the program happens automatically.
> 3 votes

# Answer
# Stax, ~~31~~ ~~30~~ 29 bytes

```
ÇôF┘≡▓ƒ◄╙>┘☼░⌂╪B<U[ÇQ╒eöΣQ╔÷n

```

Run and debug it

This uses the ring translation instruction. It replaces each element in an array with the following one from the "decoder ring". Usually, it's used to do character replacement in a string, but it can be used on an entire string too, if it's wrapped in a singleton array.

Here's the unpacked, ungolfed, commented ascii representation of the same program.

```
]   wrap input in singleton array
`5^bZ_9G*h]h%oM~X9e-0ZQJkb2`    compressed string literal with color names
:.j title case and split on spaces
:t  do ring translation

```

Run this one
> 2 votes

# Answer
# Coconut, 79 bytes

```
s->"# Violet Red # # Green Indigo Yellow # # Orange Blue".split()[ord(s[0])%12]

```

Try it online!
> 2 votes

# Answer
# , 67 64 62 bytes

-2 bytes thank to FrownyFrog

```
>:&.((cut'Red Orange Yellow Green Blue Indigo Violet Red')i.<)

```

Try it online!
> 2 votes

# Answer
# Husk, 28 bytes

```
S!o→€⁰w¨ṙ}ΘΞĠ«ẇ₇G²€ḃλBżḃIÿö⌉

```

Try it online!

Maybe there are better options for managing the arguments, but this is the best I could find

### Explanation

```
S!o→€⁰w¨ṙ}ΘΞĠ«ẇ₇G²€ḃλBżḃIÿö⌉
       ¨ṙ}ΘΞĠ«ẇ₇G²€ḃλBżḃIÿö⌉    Compressed string with all the colors
                                "Red Orange Yellow Green Blue Indigo Violet"
      w                         Split on spaces
S                               Pass the list to both the following functions:
    €⁰                          1) Find the index of the input in the list
  o→                                  and increase it by one
 !                              2) Get the element of the list at the
                                   resulting position (indexing is cyclical)

```
> 2 votes

# Answer
# , ~~109~~ 93 bytes

```
function(x){y=c("Red","Orange","Yellow","Green","Blue","Indigo","Violet");y[match(x,y)%%7+1]}

```

Try it online!

-16 thanks to Giuseppe for the use of `match` advice
> 2 votes

# Answer
# IBM/Lotus Notes Formula Language, ~~79~~ 74 bytes

```
@Left(@Right("Red Orange Yellow Green Blue Indigo Violet Red ";a+" ");" ")

```

Previous version for 79:

```
R:=@Explode("Red,Orange,Yellow,Green,Blue,Indigo,Violet,Red");R[@Member(a;R)+1]

```

Takes input from an editable text field called `a`.

There is no TIO for formula language so here's a couple of screenshots.
> 1 votes

# Answer
# Gema, 67 characters

```
*=@subst{*\?<J>=\?\$2\;\?=;RedOrangeYellowGreenBlueIndigoVioletRed}

```

Sample run:

```
bash-4.4$ echo -n Yellow | gema '*=@subst{*\?<J>=\?\$2\;\?=;RedOrangeYellowGreenBlueIndigoVioletRed}'
Green

bash-4.4$ echo -n Violet | gema '*=@subst{*\?<J>=\?\$2\;\?=;RedOrangeYellowGreenBlueIndigoVioletRed}'
Red

```

# Gema, 59 characters

```
R=Orange
O=Yellow
Y=Green
G=Blue
B=Indigo
I=Violet
V=Red
*=

```

Boring one. Dumbest approach ever, but quite short.

Sample run:

```
bash-4.4$ gema 'R=Orange;O=Yellow;Y=Green;G=Blue;B=Indigo;I=Violet;V=Red;*=' <<< 'Yellow'
Green

bash-4.4$ gema 'R=Orange;O=Yellow;Y=Green;G=Blue;B=Indigo;I=Violet;V=Red;*=' <<< 'Violet'
Red

```
> 1 votes

# Answer
# Ruby `-n`, ~~75~~ 69 bytes

```
a=%w{Red Orange Yellow Green Blue Indigo Violet};p a[-~(a.index$_)%7]

```

Try it online!
> 1 votes

# Answer
## Batch, 97 bytes

```
@set s=Red Orange Yellow Green Blue Indigo Violet Red
@call set s=%%s:*%1 =%%
@echo %s: =&rem %

```

Explanation: The `call` on the second line has the effect of substituting the parameter into the command and evaluating it, turning it into e.g. `set s=%s:Red =%`, which deletes the prefix of the string that includes the parameter. The substitution on the third line then replaces all the spaces with statement separators and comments. This works because string substitution happens before parsing.
> 1 votes

# Answer
# Julia 0.6, 76 bytes

```
f(s)=match(Regex("$s(.[a-z]*)"),"RedOrangeYellowGreenBlueIndigoViolet"^2)[1]

```

Try it online!

This handles the Violet-\>Red by recycling the string with the power `^` operator.

Here's a slightly longer solution without regexes:

```
g(s,l=split("Red Orange Yellow Green Blue Indigo Violet"," "))=l[(findin(l,[s])[1])%7+1]

```
> 1 votes

# Answer
# PowerShell, 74 bytes

```
(-split("Red Orange Yellow Green Blue Indigo Violet "*2-split$args)[1])[0]

```

Try it online!

Takes the string `"Red ... Violet "` and string-multiplies it out by two to properly handle the `Violet -> Red` test case. We then `-split` that string on input `$args` to give us an array of two strings. We take the second string thereof `[1]`, then `-split` that on whitespace to give us an array of strings and take the first `[0]`.

For example, for input `"Yellow"`, the first step will result in `@("Red Orange ", " Green Blue Indigo ... Indigo Violet ")`. We take the second one of that, split it on whitespace (which removes the whitespace), resulting in `@("Green", "Blue", ... "Violet")`, so taking the `[0]` one thereof results in the proper next string.
> 1 votes

# Answer
# PHP, 92 bytes

```
$a=" Red   OrangeYellowGreen Blue  IndigoVioletRed";echo substr($a,strpos($a,$argv[1])+6,6)

```

Try it online!
> 1 votes

# Answer
# Kotlin, 73 bytes

```
x->"RedOrangeYellow Green  BlueIndigoVioletRed".substringAfter(x).take(6)

```

Try it online!

Taking advantage of the fact that many colors are 6 characters, the ones that are not are prefixed with spaces to make them 6 characters long. Hopefully it's acceptable that some of the colors are outputted with spaces before them.
e.g. Red is `" Red"`, Blue is `" Blue"`
> 1 votes

# Answer
# SmileBASIC, ~~94~~ 84 bytes

```
C$="Red   OrangeYellowGreen Blue  IndigoViolet
INPUT I$?MID$(C$*2,INSTR(C$,I$)+6,6)

```
> 1 votes

# Answer
# Bash + GNU Utilities, 63

```
grep -Po $1\\K.[a-z]+<<<RedOrangeYellowGreenBlueIndigoVioletRed

```

The list of colours is reversed so that a regex lookahead may be used. The lookahead boilerplate is one byte shorter than the lookbehind boilerplate. Of course we can do better the PCRE `\K`.

Try it online!
> 1 votes

# Answer
# Japt, ~~45~~ 43 bytes

*-2 bytes thanks to Shaggy*

```
`R‚sOÎÁƒYÁMwsGÎ9sBluƒI˜igosVio¤t`qs
g1+UbNg

```

Try it online!
> 1 votes

# Answer
# q/kdb+, ~~59~~ 55 bytes

**Solution:**

```
.[!;2 8#($)`Red`Violet`Indigo`Blue`Green`Yellow`Orange]

```

**Examples:**

```
q).[!;2 8#($)`Red`Violet`Indigo`Blue`Green`Yellow`Orange]"Red"
"Violet"
q).[!;2 8#($)`Red`Violet`Indigo`Blue`Green`Yellow`Orange]"Orange"
"Red"
q).[!;2 8#($)`Red`Violet`Indigo`Blue`Green`Yellow`Orange]"Blue"
"Green"

```

**Explanation:**

Create a dictionary of colour =\> next colour, the input is the key to the dictionary:

```
.[!;2 8#($)`Red`Violet`Indigo`Blue`Green`Yellow`Orange] / the solution
.[ ;                                                  ] / apply multiple args to function
           `Red`Violet`Indigo`Blue`Green`Yellow`Orange  / list of colours
         ($)                                            / convert to strings
    2 8#                                                / reshape into 2x8 grid
  !                                                     / create dictionary

```

**Bonus:**

It's **53 bytes** in K4:

```
.[!;2 8#$`Red`Violet`Indigo`Blue`Green`Yellow`Orange]

```
> 1 votes

# Answer
# sed, 72 bytes

```
s/$/%RedOrangeYellowGreenBlueIndigoVioletRed/;s/(.+)%.*\1(.[a-z]+).*/\2/

```

Try it Online

**Example 1:**

Input:

```
Red
Orange
Yellow
Green
Blue
Indigo
Violet

```

Output:

```
Orange
Yellow
Green
Blue
Indigo
Violet
Red

```

**Example 2:**

Input:

```
Indigo
Yellow
Red
Red
Blue
Green
Orange
Violet
Green
Green
Green
Blue
Blue
Violet

```

Output:

```
Violet
Green
Orange
Orange
Indigo
Blue
Yellow
Red
Blue
Blue
Blue
Indigo
Indigo
Red

```
> 1 votes

# Answer
# Factor, 81 bytes

```
[ qw{ Red Orange Yellow Green Blue Indigo Violet } [ index 1 + 7 mod ] keep nth ]

```

Try it online!
> 1 votes

# Answer
# Red, 74 bytes

```
func[c][prin select[Red Orange Yellow Green Blue Indigo Violet Red]load c]

```

Try it online!
> 1 votes

# Answer
# APL+WIN, 66 bytes

```
↑(c⍳⊂⎕)⌽c←'Red' 'Orange' 'Yellow' 'Green' 'Blue' 'Indigo' 'Violet'

```

Prompts for screen input of colour as a string.
> 0 votes

# Answer
# Python 2, ~~89~~ 87 bytes

```
def f(c):a="red orange yellow green blue indigo violet".split();print a[-~a.index(c)%7]

```

**Test cases:**

`f("red")` -\> orange

`f("orange")` -\> yellow

`f("yellow")` -\> green

`f("green")` -\> blue

`f("blue")` -\> indigo

`f("indigo")` -\> violet

`f("violet")` -\> red

`f("notAColour")` -\> Error
> 0 votes

# Answer
# C (gcc) preprocessor macro, 74

Score is 74 bytes passed to the compiler.

Same idea as @nwellnhof's Perl answer.

```
-Df(c)=printf("%.6s","IndigoBlue  VioletYellowOrangeRed   Green"+*c/4%8*6)

```

Try it online!
> 0 votes

# Answer
# C (gcc), 88 bytes

```
f(char*s){printf("%.6s",(strstr("red   violetindigoblue  green yelloworangered",s)+6));}

```

Try it online!
> 0 votes

# Answer
# Swift, 121 113 bytes

```
let s=readLine()!;let i=["Red","Orange","Yellow","Green","Blue","Indigo","Violet"];print(i[(i.index(of:s)!+1)%7])

```

Try it online!
> 0 votes

# Answer
# Python 3, 85 bytes

```
c='Red Orange Yellow Green Blue Indigo Violet'.split()
f=lambda x:c[(c.index(x)+1)%7]

```

Try it online!
> 0 votes

# Answer
# Wolfram Language (Mathematica), 84 bytes

TextWords version (84 Bytes but slow)

```
#/.Thread[#->RotateLeft@#&[TextWords@"Red Orange Yellow Green Blue Indigo Violet"]]&

```

StringSplit (86 Bytes)

```
#/.Thread[#->RotateLeft@#&[StringSplit@"Red Orange Yellow Green Blue Indigo Violet"]]&

```

Built-in color names called by number, also 86 Bytes:

```
#/.Thread[#->RotateLeft@#&[ColorData["HTML","Range"][[1,{114,100,139,52,10,57,135}]]]]

```

Try it online!
> 0 votes

# Answer
# Lua, 89 bytes

```
c="Red   OrangeYellowGreen Blue  IndigoVioletRed"r=c:find(io.read())+6print(c:sub(r,r+5))

```

Outputs some trailing spaces. Example:

```
input: Yellow
output: Green
space here:  ^

```

Try it online!

# Lua, 102 bytes

```
c="Red   OrangeYellowGreen Blue  IndigoVioletRed"r=c:find(io.read())+6print(c:sub(r,r+5):match("%a+"))

```

Doesn't output any trailing spaces.

Try it online!
> 0 votes

# Answer
# Tcl, 98 bytes

```
puts [lindex [set L {Red Orange Yellow Green Blue Indigo Violet}] [expr ([lsearch $L $argv]+1)%7]]

```

Try it online!

---

# Tcl, 98 bytes

```
puts [lindex [set L {Red Orange Yellow Green Blue Indigo Violet Red}] [expr [lsearch $L $argv]+1]]

```

Try it online!
> 0 votes

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


title: Drink your morning coffee

text:
# Question
Title: Drink your morning coffee
Draw this Ascii coffee cup:

```
  o
       o
    o
 __________
/          \__
|   J      |  \
|    A     |  |
|     V    |  |
|      A   |__/
\__________/
```

Brownie points for coffee-script or java :)

Shortest code in bytes, function or program, trailing newline or white space is acceptable, drink up!

# Answer
# SOGL, 48 bytes

```
mγmλ⁶…Jcēņ▒&↓¡℮štΥ{ιE‽▼⅛÷εγ╝Ξ∫$■⌡πθ&χF׀▼ΡQ7L↓F¶‘

```

Explanation:

SOGL has built-in string compression and one of the things it has is a char dictionary compression. Even better, it has a boxstring compression type where the only chars available are " /\\|\_-\n". So the whole program is a string encased in "‘ (the " is implicit).

The string I gave the compressor are (escaped):

```
"  o\n       o\n    o\n ",
"__________",
"\n/          \\__\n|   ",
"J",
"      |  \\\n|    ",
"A",
"     |  |\n|     ",
"V",
"    |  |\n|      ",
"A",
"   |__/\n\\",
"__________",
"/"

```
> 3 votes

# Answer
## JavaScript (ES6), ~~110~~ 104 bytes

*Saved 4 bytes thanks to edc65*

```
let f =

_=>`1o
6o
3o
 9
/44\\__
|2J5|1\\
|3A4|1|
|4V3|1|
|5A2|__/
\\9/`.replace(/\d/g,n=>' _'[n>>3].repeat(++n))

console.log(f())
```

### How it works

The compression of the original ASCII art is achieved by replacing all sequences of 2 to 10 consecutive spaces and the two sequences of 10 consecutive underscores with a single digit:

* Each sequence of `N` consecutive spaces is encoded with the digit `N-1`.
* The underscore sequences are encoded with a `9`.

We use `N-1` rather than `N` so that we never have to use more than one digit. Hence the need for `++n` when decoding.

The expression `n>>3` (bitwise shift to the right) equals 0 for `n = 1` to `n = 7` and equals 1 for `n = 8` (not used) and `n = 9`. Therefore, `' _'[n>>3]` gives an underscore for `9`, and a space for all other encountered values.

The only special case is the sequence of 10 consecutive spaces just above "JAVA". Encoding it with a `9` would conflict with the underscore sequences. So we need to split it into two sequences of 5 spaces, encoded as `44`.
> 16 votes

# Answer
# Jelly, ~~67~~ 64 bytes

-2 bytes thanks to Dennis (1. remove redundant , and 2. replace transpose and run-length decode, `ZŒṙ`, with reduce by element repetition, `x/`.)

```
“Ñṁ{xGgṭḷVỤɲ8ṿfƬT9Ɱ¹=qṀS“$<(ƇỤ08ØÑḌṃṘX6~cuc8HṗḞ2’Dx/ị“ ¶_/\|JAVo

```

**Try it online!**

### How?

`“...“...’` is a list of two base-250 compressed numbers:

```
[1021021021332411532617161526181616261916162618163425334, 2117114111551155121131612111415121115141211161312111551]

```

`D` converts to decimal to yield two lists of digits:

```
[[1, 0, 2, 1, 0, 2, 1, 0, 2, 1, 3, 3, 2, 4, 1, 1, 5, 3, 2, 6, 1, 7, 1, 6, 1, 5, 2, 6, 1, 8, 1, 6, 1, 6, 2, 6, 1, 9, 1, 6, 1, 6, 2, 6, 1, 8, 1, 6, 3, 4, 2, 5, 3, 3, 4], [2, 1, 1, 7, 1, 1, 4, 1, 1, 1, 5, 5, 1, 1, 5, 5, 1, 2, 1, 1, 3, 1, 6, 1, 2, 1, 1, 1, 4, 1, 5, 1, 2, 1, 1, 1, 5, 1, 4, 1, 2, 1, 1, 1, 6, 1, 3, 1, 2, 1, 1, 1, 5, 5, 1]]

```

`x/` reduces by element repetition to give one list of digits (repeating the number from the first list by the corresponding value of the other):

```
[1, 1, 0, 2, 1, 1, 1, 1, 1, 1, 1, 0, 2, 1, 1, 1, 1, 0, 2, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 3, 3, 2, 6, 1, 1, 1, 7, 1, 1, 1, 1, 1, 1, 6, 1, 1, 5, 2, 6, 1, 1, 1, 1, 8, 1, 1, 1, 1, 1, 6, 1, 1, 6, 2, 6, 1, 1, 1, 1, 1, 9, 1, 1, 1, 1, 6, 1, 1, 6, 2, 6, 1, 1, 1, 1, 1, 1, 8, 1, 1, 1, 6, 3, 3, 4, 2, 5, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4]

```

instructs to index into the list of the right, one based and modularly (0 indexes into the rightmost item). The list on the right,  `¶_/\|JAVo`, is simply the character used in the required order where the pilcrow, , is the same code-point as a linefeed. The closing partner of  is not required as this is the end of the program:

```
[' ', ' ', 'o', '\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'o', '\n', ' ', ' ', ' ', ' ', 'o', '\n', ' ', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '\n', '/', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\\', '_', '_', '\n', '|', ' ', ' ', ' ', 'J', ' ', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', '\\', '\n', '|', ' ', ' ', ' ', ' ', 'A', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', '|', '\n', '|', ' ', ' ', ' ', ' ', ' ', 'V', ' ', ' ', ' ', ' ', '|', ' ', ' ', '|', '\n', '|', ' ', ' ', ' ', ' ', ' ', ' ', 'A', ' ', ' ', ' ', '|', '_', '_', '/', '\n', '\\', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '/']

```

Jelly performs an implicit print of this list, which, since it contains characters, prints as if it were a string:

```
  o
       o
    o
 __________
/          \__
|   J      |  \
|    A     |  |
|     V    |  |
|      A   |__/
\__________/

```
> 16 votes

# Answer
# CoffeeScript ES6, 214 180 bytes

```
r="replace";" 1o0n0 6o0n0 3o0n0 _9n0/0 9b0_1n0|0 2J0 5|0 1b0n0|0 3A 4|0 1|0n0|0 4V0 3|0 1|0n0|0 5A0 2|0_1/0n0b0_9/0"[r](/\d/g,(a,b,c)->c[b-1].repeat(a))[r](/n/g,"\n")[r](/b/g,"\\")

```

# CoffeeScript, 135 bytes with hardcoding

```
f=()->"""  o
       o
    o
 __________
/          \__
|   J      |  \\
|    A     |  |
|     V    |  |
|      A   |__/
\__________/"""

```
> 10 votes

# Answer
# PowerShell, ~~136~~ ~~124~~ ~~123~~ 105 bytes

```
"""2o
7o
4o
 $(($a='_'*10))
/55\__
|3J6|2\
|4A5|2|
|5V4|2|
|6A3|__/
\$a/"""-replace'(\d)','$(" "*$1)'|iex

```

Try it online!

*Thanks to @briantist for finding the shorter `-replace` method that I knew was there somewhere.*

This takes the string with numbers in place of the requisite number of spaces. We then regex `-replace` the digits with a script expression `$(" "*$1)`. So, for example, the first line of the string will be `$(" "*2)o`, the second will be `$(" "*7)o` and so on. Because of the triple-quoting, this is left as a string on the pipeline. We dump that to `iex` (short for `Invoke-Expression` and similar to `eval`), which processes the script expressions and leaves the resulting multi-line string on the pipeline. Output is implicit.
> 9 votes

# Answer
# Python 2, ~~174~~ ~~172~~ ~~171~~ 167 bytes

No hard-coding.
No Base-64 encoding.
No Regex.

```
k=' '
q='_'*10
print'\n'.join([k*i+'o'for i in 2,7,4]+[k+q]+['/'+k*10+'\\__']+['|'+k*s+'JAVA'[s-3]+k*(9-s)+'|'+' _'[s==6]*2+'\\||/'[s-3]for s in 3,4,5,6]+['\\'+q+'/'])

```

Saved 2 bytes by externalizing `'_'*10` and by exploiting Python's conversion of `True -> 1` and `False -> 0`.
Saved 1 byte by removing unnecessary whitespace.
Saved 4 bytes thanks to @TuukkaX!
> 6 votes

# Answer
# Python 2, ~~128~~ 127 bytes

-1 byte thanks to Rod (use multiplication of tuple `('_'*10,)` to avoid a declaration).

```
print''.join('0'<c<':'and' '*int(c)or c for c in'''2o
7o
4o
 %s
/ 9\__
|3J6|2\\
|4A5|2|
|5V4|2|
|6A3|__/
\%s/'''%(('_'*10,)*2))

```

**Try it online!**

*Note:* that double backslash *is* needed before the line feed.

Everything between the `'''` and `'''` is a single string, the two `%s` are formatters which get replaced by the content of the trailing `%(...)` tuple, which in turn contains two copies of `'_'*10` via the tuple multiplication `(...)*2`. The `'_'*10` performs string multiplication to yield `'__________'`.

The code traverses the characters, `c`, of that whole string using `for c in '''...` and creates a new string by joining (`join(...)`)
*either* the number of spaces identified by `c`, `int(c)`, if `c` is a digit
*or* `c` itself
\- being a digit is identified by `'0'<c<':'` to save over `c.isdigit()`.
> 4 votes

# Answer
# MATL, ~~87~~ ~~86~~ ~~83~~ ~~82~~ 78 bytes

```
[TIH][IAC]111Z?c'(ty!(OWM4J4gW{lm> >bw8ch|.FU2W"@\#2Dj!NQDeIMZ'F'_ /|\JAV'Za7e

```

This solution breaks the coffee into two pieces: the "bubbles" and the mug. To create the bubbles, we create a sparse matrix with 111 located at three locations and convert it to a character array

```
[TIH][IAC]111Z?c

```

For the mug component, we rely upon string compression

```
'(ty!(OWM4J4gW{lm> >bw8ch|.FU2W"@\#2Dj!NQDeIMZ'F'_ /|\JAV'Za7e

```

Both components are printed to the output and a newline is automatically placed between the components

Try it at **MATL Online**
> 4 votes

# Answer
## GNU sed, ~~113~~ 112 bytes

```
s:$:  o@SS o@S o@ UU@/SSS \\__@|SJSS|  \\@|S AS  |  |@|S  VS |  |@|SSAS|__/@\\UU/:
s:S:   :g
y:@:\n:
s:U:_____:g

```

Basic encoding, it stores 3 spaces as `S`, `\n` as `@` and 5 underlines as `U`. I'll keep trying combinations to find something shorter.

**Try it online!**

The trivial solution of printing the string directly is given below. It has 136 bytes, resulting in a compression of 18 %, using the encoding scheme above.

```
c\  o\
       o\
    o\
 __________\
/          \\__\
|   J      |  \\\
|    A     |  |\
|     V    |  |\
|      A   |__/\
\\__________/

```

**Try it online!**
> 4 votes

# Answer
# Java 8, 294 289 248 bytes

Golfed:

```
()->{String s="";for(char c:"\u026F\n\u076F\n\u046F\n __________\n/\u0A5C__\n|\u034A\u067C\u025C\n|\u0441\u057C\u027C\n|\u0556\u047C\u027C\n|\u0641\u037C__/\n\\__________/".toCharArray()){for(int i=0;i<c>>8;++i)s+=' ';s+=(char)(c&255);}return s;}

```

In the spirit of , this does not hard-code the string to output. Instead, it makes use of the fact that there are many cases of multiple spaces followed by a printable character. It encodes the number of spaces that precede a character in the high-order byte of the character, with the actual ASCII character in the low-order byte.

Ungolfed:

```
import java.util.function.*;

public class DrinkYourMorningCoffee {

  public static void main(String[] args) {
    System.out.println(f(
    () -> {
      String s = "";
      for (char c : "\u026F\n\u076F\n\u046F\n __________\n/\u0A5C__\n|\u034A\u067C\u025C\n|\u0441\u057C\u027C\n|\u0556\u047C\u027C\n|\u0641\u037C__/\n\\__________/".toCharArray()) {
        for (int i = 0; i < c >> 8; ++i) {
          s += ' ';
        }
        s += (char) (c & 255);
      }
      return s;
    }
    ));
  }

  private static String f(Supplier<String> s) {
    return s.get();
  }
}

```
> 4 votes

# Answer
# Common Lisp, ~~125~~ ~~123~~ ~~122~~ ~~120~~ 114 bytes

```
(format t"~3@{~vto
~} ~10@{_~}
/~11t\\__
|   J~11t|  \\
~2@{|~5t~a~11t|  |
~}|~7tA   |__/
\\~10{_~}/"2 7 4'A" V"1)

```

I saved 6 bytes, using idea of just putting enters in string instead of `~&`s.

Ideas for improvement welcomed.
> 2 votes

# Answer
# Befunge, ~~158~~ ~~105~~ 101 bytes

```
<v"XaXXXNYXNY77777'XXXXX2_TXQXX0XZTXDXX0X^TXXRX0X^TXXDX07]27777#"p29+55
:<_@#:,g2/+55,g2%+55
\JV/|_Ao

```

Try it online!

The characters in the string are first encoded as indices into a lookup table of the ten possible values. The indices are then grouped into pairs, each pair being combined into a single number (i1 + i2\*10) in the range 0 to 99. By carefully choosing the order of the lookup table, we can guarantee that those values will always be valid ASCII characters which can be represented in a string literal.

This is a breakdown of the code itself:

We start by initialising the last element of the lookup table with a newline character (ASCII 10).
We then use a string literal to push the encoded content onto the stack.
Finally we loop over the values of the stack, decoding and outputting two characters at a time.
The last line hold the lookup table: the 9th element is an implied space, and the 10th (newline) is set manually, as explained earlier.
> 2 votes

# Answer
# Retina, 71 bytes

Differently from my other answer, this one was written by hand.

```

2o¶6o¶3o¶1=¶/55\__¶|3J6|2\¶|4A5|2|¶|5V4|2|¶|6A3|__/¶\=/
=
10$*_
\d
$*

```

(there's a trailing space at the end)

Try it online!

The principle is still having a "compressed" string from which the cup of coffee can be reconstructed by substitutions. Trying different substitutions it turned out that the only ones worth doing are:

* `=` turns into `__________` (10 underscores)
* any digit turns into that number of spaces
> 2 votes

# Answer
# Python3, 206 bytes

```
print('  o\n'+7*' '+'o\n'+4*' '+'o\n'+' '+10*'_'+'\n'+'/'+10*' '+'\__\n'+'|'+3*' '+'J'+6*' '+'|  \\\n'+'|'+4*' '+'A'+5*' '+'|  |\n'+'|'+5*' '+'V'+4*' '+'|  |\n'+'|'+6*' '+'A'+3*' '+'|__/\n'+'\\'+10*'_'+'/')

```
> 1 votes

# Answer
# Pyth, 80 bytes

```
r"  o
7 o
4 o
 10_
/10 \__
|3 J6 |  \\
|4 A5 |  |
|5 V4 |  |
|6 A3 |__/
\\10_/"9

```

Online interpreter available here.

Simple run-length decoding.
> 1 votes

# Answer
# C - 179

Solution with extensive use of format string:

```
void f(){printf("%1$3c\n%1$8c\n%1$5c\n%2$11s\n/%3$13s\n|%4$4c%5$7c%6$3c\n|%7$5c%5$6c%5$3c\n|%8$6c%5$5c%5$3c\n|%7$7c%5$4c__/\n\\%2$s/\n",'o',"__________","\\__",74,'|',92,65,86);}

```

Here is a more readable version:

```
void f() {
  printf("%1$3c\n"
         "%1$8c\n"
         "%1$5c\n"
         "%2$11s\n"
         "/%3$13s\n"
         "|%4$4c%5$7c%6$3c\n"
         "|%7$5c%5$6c%5$3c\n"
         "|%8$6c%5$5c%5$3c\n"
         "|%7$7c%5$4c__/\n"
         "\\%2$s/\n"
         'o',"__________","\\__",'J','|','\','A','V');
}

```
> 1 votes

# Answer
# Retina, 99 bytes

This solution was generated automatically using this script.

```

0 0o¶ 1¶/32\__¶4 J24\¶|3A 34|¶| 3V34|¶|2A   |__/¶\1/
4
|
3

2

1
__________
0
  o¶

```

(there are trailing spaces on many lines)

This works by using numbers 1,2,3,4 in place of some character sequences that are repeated in the target string and then substituting them back.

I know it could be golfed more by tweaking this code or completely changing approach, but since the kolmogorov meta-golf challenge had quite a disappointing outcome I wanted to try using my script on a real challenge.

Try it online!
> 1 votes

# Answer
# PowerShell, 96 bytes

```
"2o
7o
4o
 0
/55\__
|3J6|2\
|4A5|2|
|5V4|2|
|6A3|__/
\0/"-replace'\d',{' '*"$_"+(,'_')["$_"]*10}

```

Try it online!
> 1 votes

# Answer
# Charcoal, 62 bytes

```
≔\||||α”{“‽!⭆hi¿ü” ×_¹⁰↓× ⁵¦ __↑/||\← __↓α←”|⁻⎚}”↑⁺α/Ｍ⁴¦²↘JAVA

```

Try it online!

# Pure `”~”` compression, 62 bytes

```
”~∨]S⁶Ｇ⌈↖Ｌ⌈ＬＴＦＪＳ‖j∕⍘c⊗l⁶D⍘2Ｓ∧⦃﹪�⎚º}ερＫＭ✳AV³α；≕～FＹ|◧:¶d⮌rt；↶≕Xê

```

Try it online!
> 1 votes

# Answer
## Python 3.6

*(non-competing)*

Here's my attempt at Huffman encoding. It's definitely golfable further if anyone wants to take up the idea.

```
from bitarray import bitarray as b
a=b()
a.frombytes(bytes.fromhex('ca7fca7e53b6db6db664ffc6d9ae1fd6335e2fad1af83d68d7e2e9b218db6db6db20'))
print(''.join(a.decode({k:b(v)for k,v in zip(" _|\no/\\AJV","1 011 010 0011 00101 00100 00011 00010 00001 00000".split())})))
```

The literal could be compressed further still by converting to base64 or other, and the Huffman tree could be optimized to yield a shorter bitarray still.
> 0 votes

# Answer
# GameMaker Language, 138 bytes

```
show_message("  o#       o#    o# __________#/          \__#|   J      |  \#|    A     |  |#|     V    |  |#|      A   |__/#\__________/")

```
> 0 votes

# Answer
# C, 141 Bytes

```
f(){printf("  o\n%7co\n    o\n __________\n/%11c__\n|   J%6c|  \\\n|    A     |  |\n|%6c    |  |\n|%7c   |__/\n\\__________/",0,92,0,86,65);}

```

### Usage

```
main(){f();}

```

## Easy Solution, 148 Bytes:

```
w(){puts("  o\n       o\n    o\n __________\n/          \\__\n|   J      |  \\\n|    A     |  |\n|     V    |  |\n|      A   |__/\n\\__________/");}

```
> 0 votes

# Answer
# PHP, 116 bytes

```
for(;$c="1o
6o
3o
 9
/44\\__
|2J5|1\\
|3A4|1|
|4V3|1|
|5A2|__/
\\9/"[$i++];)echo$c>0?str_repeat(" _"[$c>8],$c+1):$c;

```

This looks a lot like Arnauld´s answer \- and does pretty much the same. Run with `-r`.
> 0 votes

# Answer
# zsh, 86 bytes

```
printf "^_<8b>^H^@^@^@^@^@^B^CSPÈçR^@^A^P^CJÆÃ^A<97>¾^B^\Ä^@¹5@Ú^KÂ^E2cÀ|^EG^X¿^FÂW^HCæÃTÔÄÇësÅÀ^L^Fq^@<92>}ý^?{^@^@^@"|zcat

```

Explanation: that string is the gzip-compressed java cup ascii art. I use `printf`, because with `echo`, `zcat` prints a warning, and `echo -e` is one character longer. It doesn't work with `bash` or `sh`, because they think it's a binary file. Since you can't effectively paste that output from the browser, here's a usable file.
> 0 votes

# Answer
# Java 9 / JShell, 299 bytes

```
()->{String s="";BigInteger b=new BigInteger("43ljxwxunmd9l9jcb3w0rylqzbs62sy1zk7gak5836c2lv5t36ej6682n2pyucm7gkm9bkfbn4ttn0gltbscvbttifvtdfetxorj6mmy3mt6r3",36);while(!b.equals(BigInteger.ZERO)){int x=b.intValue()&0x3ff;for(int i=0;i<x>>7;i++)s+=' ';s+=(char)(x&0x7f);b=b.shiftRight(10);}return s;}

```

Ungolfed:

```
() -> {
    String s = "";
    BigInteger b = new BigInteger(
        "43ljxwxunmd9l9jcb3w0rylqzbs62sy1zk7gak5836c2lv5t36ej6682n2pyucm7gkm9bkfbn4ttn0gltbscvbttifvtdfetxorj6mmy3mt6r3",
        36);
    while (!b.equals(BigInteger.ZERO)) {
        int x = b.intValue() & 0x3ff;
        for (int i = 0; i < x >> 7; i++) s+=' ';
        s += (char)(x&0x7f);
        b = b.shiftRight(10);
    }
    return s;
}

```

Usage in JShell:

```
Supplier<String> golf = <lambda expression>
System.out.println(golf.get())

```

Encodes each character as ten bits consisting of a count of the number of spaces before the character in the high three bits following by the code point in the low seven bits.

(Since there are only three bits for the count it can't represent more than seven consecutive spaces, and there are ten spaces at one point in the string. These are encoded as a count of six, followed by a space, and then a count of three followed by the next character.)

Sadly, it loses to this trivial 140-byte Java solution:

```
()->"  o\n       o\n    o\n __________\n/          \\__\n|   J      |  \\\n|    A     |  |\n|     V    |  |\n|      A   |__/\n\\__________/"

```
> 0 votes

# Answer
# 05AB1E, 85 bytes

```
•1d'uì[_ÍpH»Ð]jŠ$ÿ{É˜ß|ªpå±W¾Ö:ÞjÇ&@è$´Öàˆå]Á¢šBg¦ï&-ã¥ønØ7Ñà'?•9B8ÝJ"o _/\|JAV"‡15ô»

```

Try it online!
> 0 votes

# Answer
# 05AB1E, ~~67~~ 65 bytes

```
'oƵ®Sú»•BÇÉι!т³ÂSˆtTóV”PHAëdÀāåΘý”å.@=Ø₂)øUqrÖ½ñ*•“_ |
\/AVJ“ÅвJ»

```

Pretty straight-forward approach which most likely has room for improvement.

Try it online.

**Explanation:**

```
'o            '# Push an "o"
  Ƶ®           # Push compressed integer 274
    S          # Convert it to a list of digits: [2,7,4]
     ú         # Prepend that many leading spaces to the "o": ["  o","       o","   o"]
      »        # Join them by newlines: "  o\n       o\n   o"
•BÇÉι!т³ÂSˆtTóV”PHAëdÀāåΘý”å.@=Ø₂)øUqrÖ½ñ*•
               # Push compressed integer 21514733101393053622421734761651860518184887728386739717403046550918945532453802933506348033205129
 “_ |\n\/AVJ“  # Push string "_ |\n\/AVJ"
  Åв           # Convert the integer to base-"_ |\n\/AVJ"
               # (builtin for converting to base string-length, and index those into the string)
    J          # Join the characters to a single string
     »         # And join the two strings on the stack by a newline
               # (after which the result is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ƶ®` is `274` and `•BÇÉι!т³ÂSˆtTóV”PHAëdÀāåΘý”å.@=Ø₂)øUqrÖ½ñ*•` is `21514733101393053622421734761651860518184887728386739717403046550918945532453802933506348033205129`.
> 0 votes

# Answer
# Vyxal, 108 bytes

```
`274`ƛI\o꘍,;_ð\_₀*+,\/₀꘍`\__`+,\|3꘍\J6꘍\|ðd\\Wṅ,\|4꘍\A5꘍`| `m++,\|5꘍\V4꘍`| `m++,\|6꘍\A3꘍`|__/`++,\\\_₀*\/++,

```

Try it Online!
> 0 votes

# Answer
# 05AB1E, 65 bytes

```
'oƵ®Sú»•BÇÉι₆₅8á·ŸˆE©/LнDË9Ï0³†₃þC¤ā¸·Í¨z©´Kˆι₃BÄ•"_
/\|JAV"ÅвJ»

```

Try it online!

# Pure `Åв` compression (compressing the bubbles too), 67 bytes

```
•5m™ÔćtвÃÔηŒćõ»θpøàÄqŠZ₂rÓ¢γβÞĆ?úËÄÌUöÉн%Cñí₄‡±ÁkÆùi•"o
_/\|JAV"Åв

```

Try it online! Outputs as a list of characters.

# `Λ` canvas, 109 bytes

```
'oƵ®Sú»6…/||º4Λ12„\_`5×«º2Λ2„/|0Λ4„|_º2Λ4„/|º0Λ4„\ º6Λ4'|4Λ5'|0Λ4ð2Λ4„ _º6Λ2'\0Λ2ð6ΛT'_6Λ3…_  4Λ4ð2Λ4'îáu3.Λ»

```

Try it online!
> 0 votes

# Answer
# Canvas, 59 bytes

```
？Eα)⁶^↑^jo↕ｊα◂9Ｓ⁷YNＵ>AｇＸ↷ＵＥ╬ｑ\ｄ7ｆ²ｔ}ＭøＱ＃║Ｍ<Y5２ｄｐc３Ｉ‰０Ｃ5Ｇ９－‟

```

Try it online!
> 0 votes

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


title: Optimize imnotdeadfish

text:
# Question
Title: Optimize imnotdeadfish
## Fluff

After taking a look at deadfish, I decided it sucked, so I came up with a new (and easier) variant of it: imnotdeadfish.

As with its predecessor, there are 4 commands and an accumulator which begins at 0:

```
+ # increment the accumulator
- # decrement the accumulator
s # square the accumulator
o # output the accumulator as an ascii char

```

The only difference between the languages (besides using + and -) is that if the accumulator ever goes out of range of 0 \<= x \< 256, the accumulator is taken mod 256. Ex: if the accumulator is at `255` and the command + is executed, it wraps to 0, and if, for example, it is at `0` and the command is -, the result would be 255.

An example program such as this: `++++s+so` which would output `!`

## Challenge

The problem with imnotdeadfish is that it's *too* easy, which means optimal solutions are not hard to find.

Given a string of characters, output the shortest code (which is not necessarily unique) in imnotdeadfish that prints the output. This should work for all inputs with chars between 0-255, but the testcases won't cover that.

## Examples

input =\> output

```
Hello, World! => +++s+s-s-o++s+o+++++++oo+++o----ss++s+++os+s-o+++++s--o-s+++s--o+++o------o-s---sos+so
test          => ++s+ss+++o++s+o++s++o+o
aaaaaaaaaa    => +++s--ssoooooooooo

```

This is so the shortest program, in bytes, wins. (this is the program you write, not the resulting imnotdeadfish program, since those should be the same length)

Here is a reference implementation of imnotdeadfish (for testing - this is not a valid submission to this challenge).

# Answer
# JavaScript (ES6), 129 bytes

Expects an array of characters. Returns a string.

```
a=>a.map(c=>{for(k=0;c.charCodeAt(o='')^(g=x=>(o+="o+s-"[q=x&3],q)?g(x/4,n-=q-2||n-n*n,n&=255):n)(k++,n=r););r=n;O+=o},r=O='')&&O

```

Try it online!

### Commented

```
a =>                     // a[] = input array
a.map(c =>               // for each character c in a[]:
  { for(                 //   loop:
      k = 0;             //     start with k = 0
      c.                 //     we'll stop as soon we've found a sequence
      charCodeAt(        //     producing the ASCII code of c
        o = ''           //     start each iteration with o = ''
      ) ^                //
      ( g = x =>         //     g is a recursive function which turns x
                         //     into a sequence of imnotdeadfish commands
        ( o +=           //       append to o:
            "o+s-"[      //         the symbol of the command q
              q = x & 3  //         with q = floor(x) mod 4
            ],           //
          q              //
        ) ?              //       if q is not equal to 0:
          g(             //         do a recursive call to g:
            x / 4,       //           divide x by 4
            n -=         //           update n:
              q - 2 ||   //             do +1 or -1 if q is not equal to 2
              n - n * n, //             otherwise, update n to n * n
            n &= 255     //           reduce n to a byte
          )              //         end of recursive call
        :                //       else (q = 0):
          n              //         stop here and return n
      )(k++, n = r);     //     initial call to g / increment k afterwards
    );                   //   end of for
    r = n;               //   update r to n
    O += o               //   append o to O
  },                     //
  r = O = ''             //   start with O = empty string and r zero'ish
) && O                   // end of map(); return O

```
> 6 votes

# Answer
# Python 3, 190 bytes

```
def g(x,y):
	q=[(x,"")]
	for c,s in q:
		if c==y:return s
		for n,a in[(c+1,"+"),(c-1,"-"),(c*c,"s")]:
			q+=[(n%256,s+a)]
s=[*map(ord,input())]
for x,y in zip([0]+s,s):print(end=g(x,y)+"o")

```

Try it online!

-20 bytes thanks to ophact; I was initially using a "visited" set but I forgot to add to it in the first place so it seems like it's not too necessary for efficiency, it's more the choice to BFS over brute force.

This is, by far, not the golfiest approach, but it is relatively efficient. I could golf this down a lot by brute forcing but I wanted to go for a faster approach.
> 4 votes

# Answer
# Python 2 (PyPy), 166 bytes

```
p=0
S=''
for c in map(ord,input()):
 for i in range(4**14):
	d='';n=p
	while i:d+='+-s'[i%4-1:i%4];n=[n,n+1,n-1,n*n][i%4]%256;i/=4
	if n==c:S+=d+'o';p=c;break
print S

```

Try it online!

Instead of brute-forcing the entire program, we only do it in between each character (to speed it up so it doesn't take forever). We use a bitmask to search for all possible answers up to a length of 14 (which is the maximum length needed to find an answer, from my testing).

One thing to note is that the we brute-force *four* commands instead of three. The fourth command is a NOP (meaning it does nothing), which ensures that the bitmask runs through all possible lengths. The NOP is not actually included in the program.

It takes just one second to run all three test cases on TIO. Note that PyPy is used instead of CPython to speed up execution time.
> 4 votes

# Answer
# JavaScript (ES6), 140 bytes

```
a=>a.map(p=n=>(g=([m,o],...q)=>(p=m&255)-n.charCodeAt()?g[p]?g(...q):g(...q,g[p]=[p+1,o+'+'],[p-1,o+'-'],[p*p,o+'s']):o+'o')([p,''])).join``

```

Try it online!

Input array of characters, output a string.

Remove the `g[p]?g(...q):` would work in theory but actually result stack overflow. :(

```
a=> // input (as array of characters)
a.map(
p= // p&255 is the value of cell, initial to 0
n=> // for each character `n`
(g= // a recursive function apply bfs for shortest code output `n`
    // g is assigned each iteration, so g[p] (discussed later) is cleared
 ([m, // current value got
  o], // code for current value
  ...q // queue for bfs
 )=>
  (p= // let `p` memorize code of previous char
   m&255) // bit-wise and 255 for mod 256, works for negative numbers
  -n.charCodeAt()? // the value got equals to current char?
 // not equal
 g[p]? // value `p` had been searched before
  g(...q): // don't search it again
  g(...q,  // bfs with following items enqueue
    g[p]= // assign g[p] to something thuthy so we won't search it again
    [p+1,o+'+'], // +
    [p-1,o+'-'], // -
    [p*p,o+'s']): // s
 o+'o' // output this char
)([p,'']) // search starts from empty code output previous value
).join`` // join codes for each char

```

---

# Python 3.9, 137 bytes

```
p=0
for n in input():
 q=[[p,'']]
 for p,o in q:
  if chr(p:=p%256)==n:print(end=o+'o');break
  q[:]+=[p+1,o+'+'],[p-1,o+'-'],[p*p,o+'s']

```

Try it online!

The TIO link is 139 bytes by changing the last line `q[:]` into `q[-1:]`. The code still works without the `-1` there on my computer, it only takes much longer time (timeout on TIO). And I don't know why `-1` may help the performance.

It is shorter than the mojibake like JavaScript.

---

# Python 3.8, 162 bytes

```
p=0
for n in input():
 q,v=[[p,'']],[1]*256
 for p,o in q:
  if chr(p:=p%256)==n:print(end=o+'o');break
  q[:],v[p]=q+[[p+1,o+'+'],[p-1,o+'-'],[p*p,o+'s']]*v[p],0

```

Try it online!

And 162 bytes version for better performance.
> 4 votes

# Answer
# JavaScript (V8), 187 bytes

*-12 thanks to @Ausername*

```
s=>eval('i=0;do{c=i.toString(4).padStart(Math.log2(++i)/2+1,0,o=""),(a=[...c]).reduce((r,x)=>[r+1,r+255,r*r,r,x^3||(o+=String.fromCharCode(r))][x]%256,0)}while(o!=s);a.map(d=>"+-so"[d])')

```

Try it online!

**Description:**

Shameless brute-forcing. Increments a number, and converts it to base 4. It then interprets it as imnotdeadfish, and stops as soon as the result is equal to the input. Add `n` to the first `0` for infinitely large inputs. Didn't do this because it causes TIO to error.
> 3 votes

# Answer
# Jelly, ~~43~~ 34 bytes

```
‘;’;²&255
OŻ¹Çi?ƬFiɗƝ’ḃ3ị“+-s”Up”o

```

Try it online!

A full program taking a string argument and printing the resulting program to STDOUT. For each pair of characters (prepended with a null byte) progressively extends a list by applying each of the three operations, preserving intermediate values, until the second integer is found. The position of the second integer in the flattened list is then base decoded into "+-s" and appended with "o" to yield the imnotdeadfish program.

Now works for longer inputs, because this is more efficient than the previous approach.

Full explanation to follow.
> 2 votes

# Answer
# , 174 bytes

```
\(x,p=paste0)p(mapply(\(y,z){l="";while(is.na(m<-match(z,y))){l=c(outer(l,c("+","-","s"),p));y=c(y+1,y-1,y^2)%%256};l[m]},c(0,(u=utf8ToInt(x))[-nchar(x)]),u),"o",collapse="")

```

Try it online!

A function that takes a string and returns the iamnotdeadfish program as a string
> 2 votes

# Answer
# Charcoal, 77 bytes

```
≔⁰θＦＥＳ℅ι«≔Ｅ²⁵⁶⎇⁼κθω#ηＦ¹⁴ＦΦＬη¬⁼#§ηλＦ³«≔§⟦⊕λ⊖λ×λλ⟧μκ¿⁼#§ηκ§≔ηκ⁺§ηλ§+-sμ»§ηιo≔ιθ

```

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

```
≔⁰θ

```

Initialise the accumulator to zero.

```
ＦＥＳ℅ι«

```

Loop over the code points of the input.

```
≔Ｅ²⁵⁶⎇⁼κθω#η

```

Create an array of the command strings found so far (the empty string for the current accumulator and a marker `#` for all of the other values).

```
Ｆ¹⁴

```

Repeat enough times to ensure all possible values are covered. (I could save a byte by looping 1,000 times but that would make the code unusable on TIO. On the other hand repeating until we found the value we wanted would be faster still. Try it online!)

```
ＦΦＬη¬⁼#§ηλ

```

Loop over the values of the command strings found so far.

```
Ｆ³«

```

Loop over the three possible commands.

```
≔§⟦⊕λ⊖λ×λλ⟧μκ

```

Get the result of applying the command to the current value. No need to reduce modulo 256 here because Charcoal's array indexing is automatically cyclic.

```
¿⁼#§ηκ

```

If there is no command string for this value yet, then...

```
§≔ηκ⁺§ηλ§+-sμ

```

... save the new command string.

```
»§ηιo

```

Output the desired command string.

```
≔ιθ

```

Update the accumulator.

I also wrote a program to enumerate all possible snippets for all values. This version uses the results to solve the original problem in near-constant time.

```
≔Ｅ²⁵⁶Ｅ²⁵⁶⎇⁼ιλω#θ≔Ｅ²⁵⁶⟦⟦+﹪⊕κ²⁵⁶⟧⟦-﹪⊖κ²⁵⁶⟧⟧ηＦ²⁵⁶«Ｆ¬⁼ι﹪×ιι²⁵⁶⊞§ηι⟦s﹪×ιι²⁵⁶⟧Ｆ§ηι§≔§θι§κ¹§κ⁰»≔ＥηιζＷΦθ№κ#ＦＥι⌕κω«≔⟦⟧εＦ§ζκＦ§η§λ¹Ｆ⁼#§§θκ§μ¹«§≔§θκ§μ¹⁺§λ⁰§μ⁰⊞ε⟦⁺§λ⁰§μ⁰§μ¹⟧»¿ε§≔ζκε»≔⁰δＦＳ«≔℅ιι§§θδιo≔ιδ

```

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

Using that code I was able to find some trivia e.g. the longest snippets are from `0` or `128` to `180` or `181`; these take 14 commands (not including the trailing `o`). For printable ASCII there are a number of equally longest snippets, but the most interesting worst case is from space to comma where it's not possible to improve on simply incrementing 12 times.
> 1 votes

# Answer
# Julia 0.5, 119 bytes

```
^(s,l=0,L=[""])=s==""?s:any((i=l.==(b=Int[s[1]]);))?L[i][]"o"s[2:end]^b:^(s,[l+1;l+255;l.*l]%256,vec(L.*["+" "-" "s"]))

```

Try it online!

##### ungolfed:

```
function ^(s,l=0,L=[""])
    s == "" && return ""
    b = Int[s[1]]
    i = l .== b
    if any(i)
        return L[i][1] * "o" * ^(s[2:end], b)
    else
        return ^(s, [l.+1; l.+255; l.*l].%256, vec(L.*["+" "-" "s"]))
    end
end

```

Try it online!
> 1 votes

---
Tags: code-golf, code-generation, deadfish
---


title: Let's play tennis 2: east-west game

text:
# Question
Title: Let's play tennis 2: east-west game
There is a challenge Let's play tennis by Daniel. He proposes to place a court in the North-South direction. My proposal is to create a court to play tennis in the East-West direction too.

You have to print a tennis court, but you have to do it in the fewest bytes possible because of confidential reasons.

## Tennis court

```
------x------
|  |  x  |  |
|  |--x--|  |
|  |  x  |  |
------x------

```

Original rules are:

* No extra spaces.
* No tabs as they would be unfair.
* One optional trailing newline is allowed.

## This is , so shortest code in bytes wins!

# Answer
# Canvas, ~~13~~ 12 bytes

```
«ω↕9:gＷ：ｔＣ‟┼

```

quad-palindromizes a compressed corner of the field.

Try it here!

11 bytes with uppercase `X`es, using the fact that `/` compresses better than `x` and palindromizing would result in overlapping `/` and its mirror `\`, which results in `X`
> 6 votes

# Answer
# Python 2, 59 bytes

```
s="------x------\n|  |  x  |  |\n|  |--x"
print s+s[-2::-1]

```

Try it online!

Prints the first half of the string followed by its reverse. It's boring but efficient. I tried extracting repeating parts of out `s`, especially the `-`, but didn't find anything shorter.

---

**Python 2, 59 bytes**

```
for n in 6,0,2,0,6:x='-'*n+'  |  |'[n:];print x[::-1]+'x'+x

```

Try it online!

Using Jo King's construction.

---

**Python 2, 62 bytes**

```
b='|  '*2
for r in'-'*6,b,'|  |--',b,'-'*6:print r+'x'+r[::-1]

```

Try it online!

Prints the first half of each line, followed by `'x'`, followed by the first half reversed.
> 10 votes

# Answer
# Charcoal, 15 bytes

```
↑²←⁶↓xx→x²↑²‖Ｏ¬

```

Try it online! Link is to verbose version of code. By way of explanation I will show the result after each of the drawing commands up to the final reflection:

```
↑²        |
          |

     ------
←⁶        |
          |

    x------
↓xx x     |
          |

    x------
→x² x     |
    x--   |

    x------
↑²  x  |  |
    x--|  |

```
> 7 votes

# Answer
# Python 3, ~~65~~ 62 bytes

```
for n in 7,0,3,0,7:x="-"*n+"|  "*5;print(x[6:0:-1]+'x'+x[1:7])

```

Try it online!
> 4 votes

# Answer
# Dyalog APL, 36 bytes

```
(⌽,'x',⊢)(⊢⍪'--|  |'⍪⊖)'-'⍪1 6⍴'  |'

```

Try it online!

With a little help from Adám
> 3 votes

# Answer
# Python 3, 75 bytes

```
s='-'*6;p='|  |';w=s+'x'+s;a=p+'  x  '+p;print(w,a,p+w[4:9]+p,a,w,sep='\n')

```

Probably golfable - I've never really tried challenges before.

Try it online!

In Python 2 I could get it to **76 bytes**

```
s='-'*6;p='|  |';w=s+'x'+s;a=p+'  x  '+p
for i in w,a,p+w[4:9]+p,a,w:print i

```
> 2 votes

# Answer
# Perl 5, 55 bytes

```
say$_,x,~~reverse for('-'x6,'|  'x2,'|  |--')[0..2,1,0]

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog Classic), 35 bytes

```
' |-x'[(⍉⊖⍪1∘↓)⍣2⍉3⍪2,⍨676 28⊤⍨6⍴3]

```

Try it online!
> 2 votes

# Answer
# Pip `-l`, ~~42~~ ~~39~~ 34 bytes

```
RV@<P"|  |".[s'-]X2PE'-X6M_.'x.RV_

```

Try it online!

---

Alternate solution, also 34 bytes:

```
RV@<P"-0|  0|  |--"^0M_@<16RA6,t'x

```

Try it online!
> 1 votes

# Answer
# Python 2, ~~69~~ ~~68~~ 66 bytes

*-2 thanks to Jo King*

```
for l in"-","|  ","|  |--","|  ","-":l*=6;print l[:6]+"x"+l[5::-1]

```

Try it online!

We cycle the following three patterns infinitely (6 times is sufficiently infinite for our purposes) and slice off the first 6 characters of each: `-`, `|` , and `| |--`. Then, to get the tennis court, we concatenate an `x` and the reverse of each line.
> 1 votes

# Answer
# 05AB1E, ~~25~~ 24 bytes

```
"
 -x|"•L®y[Â-Γ•5вèJ.º.∊

```

Try it online.

**~~25~~ 24 bytes alternative:**

```
… -|•B°”Ñ•3вèJ3ä'x«».º.∊

```

Try it online.

**Explanation:**

```
"\n -x|"       # Push string "\n -x|"
•L®y[Â-Γ•      # Push compressed number 5960566858660563
         5в    # Converted to Base-5 as list:
               #  [2,2,2,2,2,2,3,0,4,1,1,4,1,1,3,0,4,1,1,4,2,2,3]
è              # Index each digit into the string
 J             # And join the list together
               #  "\n -x|" and [2,2,2,2,2,2,3,0,4,1,1,4,1,1,3,0,4,1,1,4,2,2,3]
               #   → "------x\n|  |  x\n|  |--x"
.º             # Intersect mirror everything horizontally
  .∊           # Intersect mirror everything vertically (and output implicitly)

… -|           # Push string " -|"
•B°”Ñ•         # Push compressed integer 193812448
      3в       # Converted to Base-3 as list: [1,1,1,1,1,1,2,0,0,2,0,0,2,0,0,2,1,1]
è              # Index each digit into the string
 J             # And join the list together
               #  " -|" and [1,1,1,1,1,1,2,0,0,2,0,0,2,0,0,2,1,1]
               #   → "------|  |  |  |--"
3ä             # Split the string into three parts: ["------","|  |  ","|  |--"]
  'x«         '# Append an "x" to each: ["------x","|  |  x","|  |--x"]
     »         # Join by newlines: "------x\n|  |  x\n|  |--x"
.º             # Intersect mirror everything horizontally
  .∊           # Intersect mirror everything vertically (and output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•L®y[Â-Γ•` is `5960566858660563` and `•B°”Ñ•` is `193812448`.

Thanks to *@MagicOctopusUrn*'s ASCII-art generator for `•L®y[Â-Γ•5BžLR"\n -x|"‡` and `•B°”Ñ•3BžLR" -|"‡`, after which the transliterate has been golfed further by swapping the number and string on the stack, use `в` instead of `B`, and index into the string with `è`.
> 1 votes

# Answer
# , 53 bytes

```
echo|:'x'(<6)}'-'(<2;~4+i.5)}13$3 5$'-|||',11$'--   '

```

Try it online!
> 1 votes

# Answer
# MBASIC, 82 bytes

```
1 WIDTH 13:PRINT"------x------|  |  x  |  ||  |--x--|  ||  |  x  |  |------x------

```

Abusing the WIDTH directive saved me around 20 bytes.
> 1 votes

# Answer
# Stax, 19 bytes

```
⌡x♠=Γτ^┼¢Δ¶─êiö$≥⌐▓

```

Run and debug it
> 1 votes

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

```
+"x-| "@4\509 425 477 0@4\17218113

```

Try it online!

Port of K4 answer. 2 bytes saved with the `4\`, 1 byte lost due to the `+`
> 1 votes

# Answer
# Bubblegum, 28 bytes

```
00000000: d3d5 0581 0a30 a9cb 55a3 a000 4415 60b2  .....0..U...D.`.
00000010: 06cc 03cb c179 0839 5d14 7d00            .....y.9].}.

```

Try it online!
> 0 votes

# Answer
# Jelly, 22 bytes

```
“Þḅ“ H“ \’ṃ“-|x ”ŒBŒḄY

```

**Try it online!**
> 0 votes

# Answer
# , 25 bytes

```
13é-Äï5I  |<esc>ÄÙ4l5r-Îd^ãrx

```

Try it online!

Hexdump:

```
00000000: 3133 e92d c4ef 3549 2020 7c1b c4d9 346c  13.-..5I  |...4l
00000010: 3572 2dce 645e e372 78                   5r-.d^.rx

```

Here was my process:

```
13é-Äï5I  |<esc>3<<ÄÙ4l5r-Gã<C-v>ërx
13é-Äï5I  |<esc>3<<ÄÙ4l5r-Î7|rx
13é-Äï5I  |<esc>3<<ÄÙ4l5r-Îãrx
13é-Äï5I  |<esc>ÄÙ4l5r-Îd^ãrx

```

Alternate version:

```
5I  |<esc>5ÄM4l5r-HÒ-G.Îxxãrx

```

Hexdump:

```
00000000: 3549 2020 7c1b 35c4 4d34 6c35 722d 48d2  5I  |.5.M4l5r-H.
00000010: 2d47 2ece 7878 e372 780a                 -G..xx.rx.

```
> 0 votes

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

```
(a='----',A='|  |',b='--x--',B='  x  ')=>[p=a+b+a,q=A+B+A,A+b+A,q,p].join`
`

```

Try it online!

* 68 bytes if array of strings allowed.

---

# JavaScript (Node.js), 75 bytes

```
_=>[p='x---',q='x|  ','x| -',q,p].map(c=>[...'1221330331221'].map(d=>c[d]))

```

Try it online!

* This one output 2d char array. I don't know if it can be golfed further more.
> 0 votes

# Answer
# Red,98 80 bytes

```
foreach r[1 2 3 2 1][print pick["------x------""|  |  x  |  |""|  |--x--|  |"]r]

```

Try it online!
> 0 votes

# Answer
# Powershell, ~~60~~ 59 bytes

*-1 bytes thanks @AdmBorkBork*

```
('------x------','|  |  x  |  |','|  |--x--|  |')[0,1+2..0]

```
> 0 votes

# Answer
# Pyth, 32 bytes

```
t_ps@L"x-
| "jC"??ôkË7"5

```

Try it online here. The above code contains some odd characters, so copying/pasting probably won't work.

Prints the first half of the pattern, followed by its reverse without the central `x`.

```
t_ps@L"x-\n| "jC"..."5   Note newline replaced with \n, encoded string replaced with ...

               C"..."    Convert encoded string to base 256 number 727558509253668163499780
              j      5   Convert to base 5, yields [1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 2, 3, 4, 4, 3, 4, 4, 0, 4, 4, 3, 4, 4, 3, 2, 3, 4, 4, 3, 1, 1, 0]
    @L                   Map each of the above to...
      "x-\n| "           ... [x, -, newline, |, space]
   s                     Concatenate into string
  p                      Print without newline
 _                       Reverse
t                        All but first character, implicit print

```
> 0 votes

# Answer
# C# (.NET Core), 88 bytes

```
string a="------x------\n",b="|  |  x  |  |\n";Console.Write(a+b+"|  |--x--|  |\n"+b+a);

```

Try it online!

Ungolfed:

```
string a = "------x------\n",
       b = "|  |  x  |  |\n";
Console.Write(a + b + "|  |--x--|  |\n" + b + a);

```

---

Here's an alternate way to do it with an anonymous function based on adrianmp's answer from the first Let's Play Tennis thread:

# C# (.NET Core), 88 bytes

```
()=>{string a="------x------\n",b="|  |  x  |  |\n";return(a+b+"|  |--x--|  |\n"+b+a);};

```

Try it online!

Ungolfed:

```
() =>
{
    string a = "------x------\n",
           b = "|  |  x  |  |\n";
    return(a + b + "|  |--x--|  |\n" + b + a);
};

```
> 0 votes

# Answer
# K4, ~~36~~ 35 bytes

**Solution:**

```
"x-| "@4\:509 425 477 0@4\:17218113

```

**Example:**

```
q)k)"x-| "@4\:509 425 477 0@4\:17218113
"------x------"
"|  |  x  |  |"
"|  |--x--|  |"
"|  |  x  |  |"
"------x------"

```

**Explanation:**

We want to generate a list of indexes into the array `"x-| "`, e.g.

```
1 1 1 1 1 1 0 1 1 1 1 1 1
2 3 3 2 3 3 0 3 3 2 3 3 2
2 3 3 2 1 1 0 1 1 2 3 3 2
2 3 3 2 3 3 0 3 3 2 3 3 2
1 1 1 1 1 1 0 1 1 1 1 1 1

```

In order to generate this we can take the base-4 representation of the flip of these numbers. This gives us:

```
425 509 509 425 477 477 0 477 477 425 509 509 425

```

We can take the distinct values and index in at the indices we require:

```
q)509 425 477 0@1 0 0 1 2 2 3 2 2 1 0 0 1
425 509 509 425 477 477 0 477 477 425 509 509 425

```

This array `1 0 0 1 2 2 3 2 2 1 0 0 1` converted to base-4 is

```
q)k)4/:1 0 0 1 2 2 3 2 2 1 0 0 1
17218113

```

So for the solution, we are just doing these steps in reverse.

```
"x-| "@4\:509 425 477 0@4\:17218113 / the solution
                        4\:17218113 / convert 17218113 into base-4
          509 425 477 0@            / index (@) into 509 425 477 0
       4\:                          / convert to base-4
"x-| "@                             / index (@) into "x-| "

```
> 0 votes

# Answer
# ///, 46 bytes

```
/#/
!  x  !
//"/------//!/|  |/"x"#!--x--!#"x"

```

Try it online!
> 0 votes

# Answer
# Vyxal `j`, 22 bytes

```
»°₈q8»`|- `τ3/\x+ømvøm

```

Try it Online!

## Alternative 22 bytes

```
»ƛ\¶≤NV»`x-| `τ3/ømvøm

```

Try it Online!
> 0 votes

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