# Question
Title: Output all distinct permutations of a vector
### Challenge:

Output all distinct permutations of a, potentially long, list of positive integers. You may assume that the vector has less than 1,000 numbers when testing, but the process should in theory work for any vector with more than one number regardless of size.

**Restrictions:**

* You must restrict the memory usage to **O(n^2)**, where **n** is the number of elements in the input vector. You can't have **O(n!)**. That means you can't store all permutations in memory.
* You must restrict the time complexity to **O(result size * n)**. If all numbers are equal, then this will be **O(n)**, and if all are distinct, then this will be **O(n!\*n)**. That means you can't create a permutation and check it against all other permutations to ensure distinctness (that would be **O(n!^2\*n)**).
* Empirical measurements to show that time and memory restrictions are met are accepted.
* You must actually print/output the permutations (since it's impossible to store them).

If you run your program long enough, then all permutations should be outputted (in theory)!

**Distinct permutations:**

The list **\[1, 1, 2\]** has three permutations, not six: **\[1, 1, 2\]**, **\[1, 2, 1\]** and **\[2, 1, 1\]**. You may choose the order of the output.

---

## Manageable test cases:

```
Input:
[1, 2, 1]
Output:
[1, 1, 2]
[1, 2, 1]
[2, 1, 1]

Input:
[1, 2, 3, 2]
Output:
[1, 2, 2, 3]
[1, 2, 3, 2]
[1, 3, 2, 2]
[2, 1, 2, 3]
[2, 1, 3, 2]
[2, 2, 1, 3]
[2, 2, 3, 1]
[2, 3, 1, 2]
[2, 3, 2, 1]
[3, 1, 2, 2]
[3, 2, 1, 2]
[3, 2, 2, 1]

Input:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Output:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

```

### Larger test case:

It's impossible to output all permutations for this one, but it should work in theory if you gave it enough time (but not unlimited memory).

```
Input:
[1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900]

```

---

You must explain how you know that all permutations are distinct, and that all permutations will be printed, eventually.

This is so the shortest code in bytes win.

# Answer
> 6 votes
## JavaScript (ES6), ~~177~~ 169 bytes

```
a=>{s=''+a
do{console.log(a)
k=a.findIndex((e,i)=>a[i-1]>e)
if(~k)t=a[k],a[k]=a[l=a.findIndex(e=>e>t)],a[l]=t,a=a.map((e,i)=>i<k?a[k+~i]:e)
else a.reverse()}while(a!=s)}

```

Uses the well-known next lexicographic permutation generation algorithm, which I believe has memory O(len(array)) and time O(len(array)\*len(output)). (Note that the array elements are considered to be in reverse order, so that e.g. `2, 2, 1, 1` will enumerate to `2, 1, 2, 1`; `1, 2, 2, 1` etc.

# Answer
> 5 votes
# Python 3 with sympy, (50?) 81 bytes

```
lambda a:[print(v)for v in sympy.iterables.multiset_permutations(a)]
import sympy

```

**Try it online!**

**50 bytes** if a generator function is acceptable:

```
import sympy
sympy.iterables.multiset_permutations

```

The implementation is open source and currently available on git hub, at the time of writing the function is at line 983.

I think it does, but do let me know if it does not, fulfil the asymptotic bounds.

---

### Python 2, (411?) 439 bytes

A golfed version (also ignoring cases we are not required to cover) in Python 2 (still using the built-in `itertools.permutations function`) comes in at 439 bytes, or 411 with no additional boilerplate to print rather than generate (the `for v in h(input()):print v`):

```
from itertools import*
def h(a,z=-1,g=1):
 x=[v for v in[g,[[v,a.count(v)]for v in set(a)]][g==1]if 0<v[1]];S=sum([v[1]for v in x])
 if x==x[:1]:k,v=x[0];yield[k for i in range([[0,z][z<=v],v][z<1])]
 elif all(v<2for k,v in x):
    for p in permutations([v[0]for v in x],[z,None][z<0]):yield list(p)
 else:
    z=[S,z][z>-1];i=0
    for k,v in x:
     x[i][1]-=1
     for j in h([],z-1,x):
        if j:yield[k]+j
     x[i][1]+=1;i+=1
for v in h(input()):print v

```

(note: this uses the Python 2 golf of alternating tab and spaces for indents)

# Answer
> 3 votes
# JavaScript (Node.js), ~~137~~ ~~128~~ 123 bytes

```
s=>f(x=c=[],s.map(g=i=>g[i]=-~g[i]));f=i=>Object.keys(g).map(i=>g(i,--g[i]||delete g[i],f(x[c++]=i),c--))<1&&console.log(x)

```

Try it online!

```
s=>
    f(
        x=c=[],
        s.map(g=i=>g[i]=-~g[i]) // O(n) if all same, <=O(n^2) if different
    )
;
f=i=>
    Object.keys(g).map( // for(i in g) breaks when other items get removed
        i=>g(
            i,
            --g[i]||delete g[i], // O(left possible numbers)<O(child situations)
            f(x[c++]=i),
            c--
        )
    )<1
&&
    console.log(x)

```

# Answer
> 2 votes
# C++ (gcc), 203 bytes

Apparently C++ has this as a builtin function...

```
#import<bits/stdc++.h>
using namespace std;main(){vector<int>v;int x;while(cin>>x)v.push_back(x);sort(v.begin(),v.end());do{for(int y:v)cout<<y<<' ';puts("");}while(next_permutation(v.begin(),v.end()));}

```

Try it online!

Ungolfed code: TIO link.

This use `O(n)` memory (guaranteed by `std::vector`) and optimal runtime.

Some optimizations in code:

* Use `import` instead of `include` (G++ deprecated extension)
* Use `bits/stdc++.h` (precompiled header contains all other headers) instead of multiple necessary headers. Often this makes compile time slower.
* `using namespace std` which is known to be a bad idea.
* Use `puts("")` instead of `cout<<'\n'` for writing a newline. This is normal for C program, but feels weird for me. So I think this should be mentioned.
* `main` return value (`int`) can be omitted.

Otherwise (apart from whitespace deletion) it's the same way how I often program in C++.

Some possible optimizations: (I don't know if that is allowed by default):

* Enter array size before enter elements. This will allow dynamic-size array, overall save 30 bytes.
* Not separate the outputs with separators. So the output will like `1 1 2 3 1 1 3 2 1 2 1 3 1 2 3 1 1 3 1 2 1 3 2 1 2 1 1 3 2 1 3 1 2 3 1 1 3 1 1 2 3 1 2 1 3 2 1 1` for `1 2 1 3`. This allows save more 9 bytes.
* While in C it is allowed to omit headers, I don't know if there is a shorter way to use those functions without `#import` the headers in C++, or a shorter header name.

# Answer
> 2 votes
# Scala (48 bytes)

```
def%(i:Seq[Int])=i.permutations.foreach(println)

```

Try it online

permutations returns an iterator over distinct permutations.

# Answer
> 0 votes
# APL(NARS), 156 chars, 312 bytes

```
r←d F w;i;k;a;m;j;v
r←w⋄→0×⍳1≥k←↑⍴w⋄a←⍳k⋄j←i←1⋄r←⍬⋄→C
A: m←i⊃w⋄→B×⍳(i≠1)∧j=m
   v←m,¨(d,m)∇w[a∼i]
   →H×⍳0=↑⍴v⋄⎕←∊d,v
H: j←m
B: i+←1
C: →A×⍳i≤k

G←{⍬F⍵[⍋⍵]}

```

They, F and G would be 2 function to use togheter... G first order the array than apply to the that ordined array the function F and write permutations using the observation that if the element is already found, better not to go to recursion (because all the result would be already found). I don't know if this fit all restritions... Test:

```
  G 1 1 2
1 1 2
1 2 1
2 1 1

  G 1 2 3 2
1 2 2 3
1 2 3 2
1 3 2 2
2 1 2 3
2 1 3 2
2 2 1 3
2 2 3 1
2 3 1 2
2 3 2 1
3 1 2 2
3 2 1 2
3 2 2 1

  G 'abb'
abb
bab
bba

```

---
Tags: code-golf, number, permutations, restricted-complexity, restricted-time
---


title: Find the closest RGB color

text:
# Question
Title: Find the closest RGB color
Input: A valid 6 HEX digit color code wihout a # prefix
Valid:

> * 000000
> * FF00FF
> * ABC123

Your job is to find to which one of these:

```
Red:   FF0000
Green: 00FF00
Blue:  0000FF
White: FFFFFF
Black: 000000

```

the input color is the closest too, in this case you try to only match it to black or white when the RGB is the same value for all 3 (the color is grey, or black or white ofc), if there is a "tie" you can pick whichever

The output is one of the aforementioned color codes. Examples:

```
Input: FF0000, Output: FF0000
Input: F10000, Output: FF0000
Input: 22FF00, Output: 00FF00
Input: FFFF00, Output: FF0000 or 00FF00
Input: 111112, Output: 0000FF
Input: 010101, Output: 000000
Input: A0A0A0, Output: FFFFFF

```

This is , so fewest bytes will win!

# Answer
> 1 votes
# 05AB1E, ~~32~~ ~~31~~ 30 bytes

```
3äHDËiнžy@Di'F}6∍ë¾5∍sZk·„FFsǝ

```

Not really happy with it, so will see if I can golf it further..

When two `RGB` parts are the largest and equal, it will use the first one (i.e. `11ABAB` will result in `00FF00`). When all three parts are equal it will output `000000` when it's the range `[00,7F]` and `FFFFFF` for the range `[80,FF]`.

Try it online or verify all test cases.

**Explanation:**

```
3ä                  # Split the (implicit) input into three parts
  H                 # Convert each part from Hexadecimal to a base-10 decimal
   D                # Duplicate this list
    Ëi              # If all three values are equal:
      н             #  Leave only the first item of the list
       žy@          #  Check if it's larger than or equal to 128 ("80" in hex)
          D         #  Duplicate this truthy/falsey result
           i  }     #  If the result is truthy:
            'F     '#   Push "F"
                    #  (Implicit else:)
                    #   (Take the duplicated falsey 0)
               6∍   #  Lenghten it to size 6
     ë              # Else:
      ¾5∍           #  Push 0, lenghtened to size 5: "00000"
         s          #  Swap so the duplicated list is at the top of the stack
          Z         #  Take the max (without popping)
           k        #  Take the index of this max in the list
            ·       #  Double this index
             „FFsǝ  #  Replace the "0" in "00000" at this doubled index with "FF"
                    # (And output the top of the stack implicitly as result)

```

# Answer
> 3 votes
# Python 3, ~~163 162~~ 150 bytes

*-1 byte thanks to Kevin Cruijssen*

*-12 bytes by some small tricks (thanks to HyperNeutrino for the* `"0F"[bool]` *idea)*

```
def f(i):m=i[:2],i[2:4],i[4:];a,b,c=(e==max(m)for e in m);return"".join("0F"[e]*2for e in([i[:2]>"7E"]*3if a&b&c else([a,b,c]if a^b^c else[a,1^a,0])))

```

Try it online!

I was able to find a solution without turning the three hex values to integers (mainly because 'A' comes later in the ASCII table than '9', and so '9'\<'A' is true). I am not really happy with some parts, but this was the shortest I could find.

Because this solution uses a different approach than the other python3 solution, I'm posting this as a seperate answer.

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

```
s=>'00FF000000FFFFFF'.substr(([r,g,b]=s.match(/../g),r+g==g+b?r<'8'?4:10:r>b?r>g&&2:b>g&&6),6)

```

Try it online!

### How?

We could convert a bitmask to upper case hexadecimal with leading zeros using:

```
.slice(1).toString(16).toUpperCase()

```

But that would cost 36 bytes, and building such a bitmask is not especially cheap either.

It's significantly shorter to extract the relevant substring from `"00FF000000FFFFFF"`, using the following offsets:

```
 pattern | offset | 00FF000000FFFFFF
---------+--------+------------------
 000000  |    4   |     ^^^^^^
 FFFFFF  |   10   |           ^^^^^^
 FF0000  |    2   |   ^^^^^^
 00FF00  |    0   | ^^^^^^
 0000FF  |    6   |       ^^^^^^

```

# Answer
> 1 votes
# Python 3, ~~219~~ ~~112~~ 110 bytes

```
def f(s):h=max([0,1,2],key=lambda i:s[i*2:][:2]);return["00"*h+"FF"+"00"*(2-h),"F0"[s[:2]<"80"]*6][s==s[:2]*3]

```

Try it online!

-107 bytes by not being bad; drew a bit of inspiration from @Heitera by avoiding input integer parsing entirely.
-2 bytes thanks to @Heitera

---
Tags: code-golf, string, color
---


title: Validate a barcode

text:
# Question
Title: Validate a barcode
A barcode of EAN-13 symbology consists of 13 digits (0-9). The last digit of this barcode is its check digit. It is calculated by the following means (the barcode `8923642469559` is used as an example):

1. Starting from the second digit, sum up all alternating digits and multiply the sum by 3:

```
8 9 2 3 6 4 2 4 6 9 5 5 9
  |   |   |   |   |   |
  9 + 3 + 4 + 4 + 9 + 5 = 34
                           |
                           34 × 3 = 102

```
2. Then, sum up all of the remaining digits, but do not include the last digit:

```
8 9 2 3 6 4 2 4 6 9 5 5 9
|   |   |   |   |   |
8 + 2 + 6 + 2 + 6 + 5 = 29

```
3. Add the numbers obtained in steps 1 and 2 together:

```
29 + 102 = 131

```
4. The number you should add to the result of step 3 to get to the next multiple of 10 (140 in this case) is the check digit.

If the check digit of the barcode matches the one calculated as explained earlier, the barcode is valid.

---

More examples:

`6537263729385` is valid. `1902956847427` is valid. `9346735877246` is invalid. The check digit should be 3, not 6.

---

Your goal is to write a program that will:

1. Receive a barcode as its input.
2. Check whether the barcode is valid
3. Return 1 (or equivalent) if the barcode is valid, 0 (or equivalent) otherwise.

---

This is , so the shortest code in terms of bytes wins.

# Answer
# Ruby, ~~45 40~~ 37 bytes

```
->n{(n+n.scan(/.(.)/)*''*2).sum%10<1}

```

Try it online!
> 5 votes

# Answer
# Python 3, 55 bytes

```
lambda s:not sum(int(i)*d for i,d in zip(s,[1,3]*7))%10

```

Try it online!
> 2 votes

# Answer
# 05AB1E, ~~15~~ 10 bytes

```
εNÉ·>*}OTÖ

```

Try it online!

**Explanation**

```
    ε     }      # apply to each digit
     NÉ          # is the current index odd?
       ·>        # double and increment(yielding 1 or 3)
         *       # multiply by the current number
           O     # sum all modified digits
            TÖ   # is evenly divisible by 10

```
> 2 votes

# Answer
# Jelly, 10 bytes

```
D0;s2Sḅ3⁵ḍ

```

Try it online!

-4 bytes thanks to Kevin Cruijssen (semi-port @Dennis)
> 1 votes

# Answer
# Japt `-!`, 14 bytes

```
¬Ë*(Ev ª3Ãx %A

```

---

```
¬Ë*(Ev ª3Ãx %A  Full prgram.
¬               Convert to array -_-
 Ë              Map
  *             Multiply current number by
   (Ev ª3Ã      1 if index is even, else 3
          x     sum
           %A   mod 10?

```

Try it online!
> 1 votes

# Answer
# Perl 6, ~~29~~ 26 bytes

```
{:1[.comb «*»(1,3)]%%10}

```

Try it online!

-3 bytes if a list of digits is acceptable.

### Explanation

```
{                      }  # Anonymous Block
    .comb                 # Split into characters
          «*»(1,3)        # Multiply with 1 and 3 alternately
 :1[              ]       # Sum (conversion from base 1 is shorter than sum())
                   %%10   # Check if divisible by 10

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 34 bytes

```
Check[#~BarcodeImage~"EAN13";1,0]&

```

Try it online!

A port of my EAN-8 answer.
> 1 votes

# Answer
# Java 8, ~~69~~ ~~67~~ 62 bytes

```
n->{int s=0,m=3;for(;n>0;n/=10)s+=n%10*(m^=2);return s%10<1;}

```

-5 bytes thanks to *@OlivierGrégoire*.
-1 byte thanks to my own 1-year old answer for the *Is my barcode valid?* challenge, and *@OlivierGrégoire* to remind me of it.. xD

Try it online.

**Explanation:**

```
s->{               // Method with long parameter and boolean return-type
  int s=0,         //  Sum, starting at 0
      m=3;         //  Multiplier, starting at 3
  for(;n>0;        //  Loop as long as the input is not 0 yet
      n/=10)       //    After every iteration: integer-divide the input by 10
    s+=            //   Increase the sum by:
      n%10*        //    The last digit of the input multiplied by:
       (m^=2);     //    either 1 or 3 (alternating every iteration)
  return s%10<1;}  //  Then return whether the sum is divisible by 10

```
> 1 votes

# Answer
# Retina 0.8.2, ~~23~~ 22 bytes

```
.(.)
$&$1$1
.
$*
M`
1$

```

Try it online! Link includes test cases. Edit: Saved 1 byte thanks to Martin Ender's comment on @Leo's Retina answer to the EAN-8 question. Explanation:

```
.(.)
$&$1$1

```

Triplicate alternate digits.

```
.
$*

```

Convert each digit to unary.

```
M`

```

Count the number of character boundaries, which is one more than the number of characters.

```
1$

```

Check for divisibilty by 10, but allow for the 1 we just added.
> 1 votes

# Answer
# APL (Dyalog Unicode), 15 bytes

```
0=10|⊢+.×1 3⍴⍨≢

```

Try it online!

Anonymous train, outputs 1 for True and 0 for False. TIO links to a prettified version of the output.

Totally not helped at all by @ngn or @dzaima (thanks guys).

### How:

```
0=10|⊢+.×1 3⍴⍨≢ ⍝ Main fn
              ≢ ⍝ Tally the argument (will always be 13)
         1 3⍴⍨  ⍝ Reshape the vector (1 3) to 13 elements
     ⊢+.×       ⍝ Multiply the original vector by that, then sum
  10|           ⍝ Modulo 10
0=              ⍝ equals 0

```
> 1 votes

# Answer
# Python 2, 50 bytes

```
lambda x,k=1,a=0:f(x/10,4-k,a+x*k)if x else a%10<1

```

Try it online!
> 1 votes

# Answer
# Pyth, ~~11~~ 10 bytes

```
!es*V*jT7l

```

Accepts input as a list of digits. Try it online here, or verify all test cases at once here.

```
!es*V*jT7lQQ   Implicit: Q=eval(input())
               Trailing QQ implied
      jT7      10 in base 7 - yields [1,3]
     *   lQ    Repeat the above len(input) times
   *V      Q   Vectorised multiply the above with the input
  s            Take the sum
 e             % 10
!              Logical not

```

*Edit: saved a byte by replacing `,1 3` with `jT7`*
> 0 votes

# Answer
# , 65 bytes

```
function(b,y=b%/%10^(12:0)%%10)!sum(y[-1],y[(1:6)*2]*2)%%-10+y[1]

```

Try it online!
> 0 votes

---
Tags: code-golf, arithmetic
---


title: Write an IBAN validator

text:
# Question
Title: Write an IBAN validator
Write a program (the body of the function is enough) that accepts a string of alphanumeric characters and validates it according to ISO 13616:2007. The algorithm for validation is (source: wikipedia article on IBAN http://en.wikipedia.org/wiki/International\_Bank\_Account\_Number):

> Validating the IBAN An IBAN is validated by converting it into an integer and performing a basic mod-97 operation (as described in ISO 7064) on it. If the IBAN is valid, the remainder equals 1.The algorithm of IBAN validation is as follows:
>
> * Check that the total IBAN length is correct as per the country. If not, the IBAN is invalid. The correct IBAN lengths can be found here: http://pastebin.com/kp4eECVk (can also be found below), ordered by the length of the IBAN number. the first 2 characters of each number is the country code. All other characters (lowercase letters on the pastebin, but can be any case in the actual IBAN) behind the first 2 can be any alphanumeric character.
> * Move the four initial characters to the end of the string.
> * Replace each letter in the string with two digits,thereby expanding the string, where A = 10, B = 11, ..., Z = 35.
> * Interpret the string as a decimal integer and compute the remainder of that number on division by 97
>
> If the remainder is 1, the check digit test is passed and the IBAN might be valid.
>
> Example (fictitious United Kingdom bank, sort code 12-34-56, account number 98765432):
>
> ```
> - IBAN:               GB82 WEST 1234 5698 7654 32
> - Rearrange:          W E S T12345698765432 G B82
> - Convert to integer: 3214282912345698765432161182
> - Compute remainder:  3214282912345698765432161182    mod 97 = 1
>
> ```

The algorithm moest return true (or a truthy value) if the number is valid, and false (or a falsy value) if the number is invalid according to the algorithm. You do not need to check if the number actually exists, only if it's valid. The algorithm has to work for each of the different approved IBAN numbers mentioned in the wikipedia article above. The algorithm should be compatible with numbers both with or without separator characters between 2 alphanumeric characters. The separator character can either be periods, spaces or dashes and one number can contain different types of separators.

Usual loopholes apply: no external resources, no built-in functions or methods.

Puzzle type is code golf. Shortest code in bytecount wins. Standard boilerplate needed to execute the program (e.g. namespace, class, function declaration in OOP) is not included in the bytecount.

Bonus: if you can return the properly formatted IBAN number (according to the national format on wikipedia) instead of true in the case of a valid number, you get a 25% reduction in your score. If the number is invalid, you return a literal string with the value "Invalid".

---

Copy of the IBAN lengths in case the pastebin ever is removed:

```
Country;Chars;IBAN Fields
Norway;15;NOkk bbbb cccc ccx
Belgium;16;BEkk bbbc cccc ccxx
Burundi;16;BIkk nnnn nnnn nnnn
Denmark;18;DKkk bbbb cccc cccc cc
Faroe Islands;18;FOkk bbbb cccc cccc cx
Finland;18;FIkk bbbb bbcc cccc cx
Greenland;18;GLkk bbbb cccc cccc cc
Netherlands;18;NLkk bbbb cccc cccc cc
Macedonia;19;MKkk bbbc cccc cccc cxx
Slovenia;19;SIkk bbss sccc cccc cxx
Austria;20;ATkk bbbb bccc cccc cccc
Bosnia and Herzegovina;20;BAkk bbbs sscc cccc ccxx
Estonia;20;EEkk bbss cccc cccc cccx
Kazakhstan;20;KZkk bbbc cccc cccc cccc
Lithuania;20;LTkk bbbb bccc cccc cccc
Luxembourg;20;LUkk bbbc cccc cccc cccc
Costa Rica;21;CRkk bbbc cccc cccc cccc c
Croatia;21;HRkk bbbb bbbc cccc cccc c
Latvia;21;LVkk bbbb cccc cccc cccc c
Liechtenstein;21;LIkk bbbb bccc cccc cccc c
Switzerland;21;CHkk bbbb bccc cccc cccc c
Bahrain;22;BHkk bbbb cccc cccc cccc cc
Bulgaria;22;BGkk bbbb ssss ddcc cccc cc
Georgia;22;GEkk bbcc cccc cccc cccc cc
Germany;22;DEkk bbbb bbbb cccc cccc cc
Ireland;22;IEkk aaaa bbbb bbcc cccc cc
Montenegro;22;MEkk bbbc cccc cccc cccc xx
Serbia;22;RSkk bbbc cccc cccc cccc xx
United Kingdom;22;GBkk bbbb ssss sscc cccc cc
Gibraltar;23;GIkk bbbb cccc cccc cccc ccc
Israel;23;ILkk bbbn nncc cccc cccc ccc
United Arab Emirates;23;AEkk bbbc cccc cccc cccc ccc
Andorra;24;ADkk bbbb ssss cccc cccc cccc
Czech Republic;24;CZkk bbbb ssss sscc cccc cccc
Moldova;24;MDkk bbcc cccc cccc cccc cccc
Pakistan;24;PKkk bbbb cccc cccc cccc cccc
Romania;24;ROkk bbbb cccc cccc cccc cccc
Saudi Arabia;24;SAkk bbcc cccc cccc cccc cccc
Slovakia;24;SKkk bbbb ssss sscc cccc cccc
Spain;24;ESkk bbbb gggg xxcc cccc cccc
Sweden;24;SEkk bbbc cccc cccc cccc cccx
Tunisia;24;TNkk bbss sccc cccc cccc cccc
Virgin Islands;24;VGkk bbbb cccc cccc cccc cccc
Algeria;24;DZkk nnnn nnnn nnnn nnnn nnnn
Portugal;25;PTkk bbbb ssss cccc cccc cccx x
Angola;25;AOkk nnnn nnnn nnnn nnnn nnnn n
Cape Verde;25;CVkk nnnn nnnn nnnn nnnn nnnn n
Mozambique;25;MZkk nnnn nnnn nnnn nnnn nnnn n
Iceland;26;ISkk bbbb sscc cccc iiii iiii ii
Turkey;26;TRkk bbbb bxcc cccc cccc cccc cc
Iran;26;IRkk nnnn nnnn nnnn nnnn nnnn nn
France;27;FRkk bbbb bggg ggcc cccc cccc cxx
Greece;27;GRkk bbbs sssc cccc cccc cccc ccc
Italy;27;ITkk xaaa aabb bbbc cccc cccc ccc
Mauritania;27;MRkk bbbb bsss sscc cccc cccc cxx
Monaco;27;MCkk bbbb bsss sscc cccc cccc cxx
San Marino;27;SMkk xaaa aabb bbbc cccc cccc ccc
Burkina Faso;27;BFkk nnnn nnnn nnnn nnnn nnnn nnn
Cameroon;27;CMkk nnnn nnnn nnnn nnnn nnnn nnn
Madagascar;27;MGkk nnnn nnnn nnnn nnnn nnnn nnn
Albania;28;ALkk bbbs sssx cccc cccc cccc cccc
Azerbaijan;28;AZkk bbbb cccc cccc cccc cccc cccc
Cyprus;28;CYkk bbbs ssss cccc cccc cccc cccc
Dominican Republic;28;DOkk bbbb cccc cccc cccc cccc cccc
Guatemala;28;GTkk bbbb cccc cccc cccc cccc cccc
Hungary;28;HUkk bbbs sssk cccc cccc cccc cccx
Lebanon;28;LBkk bbbb cccc cccc cccc cccc cccc
Poland;28;PLkk bbbs sssx cccc cccc cccc cccc
Benin;28;BJkk annn nnnn nnnn nnnn nnnn nnnn
Ivory Coast;28;CIkk annn nnnn nnnn nnnn nnnn nnnn
Mali;28;MLkk annn nnnn nnnn nnnn nnnn nnnn
Senegal;28;SNkk annn nnnn nnnn nnnn nnnn nnnn
Brazil;29;BRkk bbbb bbbb ssss sccc cccc ccct n
Palestinian;29;PSkk bbbb xxxx xxxx xccc cccc cccc c
Qatar;29;QAkk bbbb cccc cccc cccc cccc cccc c
Ukraine;29;UAkk bbbb bbcc cccc cccc cccc cccc c
Jordan;30;JOkk bbbb nnnn cccc cccc cccc cccc cc
Kuwait;30;KWkk bbbb cccc cccc cccc cccc cccc cc
Mauritius;30;MUkk bbbb bbss cccc cccc cccc cccc cc
Malta;31;MTkk bbbb ssss sccc cccc cccc cccc ccc

```

# Answer
## J (294 - 73.5 = 220.5)

I've not counted the function definition (`f=:3 :0`...`)`) because it can be considered boilerplate, counting the whole block gives a score of **304 - 76 = 228**.

```
f=:3 :0
>((1=97|1".'x',~' '-.~":48-~k-7*64<k=.3&u:4|.b)*(#b)=15+1 i.~+/"1(2{.b)&E.;.2'NO.BEBI..DKFOFIGLNL.MKSI.ATBAEEKZLTLU.CRHRLVLICH.BHBGGEDEIEMERSGB.GIILAE.ADCZMDPKROSASKESSETNVGDZ.PTAOCVMZ.ISTRIR.FRGRITMRMCSMBFCMMG.ALAZCYDOGTHULBPLBJCIMLSN.BRPSQAUA.JOKWMU.MT.'){'Invalid';1}.;' '&,&.>_4<\b=.y-.' -.'
)

```

Tests:

```
   NB. invalid numbers
   f ''
Invalid
   f 'GB82 WEST 1234 5698 7654 31'
Invalid
   f 'NL82 WEST 1234 5698 7654 32'
Invalid

   NB. different separators and formatting
   f 'GB82.WEST.1234.5698.7654.32'
GB82 WEST 1234 5698 7654 32
   f 'GB82-WEST-1234-5698-7654-32'
GB82 WEST 1234 5698 7654 32
   f 'GB82WEST12345698765432'
GB82 WEST 1234 5698 7654 32
   f 'GB82 WEST 1234 5698 7654 32'
GB82 WEST 1234 5698 7654 32
   f 'GB.82-WE ST-12.345698.76-5432'
GB82 WEST 1234 5698 7654 32

   NB. wikipedia examples
   f 'GR16 0110 1250 0000 0001 2300 695'
GR16 0110 1250 0000 0001 2300 695
   f 'CH93 0076 2011 6238 5295 7'
CH93 0076 2011 6238 5295 7
   f 'SA03 8000 0000 6080 1016 7519'
SA03 8000 0000 6080 1016 7519
   f 'GB29 NWBK 6016 1331 9268 19'
GB29 NWBK 6016 1331 9268 19

```

Explanation:

* `b=.y-.' -.'`: remove any separators from the argument and store the result in `b`.
* `1}.;' '&,&.>_4<\b`: split `b` up in groups of four, add a space in front of every group, join the groups and remove the leading space. If `y` contained a valid IBAN number, this is its canonical representation (i.e. groups of four, separated by spaces, with the last group maybe having less than four elements).
* `(`...`){'Invalid';`: create an array with the string `Invalid` as element 0 and the formatted IBAN number as element 1. Select the right one based on whether the IBAN number is valid:

+ Check the length:
        - `'NO.BEBI.---.JOKWU.MT.'`: a list of all the country codes for each length, separated by dots
        - `+/"1(2{.b)&E.;.2`: group the string by the dots, and see which one contains the given country code (the first 2 elements of `b`).
        - `15+1 i.~`: find the index of the matching one and add `15` to find the length.
        - `(#b)=`: check it against the actual length of `b`.
    + Check the number:
        - `4|.b`: rotate `b` to the left by 4 (rearrange)
        - `k=.3&u:`: find the ASCII value for each number
        - `48-~k-7*64<k`: subtract 7 from each letter, then subtract 48 from all, giving the values
        - `1".'x',~' '-.~":`: format, remove spaces, add an 'x' at the end (for high-precision mode, which is necessary for large numbers), and turn it back into a number
        - `1=97|`: check if the number mod 97 equals 1.
* `>`: unbox the resulting string
> 4 votes

# Answer
# CJam, ~~151.5~~ 141.75 points

```
0000000: 6c22 202e 2d22 2d3a 512c 220f a86e 5136  l" .-"-:Q,"..nQ6
0000010: 1bff 75f6 e8e4 0b35 5dab f190 0d85 59c4  ..u....5].....Y.
0000020: 1938 4366 3d29 5eaa e879 024a 77d9 8baf  .8Cf=)^..y.Jw...
0000030: 5c16 3258 a4d2 4e6c 1a60 429f affa b8f4  \.2X..Nl.`B.....
0000040: 435d e706 457b 89a9 16b8 1d4b 08f7 9970  C]..E{.....K...p
0000050: eeb9 7467 f8e9 c935 33be 2467 3dd4 1afb  ..tg...53.$g=...
0000060: e2ec 20cc 99e4 2783 cb96 512d f9f8 7e75  .. ...'...Q-..~u
0000070: 7066 4307 2232 3536 6232 3762 2740 662b  pfC."256b27b'@f+
0000080: 2740 2f7b 5132 3c23 3126 217d 235f 573e  '@/{Q2<#1&!}#_W>
0000090: 462a 2b3d 5134 6d3c 412c 7327 5b2c 3635  F*+=Q4m<A,s'[,65
00000a0: 3e2b 6623 737e 3937 2531 3d5d 312d 2249  >+f#s~97%1=]1-"I
00000b0: 6e76 616c 6964 2251 342f 532a 3f         nvalid"Q4/S*?

```

The above program is 189 bytes long and qualifies for the bonus.

At the cost of 26 more bytes – for a total score of 161.25 – we can avoid unprintable characters:

```
l" .-"-:Q,",YER,moTd$V6nH\-Mh/I-z(]k!uw()=j9_[C3n&As0(F;TAn$eB-r%:p+^b,1Y.j;thavi@!d,Dt7M_x-5V:#o/m_CKj-c*Imy~IjXPBCo?aM#lrN:o48u_2EKgyG@.V"33f-94b27b'@f+'@/{Q2<#1&!}#_W>F*+=Q4m<A,s'[,65>+f#s~97%1=]1-"Invalid"Q4/S*?

```

You can test this version in the CJam interpreter.

### Example run

```
$ cat gen.cjam
"l\" .-\"-:Q,"[32,15>{[
"NO"15"BE"16"BI"16"DK"18"FO"18"FI"18"GL"18"NL"18"MK"19"SI"19
"AT"20"BA"20"EE"20"KZ"20"LT"20"LU"20"CR"21"HR"21"LV"21"LI"21
"CH"21"BH"22"BG"22"GE"22"DE"22"IE"22"ME"22"RS"22"GB"22"GI"23
"IL"23"AE"23"AD"24"CZ"24"MD"24"PK"24"RO"24"SA"24"SK"24"ES"24
"SE"24"TN"24"VG"24"DZ"24"PT"25"AO"25"CV"25"MZ"25"IS"26"TR"26
"IR"26"FR"27"GR"27"IT"27"MR"27"MC"27"SM"27"BF"27"CM"27"MG"27
"AL"28"AZ"28"CY"28"DO"28"GT"28"HU"28"LB"28"PL"28"BJ"28"CI"28
"ML"28"SN"28"BR"29"PS"29"QA"29"UA"29"JO"30"KW"30"MU"30"MT"31
]2/{1=L=},0f=_!!{:+}*}fL]"@"*'@f-27b256b:c`"\\\\"/"\\"*
"256b27b'@f+'@/{Q2<#1&!}#_W>F*+=Q4m<A,s'[,65>+f#s~97%1=]1-\"Invalid\"Q4/S*?"
$ LANG=en_US cjam gen.cjam | tee >(cksum) > iban.cjam
770150303 189
$ LANG=en_US cjam iban.cjam <<< GB82WEST12345698765432; echo
GB82 WEST 1234 5698 7654 32

```

### How it works

```
"…"256b27b'@f+"

```

converts the string `"…"` into an integer by considering it a base-256 number, then into an array of integers by considering it a base 27-number, adds the character code of `@` to each digit and casts to Character in the process.

As a result, the following code gets executed:

```
" Read one line from STDIN, remove allowed separators, store the result in variable
  “Q” and push its length (“,”).                                                      ";

l" .-"-:Q,

" Push the string from above.
  The correct number of characters for country code “NO” is 15.
  The correct number of characters for country codes “BE” and “BI” is 16.
  The number of characters should never be 17.
  ⋮                                                                                ";

"NO@BEBI@@DKFOFIGLNL@MKSI@ATBAEEKZLTLU@CRHRLVLICH@BHBGGEDEIEMERSGB@"
"GIILAE@ADCZMDPKROSASKESSETNVGDZ@PTAOCVMZ@ISTRIR@FRGRITMRMCSMBFCMMG@"
"ALAZCYDOGTHULBPLBJCIMLSN@BRPSQAUA@JOKWMU@MT"++

" Split the above string at the at signs (“@”).                                       ";

'@/

" Find the index of the (first) substring such that the index of the country code
  (“Q2<”) in the substring is even.                                                   ";

{Q2<#1&!}#

" If the country code is invalid, the index will be -1. If the index is greater than
  -1 (“W>”), add 15 to it; if it isn't, leave -1 on the stack.                        ";

_W>F*+

" Compare the result to the length of the IBAN. Push 1 if they match and 0 otherwise. ";

=

" Push the IBAN rotated to the left by four characters.                               ";

Q4m<

" “A,s'[,65>+” pushes “0123456789ABCDEFGHIJKLMNOPQRSTUVXYZ”. For each character of
   the IBAN, push its index in that string (-1 if not present).                       ";

A,s'[,65>+f#

" Stringify (“s”) the result, interpret the string (“~”) and compute the residue of
  the (topmost) resulting integer modulo 97.                                          ";

s97%

" Push 1 if the residue is 1; otherwise, push 0                                       ";

1=

" Wrap the entire stack in an array and remove the integer 1 from it. If the IBAN is
  valid, the array will be empty.

" If the result is falsy, the IBAN is valid; split it into substrings of length 4
  and join them using spaces (“S”). Otherwise, the IBAN is invalid; say so.           ";

"Invalid"Q4/S*?

```
> 4 votes

# Answer
# Bash, ~~738 519 444 434~~ 427

Here's something to start us off, I wrote it (and saved 317 characters, mostly in the country code storage bit) while the question was in the sandbox. Let me know if there are any issues.

The function reads from stdin, which is quite common in Bash (the question says "accepts a string of alphanumeric characters", it doesn't require this to be via arguments).

It returns 0 if the IBAN is valid and a non-zero value if it is invalid.

An IBAN containing any characters other than the delimiters `. -` and `A-Z0-9` is invalid

```
t=return
v=`tr -d .\ -`
[ "`tr -dc A-Z0-9<<<$v`" = $v ]||$t
((${#v}>9))||$t
r=`grep -oE "[0-9]+[A-Z]{2}*${v:0:2}"<<<15NO16BEBI18DKFIFOGLNL19MKSI20ATBAEEKZLTLU21CHCRHRLILV22BGBHDEGBGEIEMERS23AEGIIL24ADCZDZESMDPKROSASESKTNVG25AOCVMZPT26IRISTR27BFCMFRGRITMCMGMRSM28BJCICYDOGTHULBMLPLSNAZ29BRPSQAUA30JOKWMU31MT`
[ "${r:0:2}" = ${#v} ]||$t
v=${v:4:99}${v:0:4}
d=({A..Z})
for a in {10..35};{
v=${v//${d[a-10]}/$a}
}
$t `bc<<<$v%97-1`

```

## Explanation

```
t=return # Alias return to $t
v=`tr -d .\ -` # Remove delimiters from STDIN and save to a variable $v.
# If you want the function to take the IBAN as an argument, insert <<<$1 just before the last ` in the line above
# Check that the number now contains no characters other than A-Z0-9 (i.e. if all other characters are removed, the string should remain the same because there aren't any of them)
# If not, return. By default, return uses the exit status of the previous command, which will be 1
[ "`tr -dc A-Z0-9<<<$v`" = $v ]||$t
# Check that $v is long enough to have a country code at the start, return if not
# I could have put 2 instead of 9, but the character count is the same
((${#v}>9))||$t
# give grep the country code data string, which is of the format <length1><country><country><length2><country><country><country>...
# for example, this tells you that EE has an IBAN length of 20
# grep searches for a number ([0-9]+), followed by any number including zero of country codes ([A-Z]{2}*), followed by the first two characters of the input IBAN, i.e. its country code (${v:0:2})
# -o makes grep only output the match, not the line containing it; -E enables extended regexes
# The result is saved to the variable $r
r=`grep -oE "[0-9]+[A-Z]{2}*${v:0:2}"<<<15NO16BEBI18DKFIFOGLNL19MKSI20ATBAEEKZLTLU21CHCRHRLILV22BGBHDEGBGEIEMERS23AEGIIL24ADCZDZESMDPKROSASESKTNVG25AOCVMZPT26IRISTR27BFCMFRGRITMCMGMRSM28BJCICYDOGTHULBMLPLSNAZ29BRPSQAUA30JOKWMU31MT`
# Check that the length specified by the country code, the first two chars of $r, is equal to the actual IBAN's length ${#v}. return 1 if not.
[ "${r:0:2}" = ${#v} ]||$t
v=${v:4:99}${v:0:4} # Put the first 4 chars to the back
d=({A..Z}) # Make an array of letters A to Z
# Loop for each number from 10 to 35
for a in {10..35};{
# in the IBAN, replace letters A to Z by the corresponding number from 10 to 35
v=${v//${d[a-10]}/$a}
}
# $v is now an integer
# note: I used bc here because Bash's built-in arithmetic couldn't handle big numbers
# find the remainder of dividing $v by 97, subtract 1, and return the value
# if the remainder is 1, then the IBAN is valid and 1-1=0 is returned.
$t `bc<<<$v%97-1`

```

## Examples

```
ibanfn<<<'-GB82-WEST-1234 5698.7654.32    ' #returns 0, valid
ibanfn<<<'-GB82-WEST-1234 5698.7654.33    ' #returns 27, invalid, fails remainder test
ibanfn<<<'GB82 WEST 1234 5698 7654 32a'     #returns 1, invalid, contains invalid character a
ibanfn<<<'YY82 WEST 1234 5698 7654 32'      #returns 1, invalid, country code does not exist
ibanfn<<<'GB82 WEST 1234 5698 7654 3210'    #returns 1, invalid, wrong length

```
> 2 votes

# Answer
## Python 3 - (483 - 25%) 362

```
import re
def c(i):
 i=re.sub('\W','',i);q,s='NOBEBIDKFOFIGLNLMKSIATBAEEKZLTLUCRHRLVLICHBHBGGEDEIEMERSGBGIILAEADCZMDPKROSASKESSETNVGDZPTAOCVMZISTRIRFRGRITMRMCSMBFCMMGALAZCYDOGTHULBPLBJCIMLSNBRPSQAUAJOKWMUMT',i
 for m in b" !!#####$$%%%%%%&&&&&''''''''((())))))))))))****+++,,,,,,,,,------------....///0":
  if(i[:2],len(i)+17)==(q[:2],m):
   i=i[4:]+i[:4]
   for z in range(26):i=re.sub(chr(65+z),str(z+10),i)
   return(int(i)%97==1)and re.findall('.{,4}',s)or 0
  q=q[2:]
 return 0

```
> 2 votes

# Answer
## Perl 6 - 354 chars - (not sure of bonus)

```
my $r = slurp 'ir';
my @cs = $r.comb(/(\D)+/);my @ns = $r.comb(/(\d)+/);
my %h;
for @ns Z @cs -> $n, $c {%h{$n}=[$c.comb(/\w**2/)]};
for my @ =lines() {
 my $o=$_;
 my $y=$_.substr(0,2);
 $_=s:g/\s|\-|\.//.uc.comb.rotate(4).join;
 my $l=$_.chars ;
 $_.=trans(['A'..'Z'] => ['10'..'35']);
 next if $y !~~ %h{$l}.any;
 say $_%97==1??"$o ok"!!"Invalid";
}

```

Reading input from `IBANS.txt` on `STDIN` and slurping the rules from the file `ir` (I left the rules out of the total in case they were boilerplate - the rules file is 191 characters so the total would be 545.

```
 perl6 ibanvalidate.p6 IBANS.txt

```

`IBANS.txt` is as follows:

```
GB82 WEST 1234 5698 7654 32
GB82-WEST-1234-5698-7654-32
gb82-west-1234-5698-7654-32
GB82WEST12345698765432
GB82.WEST.1234.5698.7654.32
GR16 0110 1250 0000 0001 2300 695
GB82 WEST 1234 5698 7654 31
NL82 WEST 1234 5698 7654 32
GB29 NWBK 6016 1331 9268 19
Whee perl6
CANADA 000 Banks 007 911

```

**Notes**

* validates country code and length and outputs as below
* Character count from: `wc -m ibanvalidate.p6`
* Currently not much error checking validation of input is done.
* Whitespace is signficant in Perl6 (or more significant than Perl 5) so is counted.

Typical output:

```
GB82 WEST 1234 5698 7654 32 ok
GB82-WEST-1234-5698-7654-32 ok
GB82WEST12345698765432 ok
GB82.WEST.1234.5698.7654.32 ok
GR16 0110 1250 0000 0001 2300 695 ok
Invalid
GB29 NWBK 6016 1331 9268 19 ok

```

This is not typical Perl6 code (especially the `comb` \- lines a friendly and influential Perl developper mentioned this in passing): I'm a beginner. Once the contest is done I will add/change and make any modifications suggested by Perl6-ers. Thanks for playing and being nice :-)
> 2 votes

# Answer
# Perl (356+2 * 75% = 268.5)

the code is so confusing that even SE's syntax highlighting gets lost in it :)

```
#!perl -ln
use bignum;s/\W//g;$_=$T=uc;$q=15;/\w/?$H{$_}=$q:$q++for'NO,BEBI,,NLGLDKFOFI,SIMK,KZEEATLTLUBA,HRCHLVCRLI,RSIEGEDEBGBHGBME,GIAEIL,SASESKESCZMDTNPKADDZVGRO,PTMZCVAO,TRISIR,CMMGMRSMITFRGRBFMC,ALAZPLCIGTHUSNCYDOBJLBML,UABRQAPS,KWMUJO,MT'=~/,|../g;/../;$q=$H{$&}==y///c;/..../;$_=$'.$&;s/[A-Z]/ord($&)-55/ge;print+(Invalid,join' ',($T=~/.{1,4}/g))[1==$_%97*$q]

```

## Explanation

```
#!perl -nl

```

`-n` means read stdin line by line; `-l` adds newlines to print

```
use bignum;

```

required for modulo operation later to return correct value.

```
s/\W//g;

```

remove everything that's not \w from IBAN.

```
$_=$T=uc;

```

convert the iban number to upper case, also save it to $T - will be used for pretty-printing later.

```
$q=15;

```

set the temporary variable to 15, it will be used to build a hash table with country code to iban length mapping.

```
/\w/ ? $H{$_}=$q : $q++
for 'NO,BEBI,,NLGLDKFOFI,SIMK,KZEEATLTLUBA,HRCHLVCRLI,RSIEGEDEBGBHGBME,GIAEIL,SASESKESCZMDTNPKADDZVGRO,PTMZCVAO,TRISIR,CMMGMRSMITFRGRBFMC,ALAZPLCIGTHUSNCYDOBJLBML,UABRQAPS,KWMUJO,MT' =~ /,|../g;

```

split the large string into an array of commas or two-letter country codes, iterate over it. if the element starts with a letter, it's a country code - save it in the hash with a value of $q; otherwise, a comma means to increment $q. so, NO will get the value of 15, BE and BI will be 16, and so on.

```
/../;

```

match first two characters from IBAN (the country code)

```
$q=$H{$&}==y///c;

```

check if IBAN has correct length for the country code, save result in $q

```
/..../;$_=$'.$&;

```

move first four characters to the end of IBAN

```
s/[A-Z]/ord($&)-55/ge;

```

replace all letters with corresponding numbers, starting with A = 10

```
print+(Invalid,join' ',($T=~/.{1,4}/g))[1==$_%97*$q]

```

print either "Invalid" or the pretty-printed IBAN. `1==$_%97*$q` will only equal `1` for an IBAN with a correct length and correct remainder.
> 2 votes

# Answer
# Perl 6, 311 bytes, score 233.25

```
{/:i^(..)<[A..Z0..9]>+$/&&'NobeBIdkfofiglNlmkSiatbaeekzltLucrhrlvliChbhbggedeiemersGbgiilAeadczmdpkrosaskessetnvgDzptaocvMzistrIrfrgritmrmcsmbfcmMgalazcydogthulbplbjcimlSnbrpsqaUajokwMumt'~~/^:i(..)*$($0)/&&.comb==$0.comb(/<:Lu>/)+15&&[.comb].rotate(4)>>.&{:36($_)}.join%97==1&&~.comb(4)||'Invalid'}o{TR/\ .-//}

```

Try it online!

I'm not sure

* where separator characters are allowed exactly. I simply remove all of them.
* whether the final formatted output should be uppercase.

### Explanation

```
{
  /                # Match against regex
    :i             #   ignore case
    ^              #   start of string
    (..)           #   country code (stored in $0)
    <[A..Z0..9]>+  #   alphanumeric characters
    $              #   end of string
  /
  &&
  'NobeBIdk...'    # Country code string with uppercase letter
                   # for each length increase
  ~~               # match against
  /                # regex
    :i             #   ignore case
    ^              #   start of string
    (..)*          #   series of two characters (stored in $0)
    $($0)          #   country code
  /
  &&
  .comb==          # IBAN length equals
  $0.comb(/<:Lu>/) # number of uppercase characters
  +15              # plus 15
  &&
  [.comb]          # Split IBAN into characters
  .rotate(4)       # Rotate by four
  >>.&{:36($_)}    # Convert each from base-36
  .join            # Join
  %97==1           # Modulo 97 check
  &&
  ~.comb(4)        # Add space after every four characters
  ||
  'Invalid'        # Return 'Invalid' if any of the checks failed
}
o                  # Function composition
{
  TR/\ .-//        # Remove space, dot, dash
}

```
> 1 votes

# Answer
**Python3.x (539 chars - 25% = 404.25)**

(To be said first: I'm a bit confused what HAS to be counted by your rules so I just counted my whole function)

539 characters - Including `import` and `def IBAN(i):` (tabs at the beginning of the line are counted anyway in python so they don't matter)

Bonus applied as stated in the rules.

```
def IBAN(i):
    import re
    i=re.sub(r'[^\w]','',i).upper()
    k=len(i)
    z=i[:2]in re.search(r'%s([A-Z ]*)'%k,'15NO16BE BI18DK FO FI GL NL19MK SI20AT BA ES KZ LT LU21CR HR LV LI CH22BH BG GE DE IE MK RS GB23GI IL AE24MD PK RO SA SK ES SE TN VG DZ25CV MZ26IS TR IR FR GR IT MR MC SM BF CM MG28AL AZ CY DO GT HU LB PL BJ CI ML SN29BR PS QA UA30JO KW MU31MT').group(1)or None
    if int(''.join([c if c.isdigit()else str(ord(c)-55)for c in i[4:]+i[:4]]))%97!=1 or z is None:return('Invalid')
    return(' '.join([i[0+j:4+j]for j in range(0,k,4)]))

```

Code with comments (not completed yet... I'm way too tired to write the remaining part of the comments... I'll do that tomorrow)

```
def IBAN(i):
    import re
    # Remove all non word characters (including space) and change to uppercase
    # as0098-7*46.76A -> AS009874676A
    i=re.sub(r'[^\w]','',i).upper()
    # Get the length of it because I need it later multiple times
    k=len(i)
    #                   r'%s([A-Z ]*)'%k = Replace %s with the length of i
    #         re.search(                ,'15NO16BE BI18DK FO FI GL NL19MK SI20AT BA ES KZ LT LU21CR HR LV LI CH22BH BG GE DE IE MK RS GB23GI IL AE24MD PK RO SA SK ES SE TN VG DZ25CV MZ26IS TR IR FR GR IT MR MC SM BF CM MG28AL AZ CY DO GT HU LB PL BJ CI ML SN29BR PS QA UA30JO KW MU31MT')
    #                                    = search (with regexp) in this string (which are the lengths and countrycodes seperated by space)
    # Return the first found match (scroll to the right to see)                                                                                .group(1)
    # i[:2]in                                                                                or None
    # = The first two characters in the returned string (in the same order and same case)
    z=i[:2]in re.search(r'%s([A-Z ]*)'%k,'15NO16BE BI18DK FO FI GL NL19MK SI20AT BA ES KZ LT LU21CR HR LV LI CH22BH BG GE DE IE MK RS GB23GI IL AE24MD PK RO SA SK ES SE TN VG DZ25CV MZ26IS TR IR FR GR IT MR MC SM BF CM MG28AL AZ CY DO GT HU LB PL BJ CI ML SN29BR PS QA UA30JO KW MU31MT').group(1)or None
    if int(''.join([c if c.isdigit()else str(ord(c)-55)for c in i[4:]+i[:4]]))%97!=1 or z is None:return('Invalid')
    return(' '.join([i[0+j:4+j]for j in range(0,k,4)]))

```
> 0 votes

# Answer
# Perl (535)

Not really golfed yet - no idea if I qualify for the bonus ;-) I will add some @professorfish type explanations.

```
#!perl -ln
$r="15NO16BEBI18DKFIFOGLNL19MKSI20ATBAEEKZLTLU21CHCRHRLILV22BGBHDEGBGEIEMERS23AEGIIL24ADCZDZESMDPKROSASESKTNVG25AOCVMZPT26IRISTR27BFCMFRGRITMCMGMRSM28BJCICYDOGTHULBMLPLSNAZ29BRPSQAUA30JOKWMU31MT";
$c{$1} = [unpack("(A2)*", $2)] while($r) =~/(\d{2})(\D{2,})/g;
@h{("A".."Z")}=(10..35);
chomp;$o=$_;$_=uc$_;
s/[ -.]//g;
$l=y///c;
($m)=($_=~m/^.{2}/g);
($n=$_) =~s/^(....)(.*)/$2$1/dg;
$n=~s/([A-Z])/$h{$1}/g;
print $m ~~ @{$c{$l}} ? "length valid for $m":"invalid length";
use bignum;
print $n%97==1 ? "$o ok":"$o Invalid";

```
> 0 votes

# Answer
# JavaScript (Node.js), 372 bytes * .75 = 279

```
s=>(s=s[R="replace"](/[^A-Z0-9]/g,"")).length-14-"NO|BEBI||DKFOFIGLNL|MKSI|BATEEKZLTLU|CRCHRLVLI|GBHBGEDEIEMERS|GILAE|SADCZMDZPKROSASKESETNVG|PTAOCVMZ|ISTRIR|BFRGRITSMRMCMG|ALBJAZCYDOGTHUPLCIMLSN|BRPSQAUA|JOKWMU|MT".match(eval(`/.*${s.slice(0,2)}/i`))[0].split`|`.length||BigInt((s.slice(4)+s.slice(0,4))[R](/\w/g,x=>parseInt(x,36)))%97n-1n?"Invalid":s[R](/(.{4})/g,"$1 ")

```

Try it online!

Test cases borrowed from @marinus 's J answer.
> 0 votes

---
Tags: code-golf, math, string
---


# Question
Title: Given a string, calculate the number of the column it corresponds to
In Excel, the columns range from `A-Z, AA,AB,AZ,BA,..,BZ` and so on. They actually each stand for numbers, but rather are encoded as alphabet strings.

In this challenge, you will be given a string of alphabets, and you must calculate the column it corresponds to.

Some tests:

> 'A' returns 1 (meaning that it is the first column)
>
> 'B' returns 2
>
> 'Z' returns 26
>
> 'AA' returns 27
>
> 'AB' returns 28
>
> 'AZ' returns 52
>
> 'ZZ' returns 702
>
> 'AAA' returns 703

You can assume that capital letters will be given only.

Shortest bytes win.

Good luck!

# Answer
> 9 votes
# Perl 6, 17 bytes

```
{:26[.ords X-64]}

```

Try it online!

Anonymous code block that subtracts 64 from each byte value and converts from base 26 with `Z` overflowing to the next column.

# Answer
> 8 votes
# Google Sheets, 21 bytes

(formula evaluates to the result, takes input from cell A1)

```
=column(indirect(A1&2

```

# Answer
> 6 votes
# , ~~48~~ 43 bytes

-5 bytes thanks to @Giuseppe, using the same logic, but as a program that eliminates the `nchar` call.

```
for(i in utf8ToInt(scan(,"")))F=F*26+i-64;F

```

Try it online!

# Answer
> 5 votes
# Java (JDK), 39 bytes

```
s->s.chars().reduce(0,(a,b)->a*26+b%32)

```

Try it online!

# Answer
> 3 votes
# Python 2, ~~52~~ 45 bytes

```
t=0
for c in input():t=26*t+ord(c)%64
print t

```

Try it online!

# Answer
> 3 votes
# PHP, ~~41~~ 38 bytes

-3 thanks to Jo King.

```
for($c=A;$c!=$argn;$i++)$c++;echo$i+1;

```

run as pipe with `-nr`

unary output, 34 bytes:

```
1<?for($c=A;$c!=$argn;$c++)echo 1;

```

requires PHP 7.1. save to file, run as pipe with `-nF`.

# Answer
> 3 votes
# 05AB1E, 6 bytes

```
Çžx-₂β

```

Try it online!

# Answer
> 3 votes
# Haskell, ~~38~~ ~~34~~ 31 bytes

```
foldl(\o->(o*26-64+).fromEnum)0

```

Try it online!

# Answer
> 2 votes
# Jelly, 7 bytes

```
ØAiⱮḅ26

```

Try it online!

# Answer
> 2 votes
# APL(NARS), 11 chars, 22 bytes

```
{+/26⊥⎕A⍳⍵}

```

test

```
  f←{+/26⊥⎕A⍳⍵}
  f¨'A' 'AA' 'AAA'
1 27 703
  f¨'AB' 'ZZ' 'Z'
28 702 26

```

# Answer
> 2 votes
# , 11 bytes

```
26#.64|3&u:

```

Try it online!

### How it works

```
26#.64|3&u:  Monadic verb. Input: a string.
       3&u:  Convert each character to Unicode codepoint
    64|      Modulo 64; maps A -> 1, ... Z -> 26
26#.         Interpret as base-26 digits and convert to single integer

```

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

```
f=([h,...t],p=0)=>h?f(t,p*26+parseInt(h,36)-9):p

```

Try it online!

# Answer
> 1 votes
# Java (JDK), 92 bytes

```
static int m(String v){int x=0;for(int i=0;i<v.length();i++)x=x*26+v.charAt(i)-64;return x;}

```

Try it online!

**Output**

> A=1
>
> B=2
>
> Z=26
>
> AA=27
>
> AB=28
>
> AZ=52
>
> ZZ=702
>
> AAA=703

# Answer
> 1 votes
# , 20 bytes

```
[:(#.~26$~#)32|a.i.]

```

Try it online!

## Explanation:

```
 [:(#.~26$~#)32|a.i.]
                  i.    - indices
                    ]   - of the characters of the input
                a.      - in the alphabet
             32|        - mod 32
 [:(        )           - apply the following code to the above
         $~             - create a list of (left and right arguments exchanged)
       26               - the number 26
           #            - repeated the length of the input times
    #.~                 - to base (26)

```

# Answer
> 1 votes
# APL (Dyalog Classic), 11 bytes

```
⎕A∘⍳⊥⍨26⍴⍨≢

```

Try it online!

# Answer
> 1 votes
# Google Sheets, 100 bytes

(formula evaluates to the result, takes input from cell A1)

```
=sum(arrayformula(
  (
    code(
      mid(A1,row(indirect("1:"&len(A1))),1)
    )-64
  )*26^row(indirect("1:"&len(A1)))/26

```

All spaces are added for clarity only.

*Note*.

* I don't know if it's possible to remove the duplication of `row(indirect("1:"&len(A1))`.
* Although Google Sheets has a `decimal` function, the transliteration would takes a lot of bytes.

# Answer
> 1 votes
# APL+WIN, 12 bytes

Index origin 1.

```
26⊥¯65+⎕av⍳⎕

```

Try it online! Courtesy of Dyalog Classic

Explanation:

```
⎕av⍳⎕ Prompts for input and gets Ascii integer value for each character

¯65+ subtracts 65 to give integers 1-26 for A-Z

26⊥ converts resulting vector from base 26 to single integer

```

# Answer
> 1 votes
# Charcoal, 10 bytes

```
Ｉ↨²⁶ＥＳ⊕⌕αι

```

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

```
     Ｓ      Input string
    Ｅ       Map over characters
         ι  Current character
        α   Uppercase alphabet
       ⌕    Find index
      ⊕     Increment
  ²⁶        Literal 26
 ↨          Base conversion
Ｉ           Cast to string
            Implicitly print

```

# Answer
> 1 votes
# C (gcc), ~~46~~, 43 bytes

```
a;f(int*s){for(a=0;*s;)a=*s++%64+a*26;s=a;}

```

Try it online!

## Degolf

```
a; f(int*s)
{  for(a=0;*s;) // Loop through s, which is a null-terminated string.
       a=*s++%64 + a*26; // Multiply accumulated value by 26, and add current char modulo 64 to it.
   s=a;} // Return the accumulated value.

```

# Answer
> 1 votes
# Japt `-h`, 10 bytes

```
åÈ*26+InYc

```

Try it

Or without a flag. The first byte can be removed if we can take input as a character array.

```
¬®c aIÃì26

```

Try it

---

## Explanation

```
åÈ             :Cumulatively reduce by passing each character at Y through a function, with an initial total of 0
  *26          :  Multiply current total by 26
     -I        :  Subtract 64
       n       :   Subtracted from
        Yc     :    The codepoint of Y
               :Implicitly output the last element of the resulting array

```

# Answer
> 1 votes
# MATL, 11 bytes

```
0w"26*@+64-

```

Try it online!

# Answer
> 1 votes
# Kotlin, 36 bytes

```
{it.fold(0){o,n->o*26+n.toInt()-64}}

```

Try it online!

# Answer
> 1 votes
# Ruby, 18 bytes

```
->s{[*?A..s].size}

```

Try it online!

# Answer
> 1 votes
# x86 machine code, 19 bytes

```
00000000: 31c0 8b19 83e3 3f41 b21a f7e2 01d8 3831  1.....?A......81
00000010: 75f0 c3                                  u..

```

Assembly:

```
section .text
	global func
func:				;this function uses fastcall conventions
	xor eax, eax		;reset eax to 0
	loop:
		;ebx=*ecx%64
		mov ebx, [ecx]	;ecx is 1st arg to this func (in fastcall conventions)
		and ebx, 63	;because 64 is a pwr of 2,n%64=n&(64-1)

		;ecx++		get next char in str by incrementing ptr
		inc ecx

		;eax=eax*26
		mov dl, 26	;using an 8bit reg is less bytes
		mul edx

		;eax+=ebx //(eax=(*ecx%64)+(eax*26))
		add eax, ebx

		;if(*ecx!='\0')goto loop
		cmp byte [ecx], dh ;dh==0
		jne loop
	ret			;return value is in eax

```

Try it online!

# Answer
> 1 votes
# Kotlin, 29 bytes

```
{it.fold(0){a,v->v-'@'+a*26}}

```

Try it online!

## Explained

```
val column: (String) -> Int = {  // String in, Int out
    it.fold(0) { a, v ->  // acc, value
        v - '@'  // distance of char from @ (A=1 etc.)
                + a * 26
    }
}

```

# Answer
> 1 votes
# Ahead, 22 bytes

```
>jvi'@-\26l
^~>O@ ~+*<

```

Try it online!

# Answer
> 1 votes
## MBASIC, 84 bytes

```
1 INPUT S$:L=LEN(S$):FOR I=1 TO L:V=ASC(MID$(S$,I,1))-64:T=T+26^(L-I)*V:NEXT:PRINT T

```

Output:

```
? AZ
 52

? ZZ
 702

? AAA
 703

```

# Answer
> 0 votes
# Ruby `-nl`, 39 bytes

```
p$_.chars.reduce(0){|x,y|26*x+y.ord-64}

```

Try it online!

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


title: Pentomino 6x10 solution normalizer

text:
# Question
Title: Pentomino 6x10 solution normalizer
As you most probably now, there are 2339 solutions to pentomino puzzle in a 6x10 grid. There are different labeling schemes for the 12 pentominoes, two of them are shown on the image below:

Image credit: Wikipedia

For the purposes of the current task we will say that a normalized pentomino solution is a solution that uses the second labeling scheme (Conway’s).

Example:

```
O O O O O S S S Z Z
P P R R S S W W Z V
P P P R R W W Z Z V
U U X R T W Y V V V
U X X X T Y Y Y Y Q
U U X T T T Q Q Q Q

```

The piece with 5 squares in a row is denoted with letters `O`, according to the scheme. The same is true for all pieces.

## Task:

Given a solution to the 6x10 pentomino in which the pieces are labeled with a random sheme, normalize it so that all pieces are labeled in Conway’s labeling scheme. You need to recognize the pieces and mark each square of a particular piece with the symbol of the piece.

## Input:

The solution to be normalized, in any format that is convenient for you, for example:

* A multiline string
* A list of strings
* A list of lists of characters

and so on

## Output:

The same solution (all the pieces positions and orientation preserved), but each piece labeled according to Conway’s labeling scheme. Note: The output MUST be PRINTED as a 6x10 grid of characters. Leading and trailing newlines and spaces are permitted. You can also print a space between the characters (but not empty lines), as in the example above.

## Test cases:

1. Input:

```
6623338888
6222344478
66A234BB70
1AAA94B770
11A99BB700
1199555550

```

Output:

```
UURTTTQQQQ
URRRTVVVSQ
UUXRTVZZSY
PXXXWVZSSY
PPXWWZZSYY
PPWWOOOOOY

```

2. Input:

```
45ookkkk00
455ooogk00
4a55gggdd0
4aaa3gnnd.
4am333ndd.
mmmm3nn...

```

Output:

```
OWSSQQQQPP
OWWSSSRQPP
OTWWRRRUUP
OTTTXRZZUV
OTYXXXZUUV
YYYYXZZVVV

```

## Winning criteria:

The shortest solution in bytes in each language wins. Don’t be discouraged by the golfing languages. Explanations of the algorithms and implementations are welcome.

# Answer
> 12 votes
# APL (Dyalog Classic), ~~54~~ ~~53~~ 50 bytes

```
⍴⍴{'OXRYTPZQUWSV'[⌊5÷⍨⍋⍋,{×/+⌿↑|(⊢-+/÷≢)⍸⍵}¨⍵=⊂⍵]}

```

Try it online!

Compute an invariant for each pentomino in the input: measure (∆x,∆y) from each of its squares to its centre of gravity, take abs(∆x) and abs(∆y), sum the x components and separately the y components, and multiply the two sums. This gives 12 distinct results. Then, find the index of each pentomino's invariant in the sorted collection of all invariants. Replace 0 with `'O'`, 1 with `'X'`, 2 with `'R'`, etc.

# Answer
> 4 votes
# Jelly, 37 bytes

```
ŒĠZÆmạƊ€ḅı§AỤỤị“æṂ⁾+’Œ?¤+78Ọ,@FQṢƊyⱮY

```

A full program taking a list of strings (because we must print - otherwise remove the trailing `Y` and you have a monad taking a list of lists of numbers or characters which returns a list of lists of characters).

**Try it online!**

### How?

I believe this works using the same categorisation of pentominos as ngn's APL solution, albeit in a slightly different way (I also don't know APL so I'm not that sure how similar the method is beyond the categorisation).

(Note that `“æṂ⁾+’Œ?¤+78Ọ` is only a one-byte save over `“XRPTZWUYSVQO”`!)

```
ŒĠZÆmạƊ€ḅı§AỤỤị“æṂ⁾+’Œ?¤+78Ọ,@FQṢƊyⱮY - Main Link: list of lists of characters L
ŒĠ                                    - group multidimensional indices by value
      Ɗ€                              - last three links as a monad for €ach i.e. f(x):
  Z                                   -   transpose x
   Æm                                 -   mean (vectorises) (i.e. the average of the coordinates)
     ạ                                -   absolute difference with x (vectorises) (i.e. [dx, dy])
         ı                            - square root of -1 (i)
        ḅ                             - convert from base (vectorises) (i.e a list of (i*dx+dy)s)
          §                           - sum each
           A                          - absolute value (i.e. norm of the complex number)
            Ụ                         - grade up (sort indices by value)
             Ụ                        - grade up (...getting the order from the result of A back,
                                      -              but now with one through to 12)
                       ¤              - nilad followed by links as a nilad:
               “æṂ⁾+’                 -   base 250 literal = 370660794
                     Œ?               -   permutation@lex-index = [10,4,2,6,12,9,7,11,5,8,3,1]
              ị                       - index into
                        +78           - add seventy-eight
                           Ọ          - cast to characters (character(1+78)='O', etc...)
                                 Ɗ    - last three links as a monad (i.e. f(L)):
                              F       -   flatten
                               Q      -   de-duplicate
                                Ṣ     -    sort
                            ,@        - pair (with sw@pped @rguments) (giving a list of 2 lists)
                                   Ɱ  - Ɱap across L with:
                                  y   -   translate i.e. swap the letters as per the the pair)
                                    Y - join with new lines
                                      - implicit print

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 103 bytes

```
""<>Riffle[(t=#)/.Thread[SortBy[Union@@t,Tr@Kurtosis@Position[t,#]&]->Characters@"UPSWZVRTQXYO"],"\n"]&

```

Takes input as a list of lists of characters.

Try it online!

The main idea here is that for each character in the input, we find the coordinates where it occurs, take the kurtosis and sum its coordinates. This gives us an invariant for each piece.

(The kurtosis is some mostly-irrelevant operator from statistics - the key is that it's invariant under translation, while reflection and rotation might switch the order of coordinates at most. We sum the coordinates, so the invariant never changes.)

Anyway, apart from the weird invariant, this solution is similar to the others: we sort the characters and the pieces by each invariant, then replace each character by the corresponding character of `"UPSWZVRTQXYO"`: the pieces, sorted by kurtosis sum.

Finally, `""<>Riffle[...,"\n"]` is the print-as-a-grid code.

# Answer
> 2 votes
# Python 2, 191 bytes

```
def y(o):print"".join(['XPRTWZUYSVQO\n'[[w for v,w in sorted([sum(abs(u-sum(t)/5)for t in[[complex(r%11,r/11)for r,q in enumerate(o)if q==p]]for u in t),p]for p in o)].index(x)/5]for x in o])

```

Try it online!

Takes a multi-line string with a trailing newline and does six nested list comprehensions.

**Ungolfed Version**

```
def pentomino_normalizer(input_string):
    # input_string is a multi-line string with a trailing newline

    results = []  # For saving the results of the for loop
    for current_char in input_string:
        # current_char = p in the golfed version

        # The python data type complex stores a real and a imaginary value and
        # is used for storing the x and y coordinates.
        # In the end, the positions list contains a complex number for every
        # occurence of current_char in the string
        # positions_list = t in the golfed version
        positions_list = [complex(i % 11, i / 11) for i, c
                          in enumerate(input_string) if c == current_char]
        # average_pos is the midpoint of all occurences of current_char,
        # to get rid of translations
        average_pos = sum(positions_list)/5
        # Calculates a value for each tile that is invariant under
        # translations and rotations,
        # simply the sum of all the distances between the midpoint
        # and the positions
        invariant = sum(abs(pos - average_pos) for pos in positions_list)

        # Saves the invariant value to a list
        results.append(invariant, current_char)

    # This new list contains the characters occuring in the string, sorted
    # by the invariant value. Because this was done with each char in the
    # input string, this lists contains every value five times and also
    # contains six newlines
    # at the end of the list
    sorted_results = [w for v, w in sorted(results)]

    # This code snippet maps each char from the input string to its according
    # output and prints to stdout
    chars = ['XPRTWZUYSVQO\n'[sorted_results.index(c)/5] for c in input_string]
    print "".join(chars)

```

---
Tags: code-golf, pattern-matching
---


title: Let's play tennis

text:
# Question
Title: Let's play tennis
I suddenly really want to play tennis, but alas I do not have a court!

Surprise! This is where you come in.

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

## Tennis court

```
---------
|       |
---------
|   |   |
xxxxxxxxx
|   |   |
---------
|       |
---------

```

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

# Answer
# Canvas, 13 bytes

```
Ａ←⁹ｗ５+7ｑ⁴‟５ｎ┼

```

Try it here!
> 1 votes

# Answer
# Python 2, 65 bytes

```
s='-','|'+' '*7,'-','|   ','x'
for i in s+s[3::-1]:print(i*9)[:9]

```

Flp.Tkc saved a byte.
> 13 votes

# Answer
# 05AB1E, ~~29~~ ~~27~~ 26 bytes

```
'-9×©'|ð4×«Dûs®s¨¨ûû'x5×»û

```

Try it online!

```
'-9×©                      Push "---------" and store it as temporary value
     '|ð4×«Dûs             Push palindromized("|    ") = "|       |"
                           and push "|    "
              ®            Push "---------" again
               s¨¨û        Strip the last 2 characters from "|    " and push palindromized("|  ") = "|   |"
                   û       Palindromize last item -> "|   |   |"
                    'x5×   Push "xxxxx"
                        »  Join everything with newlines
                         û Palindromize the result and implicitly display it

```
> 12 votes

# Answer
# Python 3 - ~~73~~ 72 bytes

```
d=b,a,c='|       |','-'*9,'|   |   |'
print(a,*d,'x'*9,c,a,b,a,sep='\n')

```

**Python 3.6** \- 75 bytes

```
x=f"{'-'*9}\n|{' '*7}|\n{'-'*9}\n|   |   |\n"
print(x,'x'*9,x[::-1],sep='')

```

Credit goes to flp-tkc. Thank you :)

Try here!
> 7 votes

# Answer
# ///, ~~64~~ 56 bytes

```
/f/---//e/   //a/fff
|ee |
fff
//d/|e|e|
/adxxxxxxxxx
da

```

Try it online!

Another 56 byte solution:

```
/f/---//e/|   //a/fff
e    |
fff
//d/ee|
/adxxxxxxxxx
da

```
> 6 votes

# Answer
# , 25 bytes

```
9é-ÄÙÒ r|$.4äGMãlr|jj.kÒX

```

Try it online!

This should be 23 bytes:

```
9é-ÄÙÒ r|$.4äMÒXãkr|jj.

```

But I ran into several bugs while creating it. :(
> 6 votes

# Answer
# Jelly, 25 bytes

```
“¡⁵÷ḞȯḤɼ’b4ị“- x|”s5ŒBŒḄY

```

**TryItOnline!**

I had hoped to use the 1,3,1 quarter court repetition, but can't squeeze that into less (a raw version being 28: `“ßṂuB’b4s3x“¢¤¢‘ị“- x|”ŒBŒḄY`).

### How?

```
“¡⁵÷ḞȯḤɼ’b4ị“- x|”s5ŒBŒḄY - Main link: no arguments
“¡⁵÷ḞȯḤɼ’                 - base 250 number: 375116358919167
         b4               - convert to base 4:
                                [1,1,1,1,1,0,2,2,2,2,1,1,1,1,1,0,2,2,2,0,3,3,3,3,3]
           ị“- x|”        - index into character list "- x|" (1-based):
                                "-----|    -----|   |xxxxx"
                  s5      - split into chunks of length 5:
                               ["-----","|    ","-----","|   |","xxxxx"]
                    ŒB    - bounce (vectorises):
                               ["---------","|        |","---------","|   |   |","xxxxxxxxx"]
                      ŒḄ  - bounce (non-vectorising version):
                               ["---------","|        |","---------","|   |   |","xxxxxxxxx","|   |   |","---------","|        |","---------"]
                        Y - join with line feeds:
                          - implicit print

```
> 6 votes

# Answer
# J, ~~70~~ ~~54~~ ~~51~~ 50 bytes

*Saved a byte thanks to Zgarb!*

```
9 9$'-| |-| | |x| | |'#~3 9 1 7{~4#.inv 1851926050

```

Some standard compression technique, using a compressed RLE.

```
   9 9$'-| |-| | |x| | |'#~3 9 1 7{~4#.inv 1851926050
---------
|       |
---------
|   |   |
xxxxxxxxx
|   |   |
---------
|       |
---------

```
> 5 votes

# Answer
## JavaScript (ES6), ~~86~~ ~~84~~ ~~83~~ 81 bytes

*Saved 2 bytes, thanks to Neil*

```
a=`---------
`;a+=`|       |
`+a;b=`|   |   |
`;console.log(a+b+`xxxxxxxxx
`+b+a)
```

### Alternate method #1, 93 bytes

```
console.log('01232101242421512424210123210'.replace(/./g,n=>`-
|  x`[n].repeat('911739'[n])))

```

### Alternate method #2, 86 bytes

Suggested by Neil:

```
console.log(`-${s=`
       |
-
   |
`}x${s}-`.replace(/.*/g,s=>s.repeat(9).slice(-9)))

```

### Alternate method #3, 91 bytes

A recursive approach:

```
console.log((f=(n,c=`xxxx
|   |   |
---------
|       |
`[n]||'-')=>~n--?c+f(n)+c:'x')(43))

```
> 4 votes

# Answer
# Ruby, 60 bytes

```
-4.upto(4){|i|puts''.rjust(9,%w{x |%3s - |%7s -}[i.abs]%'')}

```

**Ungolfed**

```
-4.upto(4){|i|                    #iterate -4 to 4.
   puts''.rjust(9,                #Print the null string right justified to length 9 padded by repititions of
   %w{x |%3s - |%7s -}[i.abs]%'') #the string from the %w{} array modified like sprintf by the % operator
}                                 #so that %Ns is replaced by N spaces.

```
> 4 votes

# Answer
# bash/Unix tools, ~~58~~ 57 bytes

```
dc<<<4o16i3FFFFp20002prp20202p15555pszpszfp|tr 0-3 ' x|-'

```

Only four characters other than newline appear in the desired output, allowing each line to be coded as a base-4 number. These numbers are then written in hexadecimal in the script, for brevity.

The Unix calculator dc is used both for the base-16 to base-4 conversion and for stack manipulation to allow easy repetition of lines in the right places.

*Edit:* Shaved one byte off by swapping two of the base-4 digits used to code characters, permitting the tr command to be one byte shorter than the previous version.
> 4 votes

# Answer
## JavaScript, 85 bytes

```
console.log('---|  ---| |xxx| |---|  ---'.replace(/(.)((.).)/g,'$1$3$3$2$3$3$3$1\n'))

```
> 4 votes

# Answer
# SOGL 0.5, ~~24~~ ~~23~~ 20 bytes (non-competing)

```
 -9*"D√⅜‘⁴"Hοr‘¹q x9*o±

```

Explanation:

```
"'|⁶.f,‘9n_h¹q x9*o±
"'|⁶.f,‘              pushes "------------------|       ||   |   |"
        9n            splits into chunks of 9
                       stack: [["---------","---------","|       |","|   |   |"]]
          _           puts all the contents of the array into the stack
                       stack: ["---------","|       |","---------","|   |   |"]
           h          swaps the 2nd from top with 3rd from top
            ¹         turns back into array
                       stack: [["---------","|       |","---------","|   |   |"]]
             q        outputs the array without popping it from stack
               x      push "x"
                       stack: [["---------","|       |","---------","|   |   |"], "x"]
                9*    repeat it 9 times
                       stack: [["---------","|       |","---------","|   |   |"], "xxxxxxxxx"]
                  o   output that
                   ±  reverse the array
implicitly output the reversed array

```

So how does the compressed string work?

The string converted from base250 to binary is `1000000100111110010100001110100000001100010001`

and approxametally what it does:

```
100 boxstring (a custom dictionary string with chars " -/\|_\n")
000010 choose only the "-"s
01111 with length of 15+(different chars used)+2 = 18 chars
there is only 1 char type, so results in "------------------"
100 another boxsting
101000 choosing " " and "|"
01110 with length of 14+(different chars used)+2 = 18 chars
100000001100010001 the data; 0 = " " and 1 = "|"
has "------------------" and "|       ||   |   |" and just joins them together

```

non-competing, because language postdates the challenge. And this challenge is only a day old. I knew I should've put something up yesterday. I did this as a test for my language and it ended up too good not to post. Pretty sure this is golfable more too.
> 4 votes

# Answer
# ///, 59 bytes

```
/_/---------
//s/   /_|ss |
_|s|s|
xxxxxxxxx
|s|s|
_|ss |
_

```

Try it online!

Outgolfed...
> 3 votes

# Answer
# Javascript (ES6), 86 bytes:

```
a=`---------
|       |
---------`;b=`|   |   |
`;console.log(a+`
`+b+`xxxxxxxxx
`+b+a)
```

Test here:

```
a=`---------
|       |
---------`;b=`|   |   |
`;console.log(a+`
`+b+`xxxxxxxxx
`+b+a)
```
> 3 votes

# Answer
# 05AB1E, 26 bytes

```
'-5×©'|4úD®sÂðñ)í€û»'x5×»û

```

Uses the **CP-1252** encoding. Try it online!
> 3 votes

# Answer
# PHP, ~~66~~ 62 bytes

This is the original answer (66 bytes):

```
<?=$a="---------
|       |
---------
|   |   |
xxxx",x,strrev($a);

```

It generates a notice because of the unknown constant `x`. The notice can be suppressed by setting `error_reporting=0` in `php.ini` or in the command line:

```
$ php -d error_reporting=0 tennis.php

```

The last line of the output doesn't end with a newline character.

---

The updated answer (62 bytes), improving an improvement suggested by @Titus:

```
<?=$a=($b="---------
|   ")."    |
$b|   |
xxxx",x,strrev($a);

```

Run it without a configuration file (it defaults with `error_reporting=0` this way):

```
$ php -n tennis.php

```

Both versions of the code contain literal new lines embedded in the string (1 byte shorter than `\n`) and cannot we unwrapped.
> 3 votes

# Answer
## Pyke, ~~28~~ ~~26~~ 25 bytes

```
\|ddsssd7*.X--||"R\x5*nJs

```

Try it here!

```
       d7*                -    " " * 7
          .X--||"         -   grid(^, corners="-", sides="-", left="|", right="|")
\|dds                     -     "|  "
     s                    -    palindromise(^)
      s                   -   palindromise(^)
                  \x5*    -   "x" * 5
                      nJ  -  "\n".join(^)
                        s - palindromise(^)

```
> 2 votes

# Answer
# Ruby, 52 bytes

```
puts [b=[a=?-*9,"|%8s"%?|,a],c="|   |   |",?x*9,c,b]

```

Using the double simmetry, the lines are: `0-1-0 / 2-3-2 / 0-1-0`, the loop can be easily unrolled and the nested list is flattened on output.
> 2 votes

# Answer
## J, 36 bytes

```
9$'-'([,(' '4}]),[,],'x',:])9$'|   '

```

This works on the REPL, which is the standard way of using J:

```
   9$'-'([,(' '4}]),[,],'x',:])9$'|   '
---------
|       |
---------
|   |   |
xxxxxxxxx
|   |   |
---------
|       |
---------

```

With **41 bytes**, I can print the result to STDOUT:

```
echo 9$'-'([,(' '4}]),[,],'x',:])9$'|   '

```

Try it online!

## Explanation

I construct the tennis court one row at a time.

```
9$'-'([,(' '4}]),[,],'x',:])9$'|   '
                            9$'|   '  The string repeated to length 9: y = '|   |   |'
  '-'(                     )          Apply this verb to x = '-' and y:
                     'x',:]            y with a row of 'x'-chars above it.
                                       This is a 2x9 matrix, and "," now works by
                                       prepending new rows to it.
                   ],                  Prepend another y.
                 [,                    Prepend x, which is repeated to a row of length 9.
        (' '4}]),                      Prepend y with 4th character replaced by a space.
      [,                               Prepend x again.
                                      Now we have this 6x9 matrix:
                                       ---------
                                       |       |
                                       ---------
                                       |   |   |
                                       xxxxxxxxx
                                       |   |   |
9$                                    Repeat it to have 9 rows.

```
> 2 votes

# Answer
# PHP, 72 bytes

```
<?=$a="---------
",$b="|       |
$a",$c="|   |   |
","xxxxxxxxx
$c$a$b";

```

I almost hate it when it´s shorter like this than with calculating a little.
> 2 votes

# Answer
# PowerShell, ~~67~~ 66 bytes

```
($a='-'*9)
($b="|       |")
$a
($c="|   "*2+"|")
'x'*9
$c
$a
$b
$a

```

Try it online!

Just some string multiplication, setting variables, and ensuring they're encapsulated in parens to place copies on the pipeline. The default `Write-Output` at program completion gives us newlines between for free.

*Thanks to @ConnorLSW for saving an obvious byte.*
> 2 votes

# Answer
# 05AB1E, 25 bytes

```
'-9×©'|ð4×«û®…|  ûû'x5×»û

```

Uses the **CP-1252** encoding. Try it online!

Explanation:

```
'-9×                       # Push "---------"
    ©                      # Store in register_c
     '|ð4×«                # Push "|    "
           û               # Palindromize, giving "|       |"
            ®              # Retrieve from register_c
             …|            # Push "|  "
                 ûû        # Palindromize twice, giving "|   |   |"
                   'x5×    # Push "xxxxx"
                       »   # Join by newlines
                        û  # Palindromize
                           # Implicit print

```
> 2 votes

# Answer
# Vim, 32 bytes

```
9i-^[Y3pO||^[7i ^[YGPkP4lr|YpO^[9ix^[

```

This will print the tennis court into a vim buffer. `^M` represents the Enter key (0x0d) and `^[` is the Escape key (0x1b). You can run these keystrokes/code by saving them to a file and running

```
vim -s <filename> -u NONE

```

### Printing to stdout

If it has to be printed to stdout instead, you could save the buffer to a file (I used "a") and use whichever shell `vim` is set to use (I used `bash`) as well as the `cat` program in order to print the tennis court to stdout (51 bytes):

```
9i-^[Y3pO||^[7i ^[YGPkP4lr|YpO^[9ix^[:w!a|sil !cat %^M:q^M

```

It's the same as the earlier version but with `:w!a|sil !cat %^M:q^M` added onto the end
> 2 votes

# Answer
# Python 2, 75 bytes

```
a,b,c='-'*9,'|       |','|   |   |'
for e in[a,b,a,c,'x'*9,c,a,b,a]:print e

```

Uses variables borrowed from @GurupadMamadapur

Alternative also for 75

```
a,b,c='-'*9,'|       |','|   |   |'
print'\n'.join([a,b,a,c,'x'*9,c,a,b,a])

```
> 1 votes

# Answer
# Emacs, ~~43~~ 35 keystrokes

`M-9` `x` `RET` : nine x's, return
`C-SPC` : set mark
`|` `M-3` `SPC` `|` `M-3` `SPC` `|` `RET` : pipe, three spaces, pipe, three spaces, pipe, return
`M-9` `-` `RET` : nine hyphens, return
`|` `M-7` `SPC` `|` `RET` : pipe, seven spaces, pipe, return
`M-9` `-` `RET` : nine hyphens, return
`C-x` `C-x` : exchange point and mark, selecting region
`M-w` : copy region
`C-p` : previous line
`C-y` : yank copied text
`M-x` `rev-r` `RET` : execute `reverse-region` command
> 1 votes

# Answer
# Lua, 82 Bytes.

```
y=[[---------
|       |
---------
]]z="|   |   |\n"io.write(y,z,"xxxxxxxxx\n",z,y)

```

I tried many methods, and yet this one proved the victor.
> 1 votes

# Answer
# Pushy, 33 bytes

This question had 33 upvotes, and there were 33 answers, so I just had to post a 33 byte solution...

```
9:45;T`|    `wT`|   |`4dT5:120;w"

```

**Try it online!**

---

## Explanation

The code can be split into several parts, to make it easier to understand. The first part works like so:

```
9:45;    \ Push the char '-' 9 times
T        \ Push 10, which is a linefeed
`|    `  \ Push these charcodes

```

The stack is now:

```
---------
|

```

The mirror operator, `w`, then mirrors the whole stack, producing:

```
---------
|       |
---------

```

Then:

```
T        \ Push a linefeed
`|   |`  \ Push these chars
4d       \ Copy the last 4 characters
T        \ Push a linefeed
5:120;   \ Push the char 'x', 5 times

```

The stack is now beginning to look like the tennis court:

```
---------
|       |
---------
|   |   |
xxxxx

```

To finish it, we use the mirror operator `w` once more, which reflects this string to produce the full tennis court.

```
---------
|       |
---------
|   |   |
xxxxxxxxx
|   |   |
---------
|       |
---------

```

All that's left now is to print, which is done by the `"` character.
> 1 votes

# Answer
**Unix Shell; using dc and tr; 55 Bytes:** ( Optimization of Mitchell Spector solution )

```
dc<<<4o16i3FFFFp20002prp20202p15555psrfrp|tr 0-3 ' x|-'

```

**Others Solutions : Using sed; 81 Bytes;**

```
echo "---|  ---| |xxx| |---|  ---"|sed "s/\(.\)\(.\)\(.\)/\1\2\2\2\3\2\2\2\1\n/g"

```

**Using dc in function : 88 Bytes**

```
b(){ dc<<<2o16i1${1}p|tr '01' ' '$2;};(b FF -;b 01 \|;b FF -;b 11 \|)>f;cat f;b FF X;tac f

```

**or**

```
b(){ echo "obase=2;$1"|bc|tr '01' ' '$2;};(b 511 -;b 257 \|;b 511 -;b 273 \|)>f;cat f;b 511 X;tac f

```

**Using bc in function : 99 Bytes**

```
b(){ echo "obase=2;$1"|bc|tr '01' ' '$2;};(b 511 -;b 257 \|;b 511 -;b 273 \|)>f;cat f;b 511 X;tac f

```
> 1 votes

# Answer
# Powershell, 56 bytes

```
(('-'*9),'|       |'+'-'*9+'|   |   |'+'x'*9)[0..4+3..0]

```

Explanation: straightforward half-of-the-court

# Alternative, 68 bytes

```
('-----','|    '+'-'*5+'|   |'+'x'*5)[($r=0..4+3..0)]|%{-join$_[$r]}

```

Explanation: quarter-of-the-court uses the same indexes for both row and column display
> 1 votes

# Answer
# Python 2, 60 bytes

```
for i in 0,7,0,3,-2,3,0,7,0:print(('-?x|'[i%4]+' '*i)*9)[:9]

```

Try it online!

Uses Lynn's multiply-and-truncate method.
> 1 votes

# Answer
# Lua, 105 bytes

*Sure, I've already been beaten, but it ain't fun if you don't try!*

Actual answer:

```
a,c,d="---------","xxxxxxxxx","|   |   |"p=print p(a)p("|       |")p(a)p(d)p(c)p(d)p(a)p("|       |")p(a)

```

Less hardcoded:

```
a,b,c,d=("-"):rep(9),(" "):rep(7),("x"):rep(9),"|   |   |"p=print p(a)p("|"..b.."|")p(a)p(d)p(c)p(d)p(a)p("|"..b.."|")p(a)

```

Uses `String.rep` to make it less hardcoded (though it adds bytes!) (instead of `xxxxxxxxx`, write `("x"):rep(9)`)

*Just for fun, how easy would it be to just print it hardcoded?*

```
print([[---------
|       |
---------
|   |   |
xxxxxxxxx
|   |   |
---------
|       |
---------]])

```

*100 bytes. That's shorter than my code. :(*
> 0 votes

# Answer
## Batch, 116 bytes

```
@set s=---------
@for %%s in (%s% "|       |" %s% "|   |   |" %s:-=x% "|   |   |" %s% "|       |" %s%)do @echo %%~s

```

Conveniently, expansion of `for` variables happens *after* parsing, so I only have to quote the `|`s once. However, only the horizontal lines are sufficiently repetitive that using a variable saves bytes.
> 0 votes

# Answer
# Actually, 49 bytes

```
'x9*' 3*;2╟"|%s|%s|"%9'-*' 7*"|%s|"%9'-*k;RdX@i(i

```

Try it online!

Explanation:

```
'x9*' 3*;2╟"|%s|%s|"%9'-*' 7*"|%s|"%9'-*k;RdX@i(i
'x9*                                               "xxxxxxxxx"
    ' 3*;2╟"|%s|%s|"%                              "|   |   |"
                     '-*' 7*"|%s|"%                "|       |"
                                   9'-*            "---------"
                                       k;          push entire stack to list, duplicate it
                                         RdX       reverse one copy and remove the string of "x"s from it
                                            @i     flatten the other copy
                                              (i   flatten the first copy and implicitly print

```
> 0 votes

# Answer
# Scala, 90 bytes

```
val l="-"*9
val g="\n|       |\n"
val s="\n|   |   |\n"
print(l+g+l+s+"x"*9+s+l+g+l)

```
> 0 votes

# Answer
# MATL, 30 bytes

```
9Z"13+'|'7Z"yhhyy6M5(v'x'9Y"yP

```

Try it online!
> 0 votes

# Answer
# R, 121 bytes

```
m=rbind(a<-rep("-",9),b<-c("|",rep(" ",7),"|"),a,b,rep("x",9),b,a,b,a);m[c(4,6),5]="|";for(i in 1:9)cat(m[i,],"\n",sep="")

```

First time trying a Kolmogorov-Complexity challenge, not sure R is really suited for it.

### Ungolfed:

```
a <- rep("-", 9)
b <- c("|", rep(" ", 7), "|")
m <- rbind(a, b, a, b, rep("x", 9), b, a, b, a)

m[c(4,6), 5] <- "|"

for(i in 1:9){
  cat(m[i,], "\n", sep = "")
}

```

### Output:

```
---------
|       |
---------
|   |   |
xxxxxxxxx
|   |   |
---------
|       |
---------

```
> 0 votes

# Answer
# Scala, 83 bytes

```
val(a,b)=("-"*9+"\n|   ","   |\n")
val c=s"$a $b$a|$b"
print(c+"x"*9+c.reverse)

```
> 0 votes

# Answer
# C, 97 bytes

```
n=11;i,k;f(){i=n/10%10;k=n++%10;printf("%c",k?"| -x"[i%2?i==5|2:k%8-1&&k-5|i*i%5-1]:10);i?f():0;}

```
> 0 votes

# Answer
# ///, 55 bytes

```
/l/---//s/   //m/
|s|s|
//a/lll
|s s|
lll/amxxxxxxxxxma

```

**Try it online**
> 0 votes

# Answer
# Common Lisp, ~~90~~ ~~86~~ ~~85~~ ~~81~~ 79 bytes

```
(format t"~5@{~@?
~}~4@{~2:*~@?
~}"#1="~9@{-~}""|~8t|"#1#"|   |   |""~9@{x~}"1)

```

~~First we print out all arguments, and then we print them in reversed order (without `xxxxxxxxx`).~~

Similiar solution, but instead of providing every variable directly I give (where it's efficient) control string which will output needed text.
> 0 votes

# Answer
# SmileBASIC, ~~68~~ ~~65~~ ~~62~~ ~~59~~ 57 bytes

```
M$="|
L$="-"*9?L$?M$,M$?L$?M$*3?"x"*9?M$*3?L$?M$,M$?L$

```

(note the 3 trailing spaces in line 1)

Of course, this will work in many other dialects of BASIC.

Explained:

```
V$="|   " 'vertical line
H$="-"*9 'horizontal line
PRINT H$    '---------
PRINT V$,V$ '|       |
PRINT H$    '---------
PRINT V$*3  '|   |   |
PRINT "x"*9 'xxxxxxxxx
PRINT V$*3  '|   |   |
PRINT H$    '---------
PRINT V$,V$ '|       |
PRINT H$    '---------

```

`,` in `PRINT` is a tab, and luckily the default size is perfect for this challenge.
> 0 votes

# Answer
# Java 8, 98 bytes

Store repeated lines and add it all together.

```
()->{String a="---------\n",b="|       |\n",c="|   |   |\n";return a+b+a+c+"xxxxxxxxx\n"+c+a+b+a;}

```
> 0 votes

# Answer
# C#, 88 bytes

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

```

Anonymous function which returns the tennis court as a string.

Full program with ungolfed method:

```
using System;

namespace LetsPlayTennis
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string> f =
            () =>
            {
                string a = "---------\n",
                    b = "|   |   |\n";
                return (a += "|\t|\n" + a)
                    + b
                    + "xxxxxxxxx\n"
                    + b
                    + a;
            };

            Console.WriteLine(f());
        }
    }
}

```
> 0 votes

# Answer
# Pip `-l`, 31 bytes

```
"--x--"M_X9WV:" || "M_WRsX3WR'|

```

Try it online!

### Explanation

We construct the even rows, then the odd rows, and then weave them together.

```
"--x--"M_X9WV:" || "M_WRsX3WR'|
                                 s is space (implicit)
       M                         Map this function
"--x--"                          to each character of this string:
        _X9                       Repeat the character 9 times
                                 The result is a list of five 9-character strings

                    M            Map this function
              " || "             to each character of this string:
                     _            The character
                      WR          wrapped on each side in
                        sX3       three spaces
                           WR'|   wrapped on each side in |
                                 The result is a list of four 9-character strings

           WV:                   Weave the two lists together (the : helps with parsing)
                                 Print, with each list element on its own line (-l flag)

```
> 0 votes

# Answer
## MBASIC, 89 bytes

```
1 WIDTH 13:P$="---------":S$="|       |":T$="|   |   |":PRINT $S$P$T$"xxxxxxxxx"T$P$S$P$

```

More abuse of the WIDTH directive to save multiple PRINTs.
> 0 votes

# Answer
# , 76 bytes

```
"*"=strrep;write(c(a<-c(b<-"-"*9,"|       |",b,"|   |   |"),"x"*9,rev(a)),1)

```

Try it online!
> 0 votes

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


title: What Inning is it?

text:
# Question
Title: What Inning is it?
# Goal

In light of the World Series being around the corner, I need a program that can read the box scores and tell me what inning it is. This is complicated slightly because baseball uses an odd method to record the score. They don't write down the at-bat team's score for the inning until they've scored a run (and are still going) or have finished their at-bat. Thus a 0 on the scoreboard always means a finished at-bat. For example:

```
Example A:
Inning| 1| 2| 3| 4| 5| 6| 7| 8| 9|
  Them| 0| 0| 0| 0| 0| 2|  |  |  |
    Us| 0| 0| 2| 0| 0| 0|  |  |  |

Example B:
Inning| 1| 2| 3| 4| 5| 6| 7| 8| 9|
  Them| 0| 0| 0| 0| 0| 2|  |  |  |
    Us| 0| 0| 2| 0| 0| 1|  |  |  |

Example C:
Inning| 1| 2| 3| 4| 5| 6| 7| 8| 9|
  Them| 0| 0| 0| 0| 0| 2|  |  |  |
    Us| 0| 0| 2| 0| 0|  |  |  |  |

#Them is the Away Team, Us is the Home Team (who are the guys you root for)

```
* Example A: We know we're at the top of the 7th because Us has a recorded 0 in the Bottom of the 6th and the Top of the 7th is blank.
* Example B: It can either be the Bottom of the 6th or the Top of the 7th.
* Example C: It can either be the Top or Bottom of the 6th.

Your task is to return which inning(s) it could be.

# Input

Two lists of non-negative integers. Lists will be assumed jagged with the Away team's list being either the same size or one element larger in comparison to the Home team's. You can take the scores in either order but state in your answer if you do not use the default. I.e., Away Team then Home team (the default), or Home team then Away team (reversed). They can also be padded with dummy data if you want, state in your answer if you do so.

# Output

A string or something equivalent which identifies the inning number and whether it's the top or bottom. E.g. `7B 8T`, `B7 T8`, `['7B','8T']` are all fine. If there are two answers, you must output both. The format is pretty flexible though.

# Rules

* Input will always be valid
* Games can go into indefinite extra innings. Your program should be able to support up to 255 innings.
* Standard Loopholes are forbidden
* This is so shortest code wins

# Test Cases

```
#Input:
[[],
 []]
#Output: 1T

#Input:
[[0],
 []]
#Output: 1B

#Input:
[[0,0,0,1],
 [0,0,0,0]]
#Output: 5T

#Input:
[[0,0,0,1],
 [0,0,0,1]]
#Output: 4B, 5T

#Input:
[[0,0,0,1,0,0,1,0,0,1],
 [0,0,0,0,1,0,0,1,0,1]]
#Output: 10B, 11T

#Input:
[[0,0,0,1],
 [0,0,0]]
#Output: 4T, 4B

#Input:
[[0,0,0,0],
 [0,0,0]]
#Output: 4B

```

# Answer
> 4 votes
# C (gcc), 50 bytes

Takes input as a pointer to an interleaved list (i.e. `{them#1, us#1, them#2,...}`).

Returns one option via modification, and the other via return value.

Negative values indicate bottom of the inning, positive values indicate top of the inning. Zeroes are "empty". The absolute value of the output is the number of the inning. So, `-4,5` indicates the possibilities being top of the fifth and bottom of the fourth, and `1,0` indicates the only possibility being the top of the first.

The return value of the macro can be used to determine whether there's one or two possible innings; the return value is `0` if there's no other inning. Otherwise, it is the number of the inning.

Zero bytes of source code. Use the following as a preprocessor flag:

```
-Df(o,n,l)=({o=n%2?~n/2:n/2+1;l[n-1]?-o-~n%2:0;})

```

Try it online!

## Degolf

```
-Df(o,n,l)=({
// Define a function-like macro f(o,n,l)
// o is the output variable, n is the size of the list,
// l is a pointer to the first element of the list.
o=n%2?~n/2:n/2+1;
// If there's an odd number of elements, first possible inning is -(n+1)/2.
// Else, it is (n/2)+1.
l[n-1]?-o-~n%2:0})
// If the score from the last inning is non-zero, the other possible inning
// needs to be determined; flip the sign of first output value then deduct
// 1 from it if the number of elements is even.

```

# Answer
> 3 votes
# Perl 6, ~~52 48~~ 45 bytes

*-3 bytes thanks to some restructuring from nwellnhof!*

```
->\a,\b{(+a,a==b if (b,a)[a>b].tail;b+1,a>b)}

```

Try it online!

Anonymous code block that takes input as two lists, top then bottom. Output is a list of tuples, where the first element is the inning number and the second element is True or False, corresponding to Bottom or Top.

### Explanation:

```
       {                                    }  # Anonymous code block
->\a,\b   # That takes input lists a and b
        (                                  )   # Return a list of
                                    b+1,a>b    # A list of
                                               #  The length of the second list plus 1
                                               #  And top/bottom
         +a,a==b     # And the length of the first list
                     # And the other of top/bottom
                 if  # Only if:
                    (b,a)[a>b]      # The current of top/bottom's
                              .tail # Last element exists and is not 0

```

# Answer
> 3 votes
# , ~~103~~ 96 bytes

```
function(a,b,l=sum(a|1),k=sum(b|1))I(l,I(l-k,I(a[l],c(l,-l),-l),I(b[l],c(-l,l+1),l+1)),1)
I=`if`

```

Try it online!

*@digEmAll saved 7 bytes!*

Takes two ~~lists~~ vectors as input, and outputs one or two integers representing the possible innings. Positive integers are the top of the inning, and negative integers are the bottom of the inning.

In R, positive integers are truthy, so I can use the difference in lengths as the first argument to `if()`.

# Answer
> 2 votes
# JavaScript (Node.js), 75 bytes

```
f=(a,c=1,p=0,z=0)=>1/(t=a[p][c-1])?f(a,c+p,1-p,t):[c,p]+(z?[,c+p-1,1-p]:'')

```

Try it online!

# Answer
> 2 votes
# Python 2, ~~135~~ ~~129~~ ~~126~~ ~~125~~ ~~123~~ 119 bytes

```
a,b=input()
c=len(a)
e,f=`c+1`+"T",`c`+"B"
print((f+e,e)[b[-1]<1],(`c`+"T"+f,f)[a[-1]<1])[len(b)<c]if b else"1"+"TB"[c]

```

Try it online!

-1 with thanks to @ovs

-4 thanks again to @ovs

# Answer
> 2 votes
# Jelly, 11 bytes

```
ZẎṖṠṪ$Ð¡Ẉd2

```

Try it online!

First element: 0-based index of column.
Second element: `0` for top, `1` for bottom.

Output is a list of one or two pairs as specified above (prettified to show it better). The output innings are in reverse order.

# Answer
> 1 votes
# Python 2, 65 bytes

```
a,b=input()
exec"a,b=[0]+b,a;print[len(b)][a[-1]<len(a+b)%2:];"*2

```

Try it online!

Prints two lines, first the bottom inning possibility then the top one, as a singleton list. If either one is not possible, that list is empty.

# Answer
> 1 votes
# Clean, ~~84~~ 75 bytes

```
import StdEnv
$ =length
?v|last[0:v]>0= $v=0
@a b| $b< $a=(?a,$a)=($a+1,?b)

```

Try it online!

Defines the function `@ :: [Int] [Int] -> (Int, Int)` and some helpers.
Gives output in the form `(Top, Bottom)` where a zero signifies a null possibility.

---
Tags: code-golf
---