title: Easy binary triangle

text:
# Question
Title: Easy binary triangle
Given as input a positive integer `n>=1`, output the first `n` rows of the following triangle:

```
                  1
                1 0 1
              0 0 1 0 0
            1 1 1 0 1 1 1
          0 0 0 0 1 0 0 0 0
        1 1 1 1 1 0 1 1 1 1 1
      0 0 0 0 0 0 1 0 0 0 0 0 0
    1 1 1 1 1 1 1 0 1 1 1 1 1 1 1
  0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1

```

The rows alternate between all zeroes and all ones, except the center column is flipped.

## Test cases

* **Input**: `3`
* **Output**:

```
    1
  1 0 1
0 0 1 0 0

```
* **Input**: `10`
* **Output**:

```
                  1
                1 0 1
              0 0 1 0 0
            1 1 1 0 1 1 1
          0 0 0 0 1 0 0 0 0
        1 1 1 1 1 0 1 1 1 1 1
      0 0 0 0 0 0 1 0 0 0 0 0 0
    1 1 1 1 1 1 1 0 1 1 1 1 1 1 1
  0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1

```

Your code must work for any `n<100`. This is , hence the shortest code in bytes wins!

Trailing spaces / newlines and leading newlines are allowed!

# Answer
> 7 votes
# Jelly, 7 bytes

```
Ṭ=Ḃµ€ŒB

```

Try it online!

-1 byte thanks to Erik the Outgolfer

# Explanation

```
Ṭ=Ḃµ€ŒB  Main link
    €    For each element in (implicit range of) the input:
Ṭ        List 1s and 0s with 1s in the indices in the left argument (generates `[0, 0, ..., 1]`)
 =Ḃ      Is this equal to `(z % 2)` where `z` is the range number? (Every other row is flipped)
     ŒB  Reflect each row

```

# Answer
> 4 votes
# Python 2, 50 bytes

```
lambda n:[i*`i%2`+`~i%2`+i*`i%2`for i in range(n)]

```

**Try it online!**

This returns the rows as a list of Strings.

# Python 2, ~~67 65~~ 63 bytes (formatted)

```
n=input()
for i in range(n):k=i*`i%2`;print(n-i)*" "+k+`~i%2`+k

```

**Try it online!**

This outputs with a trailing space on each line.

# Answer
> 3 votes
# Jelly, 8 bytes

```
⁼€=ḂŒḄµ€

```

Try it online!

-2 thanks to HyperNeutrino.

# Answer
> 3 votes
# Python 2, 50 bytes

```
lambda n:[[i%2]*i+[~i%2]+i*[i%2]for i in range(n)]

```

Try it online!

# Python 2, 53 bytes

```
lambda n:[(([i%2]*i+[~i%2])*2)[:-1]for i in range(n)]

```

Try it online!

# Python 2, 67 bytes

```
lambda n:[[[i%2,~i%2][j==i]for j in range(2*i+1)]for i in range(n)]

```

Try it online!

# Answer
> 3 votes
# Japt, ~~12~~ 9 bytes

```
õÈÇ¥Y^uÃê

```

Test it online!

~~Quite~~ Slightly sad compared to Jelly, but Japt doesn't have anything like  so I must make do with what I have...

### Explanation

```
 õÈ   Ç   ¥ Y^ uÃ ê
UõXY{XoZ{Z==Y^Yu} ê}      Ungolfed
                          Implicit: U = input number
Uõ                        Create the range [1..U].    [1, 2, 3, 4]
  XY{              }      Map each item X and 0-index Y in this to
     Xo                     Create the range [0..X).  [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
       Z{      }            Map each item Z in this to
         Z==Y                 Z is equal to Y         [[1], [0, 1], [0, 0, 1], [0, 0, 0, 1]]
             ^Yu              XORed with Y % 2.       [[1], [1, 0], [0, 0, 1], [1, 1, 1, 0]]
                  ê         Bounce.                   [[1],
                                                       [1, 0, 1],
                                                       [0, 0, 1, 0, 0],
                                                       [1, 1, 1, 0, 1, 1, 1]]
                          Implicit: output result of last expression

```

# Answer
> 3 votes
# Pyth, 14 bytes

*Thanks to @Jakube for saving 2 bytes!*

```
ms_+Bm%d2d%hd2

```

Try it here!

# Pyth, 15 bytes

*Thanks a lot to @Jakube for -1 byte*

```
m++K*d]%d2%td2K

```

Try it here.

# Pyth, 16 bytes

```
m++K*d`%d2`%td2K

```

Try it here.

# Answer
> 3 votes
# , 73 bytes

Thanks to Giuseppe! Nice catch.

```
n=scan();for(i in 1:n)cat(c(rep(" ",n-i),x<-rep(1-i%%2,i-1)),i%%2,x,"\n")

```

Try it online!

# , 78 bytes

```
n=scan();for(i in 1:n)cat(x<-c(rep(" ",n-i),rep(1-i%%2,i-1)),i%%2,rev(x),"\n")

```

Try it online!

# , 82 bytes

```
n=scan();for(i in 1:n){j=i%%2;x=c(rep(" ",n-i),rep(1-j,i-1));cat(x,j,rev(x),"\n")}

```

Try it online!

# , 110 bytes - output to stdout

```
m=matrix(x<-rep_len(0:1,n<-scan()),n,n-1);m[upper.tri(m,T)]=" ";for(i in 1:n)cat(rev(m[i,]),1-x[i],m[i,],"\n")

```

Try it online!

# , 130 bytes - output to a file

```
m=matrix(x<-rep_len(0:1,n<-scan()),n,n-1);m[upper.tri(m,T)]=" ";for(i in 1:n)cat(rev(m[i,]),1-x[i],m[i,],"\n",file="a",append=i>1)

```

Try it online!

Writing out to a file as I do not know how to fit it in the console if `n==99` (see the result here).

# Answer
> 3 votes
# Mathematica, 77 bytes

```
Table[CellularAutomaton[51,{{1},0},#,{All,All}][[i]][[#-i+2;;-#+i-2]],{i,#}]&

```

**@Not a tree** golfed it down to 48 bytes!

# Mathematica, 48 bytes

```
#&@@@NestList[CellularAutomaton@51,{{1},0},#-1]&

```

# Answer
> 1 votes
# Pascal, ~~181~~ 154 bytes

*27 bytes saved thanks to @ThePirateBay*

```
procedure f(n:integer);var i,j:integer;begin for i:=1to n do begin write(' ':(n-i+1)*2);for j:=1to i*2-1do write((ord(j<>i)+i)mod 2,' ');writeln()end end;

```

Try it online!

**Unglofed**

```
procedure f (n: integer);
    var i, j: integer;
    begin
        for i := 1 to n do
        begin
            write(' ': (n-i+1) * 2);
            for j := 1 to i*2-1 do
                write((ord(j<>i) + i) mod 2, ' ')
            writeln()
        end
    end;

```

# Answer
> 1 votes
# Retina, 25 bytes

```
.+
$*0
0
1$`¶
T`d`10`¶.*¶

```

Try it online! Explanation: The first stage converts the input into a string of zeros of that length. The second stage then takes all of the prefixes of that string (not including the string itself) and prefixes a 1 to them. The third stage then toggles the bits on alternate lines.

# Answer
> 1 votes
# Mathematica, 90 bytes

```
Array[(x=Table[1,f=(2#-1)];x[[⌈f/2⌉]]=0;If[#==1,{1},If[OddQ@#,x/.{1->0,0->1},x]])&,#]&

```

# Answer
> 1 votes
# Perl 5, 58 + 1 (-n) = 59 bytes

```
say$"x(2*--$_).($/=$i%2 .$")x$i.(1-$i%2).$".$/x$i++while$_

```

Try it online!

~~\# Perl 5, 59 + 1 (-n) = 60 bytes~~

```
say$"x(2*--$_).($i%2 .$")x$i.(1-$i%2).($".$i%2)x$i++while$_

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 24 21 18 bytes

```
FNÉN×NÈJûIN>-úˆ}¯»

```

Try it online!

---

Edit: Well, it is my first 05AB1E golf so I'm not surprised things can be golfed. Edit history:

# Answer
> 0 votes
# SOGL V0.12, 13 bytes

```
∫:2\r*Kr1κ+╥T

```

Try it Here!

# Answer
> 0 votes
# Charcoal, 18 bytes

```
ＥＮ⪫ＩＥ⁺¹ι﹪⁺ι¬λ² ‖Ｏ←

```

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

```
ＥＮ              For each of the input number of rows
  ⪫             Join with spaces
   Ｉ            Convert to string
    Ｅ⁺¹ι        For each column
        ﹪⁺ι¬λ²  Calculate the digit
‖Ｏ←             Reflect to the left

```

# Answer
> 0 votes
# JavaScript, ~~140~~ 132 bytes (with proper formatting)

```
n=>{A=Array;a='';b=0;for(x of A(n)){for(c of A(n-b))a+=' ';for(c of A(b))a+=b%2;a+=(b+1)%2;for(c of A(b))a+=b%2;a+='\n';b++}return a}

```

Try It Online

# Answer
> 0 votes
# JavaScript (ES6), ~~74~~ ~~73~~ ~~71~~ ~~68~~ 64 bytes

**-7 bytes** by @Neil

```
f=n=>n--?[...f(n), [...Array(n-~n)].map((v,i)=>(n+(i==n))%2)]:[]

```

Try it online!

Simple recursive function that generates the lines one by one. Outputs as array of array of numbers.

---

Outputs as formatted string:

# JavaScript (ES6), ~~122~~ ~~119~~ 118 bytes

```
f=(n,w=2*n+1,N=n,s=" ".repeat((N-n)*2))=>(--n?f(n,w,N)+s+[...Array(n-~n)].map((v,i)=>(n+(i==n))%2).join(" "):s+1)+"\n"

```

Try it online!

# Answer
> 0 votes
# Haskell, 54 bytes

Straight forward list comprehension:

```
f n=[k++[mod i 2]++k|i<-[1..n],k<-[mod(i+1)2<$[2..i]]]

```

Try it online!

# Answer
> 0 votes
# J, 32 bytes

```
3 :'-.^:(2|y)(=|.)i.>:+:y'&.>@i.

```

Try it online! This is an anonymous function that returns a boxed list of values.

I like to imagine that the explicit function definition saves bytes by virtue of removing caps and such, but it probably adds a few bytes in comparison to a tacit answer.

# Explanation

```
3 :'-.^:(2|y)(=|.)i.>:+:y'&.>@i.
                              i. For i = 0 ... input - 1
3 :'-.^:(2|y)(=|.)i.>:+:y'        Explicit function: compute nth row
                    >:+:y          2n+1
                  i.               Range [0,2n+1)
             (=|.)                 Equate range to reversed range
                                    (yield 0 0 0 ... 1 ... 0 0 0)
                                   If
                                    n = 1 (mod 2)
                                   Then
                                    Negate each value
                          &.>     Box

```

# Answer
> 0 votes
# 05AB1E, 11 bytes

```
FN°SRNF_}ûˆ

```

Try it online!

**Explanation**

```
F             # for N in range [0 ... input-1] do:
 N°           # push 10^N
   S          # split to list of digits
    R         # reverse
     NF_}     # N times do: logical negation
         û    # palendromize
          ˆ   # add to global list
              # implicitly display global list

```

# Answer
> 0 votes
# , 17 bytes

```
(2&|~:0=i:)&.>@i.

```

Try it online!

Outputs a list of boxed arrays.

## Explanation

```
(2&|~:0=i:)&.>@i.  Input: n
               i.  Range from 0 to n, exclusive end
           & >     Unbox each and perform on each x
        i:           Range from -x to x, inclusive
      0=             Equal to 0
    ~:               Not equal
 2&|                 x mod 2
           &.>       Perform inverse of unbox (box)

```

# Answer
> 0 votes
# Java 8, ~~121~~ ~~111~~ ~~109~~ 101 bytes

```
n->{String r[]=new String[n],t;for(int i=0,j;i<n;r[i++]=t+i%2+t)for(j=0,t="";j++<i;t+=i%2);return r;}

```

My current byte-score (101) is also a row of the binary triangle. :)

**Explanation:**

Try it here.

```
n->{                         // Method with integer parameter and String-array return-type
  String r[]=new String[n],  //  Result String-array
         t;                  //  Temp String
  for(int i=0,j;             //  Some index-integers
      i<n;                   //  Loop (1) from 0 to `n` (exclusive)
      r[i++]=                //    After every iteration, set the next row to:
        t+                   //     `t` +
        i%2                  //     Center digit (`i` has already been raised by 1 now)
        +t)                  //     + `t` again
    for(j=0,t="";            //   Reset index `j` and the temp-String `t`
        j++<i;               //   Inner loop (2) from 0 to `i` (exclusive)
      t+=i%2                 //    Append `t` with an outer digit
    );                       //   End of inner loop (2)
                             //  End of loop (1) (implicit / single-line body)
  return r;                  //  Return resulting String-array
}                            // End of method

```

# Answer
> 0 votes
# GolfScript, 49 bytes

```
~.:a;0\{..1+2%.!""+@*+" "a(:a*+.1>-1%\+"\n"+\)}*;

```

Try it online!

---
Tags: code-golf, sequence, binary
---


# Question
Title: Use 16 colors while writing Hey! 4 times
i.e each byte appears in a different ANSI shell colour.

# Rules

* Resetting the color of the shell after output is not required
* Must be output in STDOUT or the primary colour text output of your language.
* Must be done programmatically (iterating through each color and letter of the string induvidually) instead of just writing a fixed string to shell like the reference command.
* Must output the same as the reference command: `echo -e '\e[30mH\e[31me\e[32my\e[33m!\e[34mH\e[35me\e[36my\e[37m!\e[90mH\e[91me\e[92my\e[93m!\e[94mH\e[95me\e[96my\e[97m!'` on a recent version of bash (I am using 4.3 installed via Homebrew on OS X) i.e like this:  Obviously colours will vary based on terminal colour scheme.

# Scoring

This is , so lowest bytes wins.

# Answer
> 7 votes
# Bash, 62

```
h=y!He
for i in {3,9}{0..7};do printf \\e[${i}m${h:i%4:1};done

```

Must be run from an actual script file. If you want to try it from the command line, you'll need to escape the `!`, i.e. `h=y\!He`

Online.

# Answer
> 3 votes
# C, 126 bytes

```
#define a"\x1B[%d;%dm"
#define b j,i++
i,j;main(){for(;i=30,j<2;j++)printf(a"H"a"e"a"y"a"!"a"H"a"e"a"y"a"!",b,b,b,b,b,b,b,b);}

```

*output may vary depending on your compiler, linker, operating system, and processor*

Ideone doesn't have colour output, so have a screenshot from my phone:

# Answer
> 2 votes
# bash, ~~101~~ 72 bytes

29 bytes saved with a trick from @DomHastings.

```
s='y!He'
for i in {30..37} {90..97}
do
printf "\e["$i"m"${s:$i%4:1}
done

```

If I hadn´t scrambled the string, this would have been 105 (`($i+2)%4` instead of `$i%4`), just as my
**previous approach, 105 bytes**

```
function p
{
s='Hey!'
for i in {0..3}
do
let r=i+$1
printf "\e["$r"m"${s:$i:1}
done
}
p 30;p 34;p 90;p 94

```

# Answer
> 2 votes
# dc, ~~72~~ 71 bytes

```
Fi4C 2:c6B 3:c81 0:c23 1:c28si20[d1CP61Pn74Pd4%;cP1+dli>P]dsPx68si60lPx

```

Of course the escape codes won't render right on TIO, but you can still try it online!

First we set our input to base 15, this is solely for the sake of saving a byte. Make an array, `c`, of the code points for 'y', '!', 'H', and 'e'. We'll exploit the fact that 30 mod 4 == 90 mod 4; for both of our sets of color values, value mod 4 starts at 2, so that's where we put our 'H' in the array. From there it's just a matter of setting up a loop that runs until we hit the value stored in `i`. We have our color code on the stack, we print the necessary escape codes, print the stack value, mod 4 and print that value from the array `c`, then increment the stack. We run through this once starting from 30 w/ `i` set at 38, then once more starting from 90 w/ `i` set at 98.

Shaved off one byte by doing everything in base 15; decimal version below for slightly more clarity:

```
72 2:c101 3:c121 0:c33 1:c38si30[d27P91Pn109Pd4%;cP1+dli>P]dsPx98si90lPx

```

# Answer
> 1 votes
# J, 59 bytes

```
echo,(u:27 91),"1(16$'Hey!'),.~'m',.~,/30 90":@+/i.8
exit''

```

Save it as a script to run using J. It will print the output to stdout with the escaped colors.

# Answer
> 1 votes
# Octave, 78 bytes

```
c=[b=[a="\x1b[30m"' a a a;'Hey!'] b];c(4,:)+=0:7;d=c;d(3,:)+=6;disp([c d](:)')

```

Usage:

If the code is in a file `hey.m`:

```
$ octave hey.m
Hey!Hey!Hey!Hey!

```

# Answer
> 1 votes
# APL (Dyalog), ~~38~~ 41 bytes

Now returns right result too!

```
∊(⍕¨∊29 89∘.+⍳8){'\e[',⍺,'m',⍵}¨16⍴'Hey!'

```

Try it online!

`16⍴'Hey!'` cyclically **r**eshape the string to length 16

`(``){` apply the below anonymous function to each letter pairing it with the corresponding element for this list as left argument:

`⍳8` 1 through 8
`29 89∘.+` addition table with these numbers vertically and those horizontally
**ϵ**nlist (flatten)
`⍕¨` format (stringify) each

`'m',⍵` prepend an "m"
`⍺,` prepend the left argument
`'\e[',` prepend the string

**ϵ**nlist (flatten)

# Answer
> 1 votes
# Python 3, 81 bytes

```
print(*['\33[%sm%s'%(i,'Hey!'[i%4-2])for i in range(30,98)if not 37<i<90],sep='')

```

A full program that prints to STDOUT.

**How it works**

```
for i in range(30,98)...       For all possible colour codes i in [30,97]...
...if not 37<i<90              If i is in the desired range [30,37] or [90,97]...
'\33[%sm%s'%(i,'Hey!'[i%4-2])  ...create a string of the form
                               '\033[{colour code}m{current string character}'...
[...]                          ...and store all strings in a list X
print(*...,sep='')             Print all strings in X with no separating space

```

Try it on CodingGround

# Answer
> 1 votes
## Pyke, 25 bytes

```
"Hey!"4*F\mo8.D6*3+"["s_

```

Try it here!

```
                           - o = 0
"Hey!"4*                   -   "Hey!Hey!Hey!Hey!"
        F                  -  for i in ^:
                           -   stack = [i]
         \m                -   stack.append("m")
           o               -    o += 1
            8.D            -   stack.extend(divmod(^, 8))
               6*3+        -   stack[-1] = stack[-1]*6+3
                   "["     -   stack.append("[\x1b")
                        s  -   stack = sum(stack)
                         _ -  stack = reverse(stack)
                           - print "".join(^)

```

# Answer
> 1 votes
# SmileBASIC, 39 bytes

```
FOR I=0TO 15COLOR I?("Hey!"*4)[I];
NEXT

```

# Answer
> 1 votes
# 4, 392 bytes

```
3.600486014960250603516045260553606546075560957610276119161318012111362072623336241062530021112402211255105115035005125205105115035015125215105115035025125225105115035035125235105115035045125205105115035055125215105115035065125225105115035075125235105115095005125205105115095015125215105115095025125225105115095035125235105115095045125205105115095055125215105115095065125225105115095075125234

```

Try it online!

Tip: use the `-verb`ose flag.

# Answer
> 1 votes
## Perl 5, 50 bytes

**49 bytes code + 1 for `-p`. Note that `\x1b` is a literal escape character. Utilises empty input which TIO doesn't support, so a newline is provided and not used.**

```
$_="Hey!"x4;s/./\x1b[@{[(30..37,90..97)[$-++]]}m$&/g
```

Try it online!

# Answer
> 1 votes
# PowerShell, 41 Bytes.

```
0..15|%{Write-Host -n('Hey!'[$_%4])-f $_}

```

The day we get an alias for Write-Host is a good day.

# Answer
> 0 votes
# JavaScript 134 bytes

```
<script>
  var a=0;
  var c=["H","e","y","!"];
  for(;a<3;){
    var b=-1;
    for(;++b<4;){
      document.write(<b style='color:rgb(0,0,"+(a*4+b)+"'>"+c[b]);
    }
  }
</script>

```

Golfed

```
<script>a=0;c=["H","e","y","!"];for(;a++<3;){b=-1;for(;++b<4;){document.write(<b style='color:rgb(0,0,"+(a*4+b)+"'>"+c[b]);}}</script>

```

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


title: Is it a good 2048 board?

text:
# Question
Title: Is it a good 2048 board?
*This is my first question here, so any suggestions in the comments would be appreciated! Thanks ;)*

# Introduction

One very common strategy for the 2048 game is *never ever swiping down*. This positions all the big numbers at the top, and the lower ones in the bottom. So, if you apply this strategy correctly, your board will always match the following pattern:

# The pattern to check for / Your task

Your submission should be either a full program or a function which returns a truthy value if the board can be described like this: Going down each column of the board, the first number should be the highest of the column, the second number should be less than or equal to the first number, etc. A **good 2048-board** is defined as a board where the highest numbers are all on the top. This is **code-golf**, so the shortest Code per language (in bytes) wins.

# I/O

The input can be taken in any appropriate way, for example an array of 4 arrays, each containing 4 numbers, or an array of 16 numbers. **In total, it will be always 16 numbers, representing the 4x4 board** The output should be a truthy value of the input is a "good 2048-board", and a falsy value otherwise.

# Examples

Truthy:

```
|-------------------|
| 16 |    | 64 |  8 |
|-------------------|
|  8 |    | 32 |  8 |
|-------------------|
|  4 |    | 32 |  2 |
|-------------------|
|  2 |    |    |    |
|-------------------|

|-------------------|
| 16 | 128| 64 | 32 |
|-------------------|
|  8 | 128| 32 |  8 |
|-------------------|
|  4 | 16 |  8 |  2 |
|-------------------|
|  4 |    |    |    |
|-------------------|

```

Falsy:

```
|-------------------|
| 16 |    | 64 |  8 |
|-------------------|
|  8 |    | 32 | 16 |
|-------------------|
| 32 |    | 128|  2 |
|-------------------|
|  2 |    |    |    |
|-------------------|

|-------------------|
| 16 | 128| 64 | 32 |
|-------------------|
|  8 |  32|    |  8 |
|-------------------|
|  4 | 16 |  8 |  2 |
|-------------------|
|  4 |    |    |    |
|-------------------|

```

# Note

**Look at the 2nd falsy test case: When there is an empty value (or a 0) somewhere and even when it's followed by a value which is higher than the last non-zero number, this should be falsy, because the next value after the zero would be higher than the 0 itself, which makes it invalid.**

Good luck!

# Answer
> 16 votes
# Haskell, 21 bytes

```
all$scanr1 max>>=(==)

```

Try it online!

Takes a list of columns, with empty spaces as 0.

# Answer
> 10 votes
# 05AB1E, 4 bytes

```
€{íQ

```

Try it online!

Same as my other two answers. I promise this is my last one until others have answered :)

# Answer
> 9 votes
# APL (Dyalog), ~~7~~ 4 bytes

Takes 4-by-4 matrix, using 0 for blanks, as argument.

```
⊢≡⌊⍀

```

Try it online!

`⌊⍀` is the vertical cumulative minimum

identical to

the unmodified argument?

# Answer
> 7 votes
# Jelly, 4 bytes

```
Ṣ€U⁼

```

Try it online!

Input as an array of columns. Works with arbitrary-sized grids.

# Answer
> 7 votes
# R (+pryr), 23 bytes

```
pryr::f(all(diff(x))<1)

```

Which evaluates to the function

```
function (x)
all(diff(x)) < 1

```

Which takes a matrix as input:

```
     [,1] [,2] [,3] [,4]
[1,]   16    0   64    8
[2,]    8    0   32    8
[3,]    4    0   32    2
[4,]    2    0    0    0

```

When given a matrix, `diff` automatically calculates the differences within rows (surprisingly. I didn't know of this feature until I tried it for this challenge).

```
     [,1] [,2] [,3] [,4]
[1,]   -8    0  -32    0
[2,]   -4    0    0   -6
[3,]   -2    0  -32   -2

```

None of these values can be 1 or higher in a good board, so we test for `<1` and see if `all` values of the matrix comply.

```
     [,1] [,2] [,3] [,4]
[1,] TRUE TRUE TRUE TRUE
[2,] TRUE TRUE TRUE TRUE
[3,] TRUE TRUE TRUE TRUE

[1] TRUE

```

# Answer
> 6 votes
# Python 3, 42 bytes

```
lambda l:all(x==sorted(x)[::-1]for x in l)

```

Try it online!

Same algorithm as my Jelly answer

# Answer
> 5 votes
# JavaScript, 37 bytes

```
x=>''+x==x.map(v=>v.sort((x,y)=>y-x))

```

Call it like this:

```
|-------------------|
| 16 |    | 64 |  8 |
|-------------------|
|  8 |    | 32 |  8 |
|-------------------|
|  4 |    | 32 |  2 |
|-------------------|
|  2 |    |    |    |
|-------------------|

f([[8,8,2,0],[64,32,32,0],[0,0,0,0],[16,8,4,2]])

```

Tested on Firefox, Chrome, JavaScript Shell, and, Node.js.

# Answer
> 4 votes
# C# (.NET Core), 71 bytes

```
i=>{for(int n=3;++n<i.Length;)if(i[n]>i[n-4])return false;return true;}

```

Try it online!

The BORING way. Expects input flattened into a linear array.

Alternatively the explicitly forbidden way:

```
i=>{for(int n=3;i[++n]<=i[n-4];);}

```

Try it online!

Throws an IndexOutOfBoundsException to indicate true, ends normally to indicate false. I tried a version that included conversion from exception/no exception to true/false, but it ended up just as long as the regular version.

# Answer
> 4 votes
# JavaScript, ~~34~~, 32 bytes

```
v=>!v.some((x,i)=>i%4&&x>v[i-1])

```

Call by passing in a single array containing the first column, followed by the 2nd, 3rd, and 4th.

Compares each number to the previous number except for the first number of each column and returns true if all are true.

## Test

```
f=v=>!v.some((x,i)=>i%4&&x>v[i-1])

f([16,8,4,2,0,0,0,0,64,32,32,0,8,8,2,0])
f([16,8,4,4,128,128,16,0,64,32,8,0,32,8,2,0])
f([16,8,32,2,0,0,0,0,64,32,128,0,8,16,2,0])
f([16,8,4,4,128,32,16,0,64,0,8,0,32,8,2,0])

```

Edit: saved 2 bytes thanks to tsh

# Answer
> 3 votes
# Haskell, 28 bytes

```
all$and.(zipWith(>=)=<<tail)

```

There's also

```
all$(==)=<<sort

```

with 15 bytes but it requires `import Data.List` when working with the Prelude only. Alternatively,

```
all$(==)=<<Data.List.sort

```

with 25 bytes works in GHCI.

# Answer
> 3 votes
# Gaia, ~~3~~ 6 bytes

+3 bytes because apparently I didn't know how my language worked

```
ọ¦_ẏ⁇!

```

This is a function accepting a list of columns and leaving the result on the stack.

A few other 6 byte solutions exist including `0+¦o¦ẏ` and `ọ¦_ẏ¦ỵ`.

Try it online!

### Explanation

```
ọ¦      Deltas of each column
  _     Flatten
   ẏ⁇   Keep only positive numbers
     !  Negate (is it empty?)

```

# Answer
> 3 votes
# TI-BASIC, 25 bytes

Takes input as a 4x4 matrix in Ans.

```
For(R,1,3
*row+(-1,Ans,R+1,R
End
Ans=abs(Ans

```

# Explanation

```
For(R,1,3             Loop from row 1 to 3.

*row+(-1,Ans,R+1,R    Multiply row R+1 by -1 and add it to row R in-place.
                      Effectively, this subtracts row R+1 from row R.

End                   Now the first 3 rows contain the row differences,
                      and the 4th row is non-negative assuming valid input.

Ans=abs(Ans           Check whether every element in the matrix is equal to its
                      absolute value, or in other words, contains no negative values.

```

# Answer
> 2 votes
# Haskell, 41 bytes

```
f[x]=1>0
f(a:b:c)|a<b=1<0|1>0=f$b:c
all f

```

Try it online!

Defines the point-free function `all f`, where `f` determines if a list is sorted.

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

Takes an array of columns; returns a (truthy) number or `false`.

```
a=>a.every(c=>c.reduce((r,n)=>r&&n<=r&&n))

```

---

# JavaScript (ES6), ~~54~~ 47 bytes

First attempt. Takes an array of columns; returns `true` or `false`.

```
a=>a.every(c=>c.slice(1).every((n,i)=>n<=c[i]))

```

# Answer
> 2 votes
# Swift 4, ~~84~~  77 bytes

```
func f(l:[[Int]]){print(l.filter{$0.reversed()==$0.sorted()}.count==l.count)}

```

**Try it online!**

# Answer
> 2 votes
# MATL, 4 bytes

```
SGX=

```

Try it online!

Input as an array of rows, upside down.

```
S       % sort columns
GX=     % compare with input
        % true if arrays are numerically equal
        % (implicit) convert to string and display

```

# Answer
> 2 votes
# Japt, ~~7~~ 5 bytes

Takes input as a 2D array of columns. Empty cells are `0` or can be omitted if there are no other numbers in the column.

```
eUËnw

```

Try it

```
eUËnw     :Implicit input of 2D array U
e         :Test for equality with
 UË       :  Map U
   n      :    Sort each by
    w     :    Maximum

```

# Answer
> 2 votes
# Dyalog APL, ~~21~~ ~~19~~ 15 bytes

```
∧/{⍵≡⍵[⍒⍵]}¨↓⍉⎕

```

Try it online! (modified so it will run in tryapl)

Takes input as a 2D array.

## How?

* input
* transpose
* 2D array =\> 1D vector of 1D vectors
* `{ ... }¨` apply this to each member (argument ):
    + `⍵[⍒⍵]`  sorted descending
    + `⍵≡` equality with
* `∧/` whether every element is `1`.

# Answer
> 2 votes
# Clojure, 30 bytes

```
(partial every? #(apply >= %))

```

try it online

# Answer
> 1 votes
# MY, ~~66~~ ~~62~~ 20 bytes (noncompeting)

```
ω⍉ω⍉A6ǵ'ƒ⇹(E8ǵ'ƒ⇹(Π←

```

Try it online!

The reason this is non competing is that I recently implemented `8E (≡)`, which is equivalent to APL .

## How?

* `ω⍉` The first command line argument transposed
* `ω⍉` The first command line argument transposed
* `A6ǵ'` push `chr(0x6A)` ( in the codepage, which sorts descending)
* `ƒ` as a function, rather than a string
* push a function that maps a popped function over each argument
* `(` apply
* `E8ǵ'ƒ⇹(` the same thing, except with `chr(0x8E)`, which is the match command ().
* `Π` product
* output with no newline

Yes, a lot of MY's symbols are exactly the same or similar to APL's. The explanation is that they came to mind when I wanted a 1-character command. (I don't know why I didn't use **T** for transpose)

# Answer
> 1 votes
# Java 8, 69 bytes

```
b->{for(int[]c:b)for(int i=0,f=1;i<3;)if(c[i]<c[++i])f=0;return f>0;}

```

Well, as of this writing this beats the Swift solution, so there's that! Utterly straightforward. Input is an array of integer arrays, the inner arrays being columns of the board (upper squares first). Cast to `Function<int[][], Boolean>`.

# Answer
> 0 votes
# Mathematica, 27 bytes

`t=Thread;-t[Sort/@-t@#]==#&`

## Explanation:

* `Thread` is a weird general transpose-like operation that happens to take the transpose when given a matrix.
* `t=Thread;` lets me use `t` twice instead of `Thread` twice to save bytes.
* `Sort` sorts a list (in increasing order).
* `Sort\@` maps the `Sort` function to each element of a list individually; when applied to a matrix, it sorts the rows.
* `t@#` applies the transpose function to the input `#` of the main function.
* `-` takes the negative of all of the entries so that sorting the rows of the transposed matrix (the columns of the original) sorts them in the desired way.
* The outer `-t[...]` undoes the negative and the transpose, so all we really did was sort the columns largest-to-smallest.
* `==#` tests to see if this new column-sorted matrix is equal to the original input.
* `&` ends the anonymous function with input `#` we defined.

---

You can **try it online** in the Wolfram Cloud sandbox by pasting code like the following and clicking Gear-\>"Evaluate cell" or hitting Shift+Enter or the numpad Enter:

```
t=Thread;-t[Sort/@-t@#]==#&@{{16,128,64,32},{8,32,0,8},{4,16,8,2},{4,0,0,0}}

```

Or for all test cases:

```
t=Thread;-t[Sort/@-t@#]==#&//Map[#,{{{16,0,64,8},{8,0,32,8},{4,0,32,2},{2,0,0,0}},{{16,128,64,32},{8,128,32,8},{4,16,8,2},{4,0,0,0}},{{16,0,64,8},{8,0,32,16},{32,0,128,2},{2,0,0,0}},{{16,128,64,32},{8,32,0,8},{4,16,8,2},{4,0,0,0}}}]&

```

---
Tags: code-golf, decision-problem, matrix, board-game, sliding-puzzle
---


title: Sort the climbing grades

text:
# Question
Title: Sort the climbing grades
My first code golf post, apologies for any mistakes...

# Context

In rock climbing (bouldering specifically), the V/Vermin (USA) climbing grades start at 'VB' (the easiest grade), and then go 'V0', 'V0+', 'V1', 'V2', 'V3', 'V4', 'V5' etc. up to 'V17' (the hardest grade).

# Task

You will take as input a list/array of climbing grades and you have to to return or print a list/array of the grades sorted from easiest to hardest.

If the input is empty, return an empty data structure; otherwise the input will always be a valid.

# Test cases

```
Input | Output
[] |  []
['V1'] |  ['V1']
['V7', 'V12', 'V1'] | ['V1', 'V7', 'V12']
['V13', 'V14', 'VB', 'V0'] |  ['VB', 'V0', 'V13', 'V14']
['V0+', 'V0', 'V16', 'V2', 'VB', 'V6'] | ['VB', 'V0', 'V0+', 'V2', 'V6', 'V16']

```

This is a challenge.

# Answer
> 24 votes
# Python 2, ~~58~~ 54 bytes

```
lambda x:sorted(x,key=lambda y,B10=0:eval(y[1:]+'10'))

```

Try it online!

## How it works

```
y         y[1:]+'10'   eval(y[1:]+'10')
=======================================
VB        B10          0  (a variable we defined)
V0        010          8  (an octal literal)
V0+       0+10         10
V1        110          110
V2        210          210
...       ...          ...
V17       1710         1710

```

# Answer
> 15 votes
## JavaScript (ES6) / Firefox, 53 bytes

```
a=>a.sort((a,b)=>(g=s=>parseInt(s,32)%334+s)(a)>g(b))

```

### Test cases

For Firefox:

```
let f =

a=>a.sort((a,b)=>(g=s=>parseInt(s,32)%334+s)(a)>g(b))

console.log(JSON.stringify(f([])))
console.log(JSON.stringify(f(['V1'])))
console.log(JSON.stringify(f(['V7', 'V12', 'V1'])))
console.log(JSON.stringify(f(['V13', 'V14', 'VB', 'V0'])))
console.log(JSON.stringify(f(['V0+', 'V0', 'V16', 'V2', 'VB', 'V6'])))
```

For Chrome or Edge (+4 bytes):

```
let f =

a=>a.sort((a,b)=>(g=s=>parseInt(s,32)%334+s)(a)>g(b)||-1)

console.log(JSON.stringify(f([])))
console.log(JSON.stringify(f(['V1'])))
console.log(JSON.stringify(f(['V7', 'V12', 'V1'])))
console.log(JSON.stringify(f(['V13', 'V14', 'VB', 'V0'])))
console.log(JSON.stringify(f(['V0+', 'V0', 'V16', 'V2', 'VB', 'V6'])))
```

### How?

We apply 3 successive transformations that lead to lexicographically comparable strings.

```
s     | Base32 -> dec. | MOD 334 | +s
------+----------------+---------+---------
"VB"  |           1003 |       1 | "1VB"
"V0"  |            992 |     324 | "324V0"
"V0+" |            992 |     324 | "324V0+"
"V1"  |            993 |     325 | "325V1"
"V2"  |            994 |     326 | "326V2"
"V3"  |            995 |     327 | "327V3"
"V4"  |            996 |     328 | "328V4"
"V5"  |            997 |     329 | "329V5"
"V6"  |            998 |     330 | "330V6"
"V7"  |            999 |     331 | "331V7"
"V8"  |           1000 |     332 | "332V8"
"V9"  |           1001 |     333 | "333V9"
"V10" |          31776 |      46 | "46V10"
"V11" |          31777 |      47 | "47V11"
"V12" |          31778 |      48 | "48V12"
"V13" |          31779 |      49 | "49V13"
"V14" |          31780 |      50 | "50V14"
"V15" |          31781 |      51 | "51V15"
"V16" |          31782 |      52 | "52V16"
"V17" |          31783 |      53 | "53V17"

```

# Answer
> 12 votes
## Husk, 5 bytes

```
ÖiÖm±

```

Try it online! The results are printed one per line, but internally this is a function that takes and returns a list of strings.

## Explanation

This is surprisingly similar to Martin's Retina answer. First we do `Öm±`, meaning "order by mapping is-digit". This puts `VB`, `V0` and `V0+` in the correct order, since they are compared as `[0,0]`, `[0,1]` and `[0,1,0]`. Next we do `Öi`, meaning "order by integer value". Given a string, `i` returns the first sequence of digits occurring in it as an integer, or 0 if one is not found. The three strings above are all mapped to 0 and the sort is stable, so they will be in the correct order in the output.

# Answer
> 11 votes
## Retina, 14 bytes

```
B
!
O`
!
B
O#`

```

Try it online!

### Explanation

```
B
!

```

Replace `B` with `!` so that the lexicographic order of grades puts `VB` (or then `V!`) in front of all the numeric grades.

```
O`

```

Sort all input lines lexicographically. This doesn't give the right result but it does order `V! < V0 < V0+` correctly.

```
!
B

```

Turn `V!` back into `VB`.

```
O#`

```

Sort the lines numerically. Retina simply looks for the first decimal number in a string to determines its sort key. If there is no number (such as for `VB`), it sets the value to `0`. That means all of `VB`, `V0` and `V0+` have the same sort key. But Retina's sort is stable and we've already put them in the correct relative order.

# Answer
> 6 votes
# , 3 bytes

```
Úún

```

Try it online!

## How does it work?

```
ú   # Sort on...
 n  #   the first decimal number on the line

```

This command is *almost* a valid solution, since every line that *can't* be sorted by numbers (AKA, `VB`) will be placed at the beginning, without the order changed. However, since it's only looking at numbers, it can't distinguish between `V0` and `V0+`. Since Vim uses a stable sort, whichever of these came first will remain first after sorting it. So...

```
Ú   # Sort lexicographically (will place 'V0' before 'V0+')
 ú  # Sort by...
  n #   The first number on the line

```

# Answer
> 5 votes
# C#, ~~121~~ ~~83~~ ~~82~~ 83 bytes

*Saved **39** bytes thanks to TheLethalCoder and LiefdeWen*

```
a=>a.OrderBy(x=>x[1]>65?-1:x=="V0+"?0.5:int.Parse(x.Remove(0,1)))

```

Try it online!

Bytecount includes `using System.Linq`.

---

**How?**

* Gets an array of strings as input.
* If the input is equal to `VB`, set the value to -1, if it's equal to `VB0+`, set the value to 0.
* Order the input based on the number value that comes after the `V`.

Might be a bit of a hack, but it works! :)

# Answer
> 4 votes
# Ruby, ~~52 42~~ 41 bytes

```
->x{[?B,0,"0+",*1..17].map{|a|"V#{a}"}&x}

```

Try it online!

### How it works:

Turn the problem around, produce the full sorted list, then get the intersection with our input.

Thanks Lynn for saving 1 byte.

# Answer
> 2 votes
~~To kick things off here is my Python 3 solution...~~ Apologies, posted this too soon against convention, now re-posting...

# Python 3, ~~69~~ 67 bytes

```
lambda l:sorted(l,key=lambda x:'B00+'.find(x[1:])+1or int(x[1:])+3)

```

Try it online!

# Answer
> 2 votes
# Pyth, 16 bytes

Port of Python answer by OP.

```
o|hx"B00+"tN+3st

```

Test suite.

# Answer
> 2 votes
# 05AB1E, ~~17~~ ~~13~~ 8 bytes

```
Σþï}„VB†

```

Try it online!

# Answer
> 2 votes
# Jelly, 9 bytes

```
Ḋv-.F+LµÞ

```

A monadic link taking a list of lists of characters and returning the sorted list.

**Try it online!** (the footer formats the result nicely)

### How?

```
Ḋv-.F+LµÞ - Link: list of lists of characters
       µÞ - sort by key:
Ḋ         -   dequeue (remove the 'V' from the item)
  -.      -   literal -0.5
 v        -   evaluate as Jelly code with argument -0.5
          -   ...this means `VB` and `V0+` become -0.5
          -      (to binary and addition respectively)
          -      while others become their literal numbers
    F     -   flatten
     +L   -   add the length of the item
          -   ...'VB', 'V0', 'V0+', 'V1', 'V2'... -> 1.5, 2, 2.5, 3, 4, ...

```

# Answer
> 2 votes
# Haskell, 55 bytes

```
f l=['V':x|x<-"B":"0":"0+":map show[1..17],_:y<-l,x==y]

```

Try it online!

# Answer
> 1 votes
# Swift 3, 102 bytes

```
var r={String((Int($0,radix:32) ?? 992)%334)+$0};func f(l:[String]){print(l.sorted(by:{r($0)<r($1)}))}

```

This is a function. You can call it as such:

```
f(l:["V0","VB","V13","V0+"])

```

**Try it online!**

---

# How does this work?

This is basically a port of the amazing Javascript answer by @Arnauld, but optimized for Swift.

It maps each of the values to lexicographically orderable Strings as shown in the table below:

```
Initial String -> Result

V1  ->  325V1
V10 ->  46V10
V11 ->  47V11
V12 ->  48V12
V13 ->  49V13
V14 ->  50V14
V15 ->  51V15
V16 ->  52V16
V17 ->  53V17
V2  ->  326V2
V3  ->  327V3
V4  ->  328V4
V5  ->  329V5
V6  ->  330V6
V7  ->  331V7
V8  ->  332V8
V9  ->  333V9
V0+ ->  324V0+
V0  ->  324V0
VB  ->  1VB

```

---

# Code Explanation

* `String((Int($0,radix:32) ?? 992)%334)` \- Converts each String from a base-32 Number to Decimal. In case the value is "V0+", the call to `Int(_:radix:)` will return nil, and we take the value of "V0", 992. We additionally take the result of `mod 334`, and finally convert it to String.
* `+$0` \- Adds the current value to the String created above. For instance, if the String is `V9`, the function above returns `333` and we add `V9`, resulting in `333V9`.
* `var r={...}` \- Declares a variable `r` to an anonymous closure, because it saves lots of bytes since it's used twice.
* `func f(l:[String])` \- Defines a function `f` with a parameter `l`, a list of Strings.
* `print(l.sorted(by:{r($0)<r($1)}))` \- Prints the result of sorting the given list, with the key being the variable `r` defined above.

# Answer
> 1 votes
# PowerShell, 45 bytes

```
param($a)'B',0,'0+'+1..17|%{"V$_"}|?{$_-in$a}

```

Try it online!

Uses the same process as G B's Ruby answer to construct the full argument list in sorted order, then select out those that are `-in` the input list.

# Answer
> 1 votes
# Google Sheets, 142 bytes

```
=ArrayFormula(If(A1="","",Sort(Transpose(Split(A1,",")),Transpose(IfError(Find(Split(A1,","),"VBV0V0+"),Value(Mid(Split(A1,","),2,3))+9)),1)))

```

Input is a string in `A1` with each entry separated by a comma.
Output is the formula's cell plus the `n-1` cells below it where `n` is the number of entries in `A1`.

It's a long, messy formula so let's unpack it.

* `If(A1="","",~)` fixes the null input. Without this, an empty input returns a `#VALUE!` error because the `Split` function doesn't work on empty inputs.
* `Transpose(Split(A1,","))` splits `A1` at the commas and transposes it into a column because the `Sort` function only works on columns.
* `Transpose(IfError(Find(),Value()+9))` is breaks into these pieces:
    + `Find(Split(A1,","),"VBV0V0+")` tries to find each parameter in that string. These first three are the only ones that must be sorted as strings so we use `Find` to get their sort order.
    + `Value(Mid(Split(A1,","),2,3))+9` gets the numerical value of the grade. This only matters for V1 and higher so they sort numerically just fine. The `+9` at the end is to ensure V1 comes after V0+ since its `Find` value would be `5`. Technically, then, only `+5` is required but it costs me no more bytes to make extra double sure it sorts correctly.
    + `IfError(Find(~),Value(~))` returns the `Find` value if the string was found (i.e., the grade is VB, V0, or V0+). If it can't be found, it returns the numerical value of the grade plus nine.
    + `Transpose(IfError(~))` again turns it into a column so `Sort` can use it.
* `Sort(Transpose(Split(~)),Transpose(IfError(Find(~),Value(~)+9)),1)` wraps it all up by sorting the split input using the custom sort order ascending.
* `ArrayFormula(~)` wraps the entire thing so it returns the results as an array instead of just returning the first value in that array. This is what causes the formula in one cell to fill the cells below it, too.

# Answer
> 1 votes
# Bash + coreutils, 21

```
tr B .|sort -V|tr . B

```

GNU `sort`'s `-V`ersion sorting mode almost does what we want. Switch the `B` for a `.` and we're done.

Try it online.

# Answer
> 1 votes
# Haskell, ~~90~~ ~~84~~ ~~83~~ 61 bytes

```
import Data.List
f"VB"=[]
f(_:'1':[a])='X':[a]
f x=x
sortOn f

```

Try it online!

`f` is a function that converts climbing grades to strings that can be compared. If converts `VB` to be the empty string so it gets the highest priority, it then replaces `V1` with `X` in strings that are three long to lower the priority of `V10`-`V17`. For the remainder we do nothing.

To sort the list we use `Data.Lists`'s `sortOn` function (as suggested by Lynn) to create a point-free function.

# Answer
> 1 votes
# , 45 bytes

```
l=paste0('V',c('B','0','0+',1:17));l[l%in%x]

```

### How does this work?

* Assign the correctly ordered vector of grades to 'l';
    + Use 'paste0' instead of 'paste' to avoiding making a 'sep=""' argument;
* Index 'l' based on matches of 'l' in your input vector of mixed, unsorted grades.

# Answer
> 0 votes
# Jelly, ~~17~~ 11 bytes

```
fØD
ṢÇÞÇV$Þ

```

Try it online!

# Answer
> 0 votes
**Python2, 77 bytes**

```
sorted(input(),key=lambda s:float(s[1:].replace("B","-1").replace("+",".5")))

```

# Answer
> 0 votes
# TXR Lisp: 45 bytes

```
(op sort @1 :(ret`@(mod(toint @1 32)334)@1`))

```

Run:

```
1> (op sort @1 :(ret`@(mod(toint @1 32)334)@1`))
#<interpreted fun: lambda (#:arg-01-0168 . #:rest-0167)>
2> [*1 ()]
nil
3> [*1 (list "V0+" "V0" "V16" "V2" "VB" "V6")]
("VB" "V0" "V0+" "V2" "V6" "V16")

```

# Answer
> 0 votes
# Perl 5, 56 + 1 (-a) = 57 bytes

```
map{$i=$_;s/V//;$a[/B/?0:/^0/?length:$_+2]=$i}@F;say"@a"

```

Try it online!

---
Tags: code-golf, array, sorting
---


title: Bigger, Better (Broken) Zipper

text:
# Question
Title: Bigger, Better (Broken) Zipper
*(Inspired quite heavily by this challenge)*

In the original challenge you were to make a horizontal zipper, however, looking down at my hoodie, my zipper is much more vertical (and a little bit broken) :P

**Input**

You will be given a single string (`s`), and a pair of integers (`a` and `b`) in any format. Where:

`a < (length-of-s / 2)`

`b <= ((length-of-s / 2) - (a + 1)) / 6`

**Output and Scoring**

Your program may be a full program or a function that produces a single string with the correct formatting or an array (one item per line) you choose. Leading and trailing spaces and newlines are optional as long as the characters of the output all line up. eg.

```
["f     r"],["u     e"],["l     p"],["l     p"],["y     i"],[" o   z "],["  p n  "],["   e   "]

```

or

```
"f     r\nu     e\nl     p\nl     p\ny     i\n o   z \n  p n  \n   e   "

```

are acceptable outputs for test case 1

Standard Loopholes are forbidden and the shortest code in bytes wins. Any answer with no explanation will not be able to win.

**Explanation**

To make a zipper you must first remove any whitespace or newline characters from the string. And then fold it in half like so (see test case 1 for more)

`abcde fgh ij klmnopqr` becomes the two strings below, notice the second half is reversed.

`abcdefghi` and `rqponmlkj`

Then starting at the beginnning of each string we place the same indexed character from each substring onto one line with the spacing determined as follows:

```
[0] a     r -- (a-3) five spaces
[1]  b   q  -- (a-2) three spaces
[2]   c p   -- (a-1) one space
[3]    d    -- (a)
[4]    o
[5]    e
[6]    n
etc...

```

That makes the base for our zipper. Now the integers `a` and `b`.

`a` is the location of our zip. To determine where the zipper is located we use the index of our output lines as the point to close our zip. eg the square bracketed `[3]` in my above example is where the zip is.

Before our zipper reaches a close, the above zipper must remain at a five space gap until it reaches `a-2` where it closes to 3 spaces and `a-1` where it closes to 1 space. Just to be clear, in the above example `a = 3` (0-indexed)

---

`b` is the number of holes in my zipper. To create a hole in the zip, we split the string out again with some spacing.

Starting with the index of the example hole as `h` we increase the spacing of `h-1` to one space, `h` to 3 spaces and `h+1` back to one space, leaving `h-2` and `h+2` with just one character per line as they are counted as part of the hole.

After the zip and between each of the holes there must be a gap of one character so our zip looks fully connected between holes.

You get to choose the indexes of the holes, but they must all be present within the 'closed' section of the zipper.

```
Again using 'abcdefghi' and 'rqponmlkj'

[0] a     r -- (open)
[1]  b   q  -- (closing)
[2]   c p   -- (closing)
[3]    d    -- zip
[4]    o    -- gap
[5]    e    -- start of hole  (h-2)
[6]   n f   -- one space      (h-1)
[7]  m   g  -- three spaces   (hole h)
[8]   l h   -- one space      (h+1)
[9]    k    -- end of hole    (h+2)
[10]   i    -- gap
[11]   j

```

I'm hoping that all makes sense, if not ask away. In anticipation of questions, you may notice that the character `p` in my second example is present in the second substring, however, appears at the beginning of its line, this is intended, you must follow the sequence of 1-2-1-2-1-2, taking a character from each half in-turn regardless of its position in the output.

**Test Cases**

```
"fully open zipper", 7, 0                     | "fully closed zipper", 0, 0
fullyope reppizn                              | fullyclos reppizde
                                              |
f     r   *Note: i particularly like this     | f
u     e     example as it shows the reversing | r
l     p     of the second half of the string  | u
l     p     causes the words to wrap from top | e
y     i     left to the  bottom and back up   | l
 o   z      the right side                    | p
  p n                                         | l
   e                                          | p
                                              | y
                                              | i
                                              | c
                                              | z
                                              | l
                                              | d
                                              | o
                                              | e
                                              | s

```
* Column 1: "stupidly long unbroken zipper that shouldnt exist on any decent hoodie", 24, 0
* Column 2: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris faucibus molestie mi. Aliquam nec fringilla ipsum", 15, 5

:

```
s     e          |          L     m
t     i          |          o     u
u     d          |          r     s
p     o          |          e     p
i     o          |          m     i
d     h          |          i     a
l     t          |          p     l
y     n          |          s     l
l     e          |          u     i
o     c          |          m     g
n     e          |          d     n
g     d          |          o     i
u     y          |          l     r
n     n          |           o   f
b     a          |            r c
r     n          |             s
o     o          |             e
k     t          |             i
e     s          |            n t
n     i          |           m   a
z     x          |            a m
i     e          |             u
 p   t           |             e
  p n            |             q
   e             |             t
   d             |             i
   r             |             ,
   l             |            l c
   t             |           A   o
   u             |            . n
   h             |             i
   o             |             s
   a             |             m
   h             |            e e
   t             |           c   i
   s             |            t t
                 |             e
                 |             s
                 |             t
                 |             s
                 |             u
                 |             l
                 |             r
                 |             o
                 |             a
                 |             m
                 |             d
                 |             s
                 |             i
                 |             u
                 |             p
                 |            b i
                 |           i   s
                 |            c c
                 |             u
                 |             i
                 |             a
                 |             n
                 |             f
                 |             g
                 |             s
                 |             e
                 |             i
                 |            l r
                 |           i   u
                 |            t a
                 |             .
                 |             M

```

**EDIT: Added Test Cases**

```
"abcde fgh ij klmnopqr","3","1"

a     r
 b   q
  c p
   d
   o
   e
  n f
 m   g
  l h
   k
   i
   j

```

# Answer
# PHP 7.1, ~~421 412 218 195 192 191~~ 195 bytes

```
for([,$s,$a,$b]=$argv;$i-$k<strlen($s=strtr($s,[" "=>""]));$p=0)for($t=++$y>$a-2?$y>=$a?$y>$a?$b-->0?_4_4_4_31_23_31:_4:_31:_23:_15;$c=$t[$p++];)echo$c<_?str_pad("",$c).$s[++$f&1?$i++:$k-=1]:"
";

```

Run with `-nr` or try it online.
Prints a leading, but no trailing newline and one leading space in each line.
> 1 votes

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


title: All your base 97 are belong to us

text:
# Question
Title: All your base 97 are belong to us
Many programming languages are written using solely printable ASCII, tabs and newlines. These 97 characters are then stored in 8-bit bytes (which are actually capable of holding 256 different characters!), which is just terribly inefficient - especially in code-golfing, where every byte counts! In this challenge, you will be able to reduce your score by using base conversion.

## Challenge

Your program/function takes a string or character array as input, which it then interprets as a **base-97** number. It then converts this to a **base-256** number, and counts the number of symbols (i.e., bytes) necessary to represent this number. This count will be the output/return value of your program/function.

*A simple example using base-2 and base-10 (binary and decimal): if the input is `10110`, the output would be 2, since 101102=2210 (two digits necessary to represent output). Similarly, 11012 becomes 1310, giving an output of 2 as well, and 1102 becomes 610, so then the output would be 1.*

The input string can contain all 95 printable ASCII characters , as well as newline `\n` and literal tab `\t`, which creates a **source alphabet** of 97 symbols for your base conversion. The exact alphabet will thus be *(substituting the `\t` and `\n` with actual literal tab and newline; note the literal space following the newline)*:

```
\t\n !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

```

Note that the order of this alphabet is important: for example, base-97 `\t` corresponds to decimal `0`, and `!` corresponds to decimal `3`.

Some testcases: (you do not need to handle an empty string)

```
Input                             Output
'example@domain.com'                  15
'All your base are belong to us!'     26
'       abcd'                          9
'~      abcd'                         10
'ABCDEFGHIJK'                          9
'zyxwvutsrpq'                         10
'{".~"}.~'                             7
'\t\t\t\t\t\t\t\t'                     1 (with \t a literal tab; the result is 0, which can be represented with 1 byte)
'!\t\t\t\t\t\t\t\t'                    7 (with \t a literal tab)

```

# Scoring

1. **If your entry uses only printable ASCII, newline and/or tab:** The score of your program will be the output of your program, when given its own source code as input.
2. **If your entry uses any characters that are not printable ASCII, newline or tab:** The score of your program is simply the number of bytes, like in .

# Answer
# Python 2, score 73  72 71

**Edit:** -1 thanks to @Jonathan Allan

```
def f(l,z=0):
	for i in map(ord,l):z+=i-[30,9][i<32];z*=97
	print(len(bin(z))-2)/8or 1

```

Try it online!
> 7 votes

# Answer
# Jelly,  ~~18~~  17 bytes \- score  ~~18~~  17

-1 byte thanks to Erik the Outgolfer (no need for a list of lists for the translation)

```
O“µœ½þ‘y_30ḅ97b⁹L

```

**Try it online!**

### How?

```
O“µœ½þ‘y_30ḅ97b⁹L - Link: list of characters
O                 - convert from characters to ordinals
 “µœ½þ‘           - code-page indices = [9,30,10,31]
       y          - translate (9->30 and 10->31)
        _30       - subtract 30
           ḅ97    - convert from base 97
               ⁹  - literal 256
              b   - convert to base
                L - length of the result

```

---

--The best I've got with ASCII only is a score of **29**:

```
O10,31,9,30y_30Ux"J_1 97*$$$SSb256L

```

\- this is **extremely** inefficient too. It translates the ordinals like above, but the conversion from base 97 is achieved by repeating the values and summing, rather than using direct multiplication - that is to convert `{".~"}.~` it gets the adjusted indexes `[93,4,16,96,4,95,16,96]` then reverses (`U`) and repeats them to make `[[96,96,..., 97⁷ times ...,96],[16,16,... 97⁶ times ...16],[95,95,... 97⁵ times ...95],[4,4,... 97⁴ times ...4],[96,96,... 97³ times ...96],,[16,16,... 97² times ...,16],[4,4,... 97 times ...4],[93]]` and then sums, converts to base 256 and gets the length (if it has not run out of memory :p).
> 5 votes

# Answer
# Japt, score 19 (23 bytes)

```
nHo127 uA9 md)sG l /2 c

```

Test it online!

By coincidence, I don't think this can be golfed much even with non-ASCII chars...

### Explanation

```
UnHo127 uA9 md)sG l /2 c   Implicit: U = input string, A = 10, G = 16, H = 32
  Ho127                    Create the range [32, 33, ..., 126].
        uA9                Insert 9 and 10 at the beginning of this range.
            md             Map each to a character, yielding ["\t", "\n", " ", "!", ... "~"].
Un            )            Convert U to a number via this alphabet ("\t" -> 0, "~" -> 96, etc.)
               sG          Convert this number to a base-16 (hexadecimal) string.
                  l        Take the length of this string.
                    /2 c   Divide by two and round up to get the length in base-256.
                           Implicit: output result of last expression

```
> 5 votes

# Answer
# , 36 bytes, score = 30

```
256#@(#.inv)97x#.(u:9,10,32+i.95)&i.

```

Try it online!

J uses only the 7-bit ASCII characters for its primitives.

## Explanation

```
256#@(#.inv)97x#.(u:9,10,32+i.95)&i.  Input: string S
                 (              )     Form 7-bit ASCII alphabet
                            i.95        Range [0, 95)
                         32+            Add 32
                    9,10,               Prepend 9 and 10
                  u:                    Convert to characters
                                 &i.  Index of each char in S in that alphabet
            97x#.                     Convert from base 97 to decimal
256   #.inv                           Convert to base 256
   #@                                 Length

```
> 3 votes

# Answer
# Gaia, 14 bytes, score 14

```
9c₸c₵R]$;B₵rBl

```

Try it online!

### Explanation

```
9c              Push a tab character. (done like this since tab isn't in the codepage)
  ₸c            Push a linefeed character.
    ₵R          Push all printable ASCII characters.
      ]$        Concatenate everything together.
        ;       Copy second-from-top, implicitly push input. Stack is now [ASCII input ASCII]
         B      Convert input from the base where the ASCII string is the digits.
          ₵rB   Convert that to the base where the code page is the digits (base 256).
             l  Get the length of the result.
                Implicitly output top of stack.

```

## ASCII only

This is the best I could come up with using only ASCII, giving a score of 19:

```
9c10c8373c'R+e]$;B256Bl

```

The difficulty is in the conversion of input. The only reasonable way to convert from the base-97 system is to use `B`, since mapping requires the non-ASCII `¦`. Additionally, there isn't currently a way to make a character range without mapping `c` over a number range, which suffers the same problem. The best solution I could see was constructing the string `₵R` and evaling it.
> 3 votes

# Answer
# Python 2, score 60

```
lambda s:len(bin(reduce(lambda a,c:a*97+ord(c)-[30,9][c<' '],s,0)))+5>>3

```

Try it online!

## Mapping to base-97

The value of a character is obtained by `ord(c)-[30,9][c<' ']`: its ASCII code, minus 9 for tabs and newlines (which precede `' '` lexicographically), or minus 30 for everything else.

## Converting to a number

We use `reduce` to convert the string to a number. This is equivalent to computing

```
a = 0
for c in s: a = a*97+ord(c)-[30,9][c<' ']
return a

```

## Computing base-256 length

The return value of `bin` is a string, which looks somewhat like this:

```
"0b10101100111100001101"

```

Call its length `L`. A value with an `n`-bit binary representation has a `ceil(n/8)`-bit base-256 representation. We can compute `n` as `L-2`; also, `ceil(n/8)` can be written as `floor((n+7)/8)` = `n+7>>3`, so our answer is `L-2+7>>3` = `L+5>>3`.

The case where the input string has value 0 is handled correctly, as `bin` returns `"0b0"`, so we return `3+5>>3` = 1.
> 3 votes

# Answer
# APL, score 24 (bytes\*)

```
⌈256⍟97⊥97|118|¯31+⎕AV⍳⍞

```

Assumes the default `⎕IO←1`, otherwise just change ¯31 to ¯30.

**Explanation:**

```
                   ⎕AV⍳⍞  Read a string and convert it to ASCII codepoints + 1
               ¯31+       Subtract 31, so that space = 2, bang = 3, etc.
           118|           Modulo 118, so that tab = 97, newline = 98
        97|               Modulo 97, so that tab = 0, newline = 1
     97⊥                  Decode number from base 97
⌈256⍟                     Ceiling of log base 256, to count number of digits

```

**Examples:**

```
      ⌈256⍟97⊥97|118|¯31+⎕AV⍳⍞
example@domain.com
15
      ⌈256⍟97⊥97|118|¯31+⎕AV⍳⍞
All your base are belong to us!
26
      ⌈256⍟97⊥97|118|¯31+⎕AV⍳⍞
       abcd
9
      ⌈256⍟97⊥97|118|¯31+⎕AV⍳⍞
~      abcd
10

```

\________________
\*: APL can be written in its own legacy charset (defined by `⎕AV`) instead of Unicode; therefore an APL program that only uses ASCII characters and APL symbols can be scored as 1 char = 1 byte.
> 2 votes

# Answer
# Jelly, score: 18 (bytes)

```
9,⁷Ọ;ØṖiÐ€⁸’ḅ97b⁹L

```

Try it online!
> 1 votes

# Answer
# Perl 5, 76 + 1 (-F) = 77 bytes

```
}{$d+=97**(@F+--$i)*((ord)-(/	|
/?9:30))for@F;say!$d||1+int((log$d)/log 256)

```

Try it online!

**How?**

Implicitly, separate the characters of the input (`-F`), storing all of that in @F. Close the implicit `while` loop and start a new block (`}{`) (*Thanks, @Dom Hastings!*). For each character, multiply its value by 97 to the appropriate power. Calculate the number of characters by finding the size of the sum in base 256 using logarithms.
> 1 votes

# Answer
# MATL (19 bytes), score 16

```
9=?1}G9tQ6Y2hh8WZan

```

Non-printable characters (tab, newline) in the input string are entered by contatenating their ASCII codes (`9`, `10`) with the rest of the string.

The initial part `9=?1}G` is only necessary because of a bug in the `Za` (base conversion) function, which causes it to fail when the input only consists of "zeros" (tabs here). It will be fixed in the next release of the language.

### Explanation

```
9=      % Implicitly input a string. Compare each entry with 9 (tab)
?       % If all entries were 9
  1     %   Push 1. this will be the ouput
}       % Else
  G     %   Push input string again
  9     %   Push 9 (tab)
  tQ    %   Duplicate, add 1: pushes 10 (newline)
  6Y2   %   Push string of all printable ASCII chars
  hh    %   Concatenate twice. This gives the input alphabet of 97 chars
  8W    %   Push 2 raised to 8, that is, 256. This represents the output
        %   alphabet, interpreted as a range, for base conversion
  Za    %   Base conversion. Gives a vector of byte numbers
  n     %   Length of that vector
        % End (implicit). Display (implicit)

```
> 1 votes

# Answer
# Ruby, 70 bytes, score 58

```
->n{x=0;n.bytes{|i|x+=i-(i<32?9:30);x*=97};a=x.to_s(2).size/8;a<1?1:a}

```

Try it online!
> 1 votes

# Answer
# Befunge-93, ~~83~~ 79 bytes, score ~~74~~ 65

```
<v_v#-*52:_v#-9:_v#`0:~
 5v$
^6>>1>\"a"* +
 >*- ^   0$<
0_v#:/*4*88\+1\ $<
.@>$

```

Try it here!

The program first converts the input to a base-97 number, and then counts how many digits are required for a base-256 number. As such, the base-97 number is huge, so big that TIO will output a maximum value of 8 for large values; however, the JS interpreter doesn't care and will output the correct value.
> 1 votes

---
Tags: code-challenge, base-conversion, compression
---


title: Bubble the brackets!

text:
# Question
Title: Bubble the brackets!
There are a few questions on this site about balancing brackets, and checking whether brackets are balanced. I propose it's now time to use those balanced brackets for something!

In mathematics and programming, brackets are like bubbles, isolating everything inside form everything outside so that whatever's inside can do its thing in peace and whatever's outside only sees one object. However, a string of brackets is one-dimensional, while bubbles usually are at least two dimensional. That means that bubbles are free to move around one another as long as they never touch each other or cross between the inside and the outside of any other bubbles.

# Challenge

The input is a string of matched brackets of a single type, either round `()`, square `[]`, curly `{}` or angle `<>`. It's up to you what kind you want your program to accept, and a program that only accepts a single kind of brackets is accepted. (Imaginary bonus if your program can handle any of them, massive imaginary bonus points if it can handle all of them in the same input.) The input cannot contain anything between the brackets, although trailing whitespaces are allowed.

The output is all possible reorganisations (in arbitrary order, and including the original input) of those brackets that yields the same configuration of bubbles, with no two identical strings. That means that with an input of `()()`, the output is also just `()()`, even though it's technically two bubbles that could swap places. For the massive imaginary bonus, an input of `{}[]()` will of course lead to an output of 6 different elements / strings / lines.

Two configurations of bubbles are "the same" if you can make one into the other by moving bubbles around, without letting any bubble cross from inside another bubble to outside it, or from outside to inside. If you liken nested parentheses to trees (each matched pair is one node, and every matched pair within is a subnode, and each matched pair within there is a subnode of those again, and so on) where the subnodes of any given node are ordered, then a single configuration of bubbles is a tree where the nodes are unordered.

Any reasonable output format will do, like returning a list of strings or a list of list of single characters or a single string with some kind of whitespace, or printing to `stdout`or `stderr` with some form of visible whitespace character (most commonly newline or space) between each reorganisation.

Trailing spaces for each reorganisation and trailing and preceeding newlines / empty list elements before and after the actual output is allowed. You should use the same kind of brackets in your output as you accept in your input. Apart from the brackets, newlines and spaces as specified here, and whatever separator you use, nothing should be printed (including invisible / zero-width characters).

The score is the number of bytes in the code; lowest count for each language wins. You may note whether you get an imaginary bonus, either regular or massive, but it doesn't affect your score. Actual bonuses are too hard to balance right.

# Input-output examples

### Example 1:

Input:

```
()(())

```

Output:

```
()(())
(())()

```

### Example 2:

Input:

```
(()())()()

```

Output:

```
(()())()()
()(()())()
()()(()())

```

### Example 3:

Input:

```
(()(()))()

```

Output:

```
((())())()
()((())())
(()(()))()
()(()(()))

```

# Answer
# CJam, 18 bytes

```
{~{_{{B}%e!}&}:B~}

```

Try it online!

-2 thanks to Business Cat.

Receives input as a string containing only `[]`. Returns a list of permutations (empty lists are the same as empty strings in CJam, so instead of `[]` you'll be getting `""`).
> 4 votes

# Answer
# Haskell, ~~227~~ ~~210~~ ~~208~~ 205 bytes

```
import Data.List
l=last
a!x=init a++[l a++[x]]
h[]=[""]
h(x:y)=["("++z++")"++t|z<-v x,t<-h y]
g(a,r)x|x=='('=(a+1,l$(r++h[]):[r!x|a>0])|1>0=(a-1,l$r:[r!x|a>1])
v s=nub$h=<<(permutations.snd$foldl g(0,[])s)

```

Try it online!

This one was tough!

*Golfed a little bit*

*Saved two bytes thanks to Laikoni*

*Save two bytes thanks to Bruce Forte*

I'm not sure this works in every case. Some explanations:

* `a!x` add the String `x` to the last list of String in `a` (a is of type `[[String]]`)
* `snd$foldl(\(a,r)x->if x=='('then(a+1,last$(r++[[]]):[r!x|a>0])else(a-1,last$r:[r!x|a>1])` uses the shorter conditional to express the simple idea: split a String on *root* `)(`s. E.g. `"(()(()))()"` gives `["()(())", ""]`.
* We need to process each part of the split, then to gather and join all the strings to get the correct output:

1. `h` processs a list of parts: it applies `v` to the first part and combines the result to the process of the remaining parts.
    2. `v` aggregates the results for each permutation of the parts, and remove the duplicates.

*To add a broader view: you have basically a tree (not a binary one) with empty nodes. Leave are `()`. You have to produce all the permutations of the branches for each node, but you may not take a branch from a node and put it on another node. I did a kind of depth first search.*
> 4 votes

# Answer
## JavaScript (Firefox 30-57), 222 bytes

```
s=>(g=a=>a+a?[for(x of g(a[0]))for(y of a.keys())for(z of g(a.slice(1)))(z.splice(y,0,x),z)]:[a])(eval(`[${s.replace(/]\[/g,`],[`)}]`)).map(g=a=>`[`+a.map(g).join``+`]`).sort().filter(s=>t<(t=s),t=``).map(s=>s.slice(1,-1))

```

Takes `[]` strings. Explanation:

```
s=>(                                Inner function to permute an array
 g=a=>a+a?[                         If array is not empty
  for(x of g(a[0]))                 Permute the first element of the array
  for(y of a.keys())                Generate a list of insertion points
  for(z of g(a.slice(1)))           Permute the rest of the array
  (z.splice(y,0,x),z)]:             Make all possible permutations
  [a]                               Otherwise return a list of an empty array
)(eval(`[${                         Convert the string to a nested array
   s.replace(/]\[/g,`],[`)}]`)      ... inserting commas where necessary
).map(                              Process the results
 g=a=>`[`+a.map(g).join``+`]`       Recursively convert back to string
).sort().filter(s=>t<(t=s),t=``     Check for duplicates
).map(s=>s.slice(1,-1))             Remove outer `[]`s

```
> 2 votes

# Answer
# Python 2, ~~353~~ ~~350~~ 331 Bytes

```
s=input()
f=lambda i,t=0:i+1if t<0else f(i+1,t-1)if"("<s[i+1]else f(i+1,t+1)
c=[(x,f(x))for x in range(len(s))if")">s[x]]
p=lambda l:[[]]if len(l)<1else[x for y in p(l[1:])for x in[y[:i]+[l[0]]+y[i:]for i in range(len(y)+1)]]
print[''.join(x)for x in p([s[c[x][0]:c[x][1]]for x in range(len(c))if all(c[x][1]>y[1]for y in c[:x])])]

```

Receives string of `()` as input and prints the result.

Try it here!

I avoided using `itertools.permutations` with help from Paolo's answer to this question.

Thank you to Business Cat for finding 3 bytes, and thank you to Mr. Xcoder for an incredible 19 bytes!

### Explanation

1. Create a list of tuples of the indices of each `()` pair in the input string.
2. Drop any tuples from the list that are surrounded by another `()` pair.
3. Slice the string at the indices of the remaining tuples.
4. Make a list of each permutation of the list of slices.
5. Join the list with a new line for printing.
> 2 votes

# Answer
# Mathematica, 337 bytes

Not to get code-golf points, but to show the usage of `Permutations` and `Distribute` in this problem. There may be better approaches, though.

(`seq` : sequence, `alt` : alternatives)

```
SetAttributes[alt, {Flat, OneIdentity}]
StringTake[
  StringReplace[ToString[
    ToExpression["{" <> StringReplace[#, "}{" -> "},{"] <> "}"]
        /. List -> Permutations@*seq
       /. List -> alt
      /. seq -> (Distribute[seq@##, alt] &)
     /. {seq -> List, alt -> Alternatives}],
   {", " -> "", "} | {" -> "\n"}],
  {2, -2}] &

```

Take input as a string, using curly brackets `{` and `}`. Output a multi-line string.
> 0 votes

---
Tags: code-golf, permutations, balanced-string
---


title: Score my golf round!

text:
# Question
Title: Score my golf round!
Since this SE community is about golfing, I thought a golf-related challenge would be appropriate.

## Explanation

Normally, the objective of golf is to finish a hole (and consequently, the entire round) with the least amount of strokes. This is a simple version of golf: Play until you hole the ball and sum up your score. Finally subtract it from the total par and the resulting number indicates your score: 0 if you played exactly par, positive if you played worse and negative if you played better.

But in 1898 a guy named Dr. Frank Barney Gorton Stableford devised a new system of playing which was designed to be more forgiving. This system awards a number of points to a player, based on a relative rating per hole, called the stroke index (SI) which is based on a player rating called handicap. This limits the amount of points a player can lose per hole. Additionally, the handiccp ensures fair competition between players despite skill difference.

This format isn't used in professional golf, but can be found almost anywhere in amateur golf.

## The scoring algorithm

For anyone unfamiliar with golf, the algorithm for scoring a hole based version is as follows.

1. Beginning with the hardest hole (rating 1) to the easiest one (rating 18), increase the stroke index of that hole by 1 and decrement the handicap. If you exhaust the handicap, stop. If you hit the easiest hole you wrap around to the hardest and continue. (Ex: stroke index for hcp `24` and `[1..18]`: `[2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1]`).
2. For every score on a hole, subtract it from the sum of par and stroke index and add 2 (formula: `(par + stroke index) - achieved score + 2`). These are the stableford points received for that hole. Note that you cannot receive less than 0 points.
3. Sum up all the points. The resulting total is the total number of stableford points.

Thus, reaching 36 points is equivalent to playing exactly one's handicap, and more points are better.

## Rules

Your task will be to calculate the total number of stableford points of an arbitrary golf round on an arbitrary golf course given a handicap.

You will be given a list of difficulty ratings, a list of pars, a list of scores and the handicap to use. You may order these arguments as you wish, but please state how you order them.

You may write a function ot program, input can be taken either as command line argument or function argument.

Output may either be printed to STDOUT or the return value of a function.

You may assume the following about the input:

* Every list will contain exactly 18 elements.
* The lists are orderd by hole: First element = info for first hole, etc.
* The handicap will be an integer between 0 and 54 inclusive.
* Pars will be between 3 and 7.
* The score is always a positive integer.
* The difficulty rating list will always be a permutation of `[1..18]`.

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

## Examples

```
Input: hcp: 0
       difficulty: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
       pars: [3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5]
       score: [3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5]
Output: 36

Input: hcp: 15
       difficulty: [9,3,1,13,11,17,15,7,5,18,14,10,4,6,12,16,8,2]
       pars: [4,4,4,3,5,4,3,4,4,4,3,4,4,4,5,3,5,4]
       score: [5,5,4,5,4,4,4,4,5,7,3,5,5,6,4,6,5,5]
Output: 38

Input: hcp: 28
       difficulty: [9,3,1,13,11,17,15,7,5,18,14,10,4,6,12,16,8,2]
       pars: [4,4,4,3,5,4,3,4,4,4,3,4,4,4,5,3,5,4]
       score: [5,5,5,6,3,7,3,6,5,8,4,6,7,8,4,7,6,5]
Outut: 37

Input: hcp: 54
       difficulty: [9,3,1,13,11,17,15,7,5,18,14,10,4,6,12,16,8,2]
       pars: [4,4,4,3,5,4,3,4,4,4,3,4,4,4,5,3,5,4]
       score: [9,10,9,10,9,10,9,10,9,10,9,10,9,10,9,10,9,10]
Output: 3

```

Happy golfing!

# Answer
# Pyth, 46 bytes

```
u+G.)S[0+-++@@Q2Hg%hQ18@@Q1H/hQ18@@Q3H2)Ul@Q1Z

```

A program that takes input as a list of the form `[handicap, [difficulties], [pars], [scores]]` and prints the overall score.

I am very new to Pyth, so this can probably be golfed further.

Try it online

**How it works**

```
u+G.)S[0+-++@@Q2Hg%hQ18@@Q1H/hQ18@@Q3H2)Ul@Q1Z  Program. Input: Q

 +G.)S[0+-++@@Q2Hg%hQ18@@Q1H/hQ18@@Q3H2)        Function. Inputs: G, H
            @@Q2H                               Q[2][H]
                   hQ                           Q[0]
                     18                         18
                  %                             Q[0]%18
                       @@Q1H                    Q[1][H]
                 g                              Q[0]%18>=Q[1][H]
           +                                    Q[2][H]+Q[0]%18>=Q[1][H]
                             hQ                 Q[0]
                               18               18
                            /                   Q[0]//18
          +                                     Q[2][H]+Q[0]%18>=Q[1][H]+Q[0]//18
                                 @@Q3H          Q[3][H]
         -                                      Q[2][H]+Q[0]%18>=Q[1][H]+Q[0]//18-Q[3][H]
                                      2         2
        +                                       Q[2][H]+Q[0]%18>=Q[1][H]+Q[0]//18-Q[3][H]+2
       0                                        0
      [                                )        List [0, above expression]
     S                                          Sort ascending
   .)                                           Pop last value, clamping negatives to 0
  G                                             G
 +                                              G + popped value

u                                       Ul@Q1Z
                                          @Q1   Q[1]
                                         l      Length
                                        U       Unary range, yielding [0, len(Q[1])-1]
                                             Z  0
u                                               Reduce the function over that, start at 0

```
> 1 votes

# Answer
## JavaScript (ES6), 72 bytes

```
(h,d,p,s)=>s.map((e,i)=>(e=p[i]+2-e+(h%18>=d[i])+h/18|0)<0?0:r+=e,r=0)|r

```
> 2 votes

# Answer
# Python 3, 71 bytes

```
lambda h,d,p,s:sum(max(0,j+(h%18>=i)+h//18-k+2)for i,j,k in zip(d,p,s))

```

An anonymous function that takes input via argument of a handicap `h` as an integer, and difficulties `d`, pars `p` and scores `s` as lists, and returns the overall score.

**How it works**

```
lambda h,d,p,s           Anonymous funtion with inputs handicap h, difficulties d, pars p
                         and scores s
for i,j,k in zip(d,p,s)  For each (difficulty, par, score) set (i, j, k):
  (h%18>=i)+h//18          Calculate the stroke index...
  j+...-k+2                ..calculate (par + stroke index) - score + 2...
  max(0,...)               ...and clamp negative values to zero
:sum(...)                Return the sum of the above over all holes, which is the overall
                         score

```

Try it on Ideone
> 1 votes

# Answer
# Haskell, 75 bytes

This can definitely be golfed some more

```
(h!d)p s=sum[max 0$j-k+2+h`div`18+1`min`div(h`mod`18)i|(i,j,k)<-zip3 d p s]

```
> 1 votes

# Answer
# Perl 5, 142 bytes

```
($h,@a)=map/\d+/g,<>;%d=map{$j++,$_}@a[0..17];$z+=($t=$a[18+$_]-$a[36+$_]+2+int$h/18+($k++<$h%18))>0?$t:0for sort{$d{$a}<=>$d{$b}}keys%d;say$z

```

Try it online!

There has got to be a shorter way to do this, but my brain can't come up with it right now.
> 1 votes

---
Tags: code-golf
---


title: Generate every ASCII string

text:
# Question
Title: Generate every ASCII string
**Description**

There are an infinite number of ASCII strings. Write a program that will output every possible ASCII string exactly once.

The ordering does not matter, but you must be able to show that for any possible ASCII string `s`, there exists an integer `n` such that `s` is the `n`th string in the output. This restriction means that you cannot output `'a', 'aa', 'aaa', 'aaaa', ...`, since the string `'b'` will never occur.

The simplest ordering (shown here in terms of letters so I don't have to type unprintables) is:

```
'', 'a', 'b', 'c', ..., 'z', 'aa', 'ab', ..., 'az', 'ba', 'bb', 'bc', ... 'zz', 'aaa', ...

```

Essentially, this is counting in base 128 using ASCII characters.

**Rules**

* The empty string is required
* You may use any valid ordering you want
* All possible strings using ASCII must be known to occur in the output
* The ordering does not need to be deterministic, as long as you can show that every string will be *guaranteed* to occur. Be careful if you use randomness for each string, because at some point your bits of entropy may not be enough to guarantee a unique string.

**Example orderings**

*Note that, again, I'm showing only letters for the examples, but you have to include all ASCII characters.*

**Valid:**

```
'', 'a', 'b', 'c', ..., 'z', 'aa', 'ab', ..., 'az', 'ba', 'bb', 'bc', ... 'zz', 'aaa', ...

'', 'z', 'y', 'x', ..., 'a', 'zz', 'zy', ...

'', 'a', 'b', 'ab', 'ba', 'c', 'ac', 'ca', 'bc', 'cb', ...

```

**Invalid:**

```
'', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa', ...

'', 'a', 'ab', 'abc', 'abcd', ..., 'abc...xyza', ...

```

# Answer
# SOGL V0.12, 10 bytes

```
]¶tēN»─{Rt

```

Try it Here!

Note that this spams the stack with an extra item every iteration, and with how slow SOGL is, it gets out of hand quickly.
> 0 votes

# Answer
# Python 2, ~~69~~ 62 bytes

```
a=0
while 1:
 k=a
 while k:print chr(k%128),;k>>=7
 print;a+=1

```

*-7 bytes thanks to @notjagan*

Try it online!
> 3 votes

# Answer
# Proton, 96 bytes

```
i=0
(p=print)()
while++i for j:cartesianpower(i,0..128)p(j is tuple? ''.join(map(chr,j)):chr(j))

```

Try it online!
> 2 votes

# Answer
# Pyth - 12 bytes

```
.Vj^sCMS127b

```

Finite version online.
> 1 votes

# Answer
# Ruby, 64 bytes

```
(f=->a{f[a.flat_map{|s|puts s;(1..127).map{|b|s+b.chr}}]})[['']]

```

Recursive function that prints the array `a` then calls itself on a newly constructed array whose contents are (in set notation) `{ sc | s in a, c in ASCII }`. We kick it off with an array containing the empty string.
> 1 votes

# Answer
# Mathematica, ~~44~~ ~~41~~ 61 bytes

Crossed out 44 is still regular 44...

```
0//.i_:>(Print@@@Array[FromCharacterCode,128,0]~Tuples~i;i+1)

```

Prints in the pattern:  `"", "a", "b", ... , "z", "aa", "ab", ... , "az", "ba", "bb", ... , "zz", "aaa", "aab", ...` (but with \00, \01, ...).

Try it on Wolfram Sandbox

Unfortunately, I could not use the built-in `CharacterRange` function (which would have reduced 10 bytes) because it cannot generate the null character.

---

I recommend testing with the version that pauses 0.25 sec between each `Print` calls:

```
0//.i_:>((Pause[0.25];Print@##)&@@@Array[FromCharacterCode,128,0]~Tuples~i;i+1)

```
> 1 votes

# Answer
# Python 3, 103 78 bytes

```
n=0
while 1:print(n.to_bytes(n.bit_length()+7>>3,"big").decode());n+=n+1&128|1

```

Try it online!
> 0 votes

---
Tags: code-golf, string, sequence
---


title: Combination lock counter

text:
# Question
Title: Combination lock counter
# The scene is:

Peter is at the gym with his buddy Brian when Brian suddenly is in dire need of his inhaler. Brian manages to tell Peter the code to his combination lock before he collapses on the floor.

The moment Peter gets to Brian's locker and sees what the indicator is pointing at, Stewie ambushes him and sprays a full can of pepper spray in his face, thus blinding Peter.

Peter must now try to open the lock without looking at it. He starts turning the dial to the right, counting the numbers while he passes them. He then, at the correct number starts turning the dial to the left, still counting, and finally turns it to the right until the lock opens.

---

# The challenge:

Write a function/program that takes two inputs, the combination from Brian, and the indicator position. Output the numbers Peter has to count.

Rules:

* The combination and the indicator position must be separate arguments.
* The input can be either from command prompt or as function arguments.
* The output must be printed to the screen / otherwise displayed (not to file)
* Assume that the starting position is not the same as the first number, and that all three numbers in the combination are unique
* It's the lock shown in the picture below, with possible numbers: 0-39.

# Instructions:

To open the lock below, you need to follow a set of instructions:

1. You must know your code. Assume it's (38, 16, 22) for now.
2. Turn the dial 3 times to the right (passing the starting number three times), then stop when the first number (38) aligns with the indicator
3. Turn the dial 1 full turn to the left, passing the first number, and stop when the second number (16) lines up with the indicator.
4. Turn the dial to the right and stop when the third number (22) lines up with the indicator
5. Pull the lock down

Example:

```
Input
38 16 22
33

Output
33  32  31  30  29  28  27  26  25  24  23  22  21  20  19  18  17  16  15  14  13  12  11  10   9   8   7   6   5   4   3   2   1   0  39  38  37  36  35  34  33  32  31  30  29  28  27  26  25  24  23  22  21  20  19  18  17  16  15  14  13  12  11  10   9   8   7   6   5   4   3   2   1   0  39  38  37  36  35  34  33  32  31  30  29  28  27  26  25  24  23  22  21  20  19  18  17  16  15  14  13  12  11  10   9   8   7   6   5   4   3   2   1   0  39  38  37  36  35  34  33  32  31  30  29  28  27  26  25  24  23  22  21  20  19  18  17  16  15  14  13  12  11  10   9   8   7   6   5   4   3   2   1   0  39  38  39   0   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   0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  15  14  13  12  11  10   9   8   7   6   5   4   3   2   1   0  39  38  37  36  35  34  33  32  31  30  29  28  27  26  25  24  23  22

```

Standard code golf rules apply.

Solutions that are posted later can still win if they're shorter than Dennis' answer.

# Answer
> 3 votes
# CJam, ~~52~~ 39 bytes

```
q~[3X0].{@40,m<1$({(+W%}&:T*T@#)T<)}e_p

```

Try it online in the CJam interpreter.

### How it works

```
q~      e# Read and evaluate all input. This pushes the initial position
        e# as an integer and the combination as an array.
[3X0]   e# Push [3 1 0]. This encodes the respective numbers of full turns
.{      e# For each number in the combination (N) and the corresponding
        e# number of full turns (F):
  @     e#   Rotate the initial position on top of the stack.
  40,m< e#   Push [0 ... 39] and rotate it that many units to the left.
        e#   For position P, this pushes [P P+1 ... 39 0 ... P-2 P-1].
  1$(   e#   Copy F and subtract 1.
  {     e#   If the result is non-zero:
    (+  e#     Rotate the array of length 40 one unit to the left.
    W%  e#     Reverse it.
  }&    e#   For position P, this pushes [P P-1 ... 0 39 ... P+2 P+1].
  :T*   e#   Save in T and repeat the array F.
  T@    e#   Push T. Rotate N on top of the stack.
  #)    e#   Find the index of N in T and add 1 to it.
  T<    e#   Keep that many elements from the beginning of T.
  )     e#   Pop the last element of the result (N).
}       e# N is the new initial position.
e_p     e# Flatten the resulting array and print it.

```

# Answer
> 1 votes
# Groovy, ~~189~~ 175 bytes

Assumes the indicator is passed as arg0 and the combo is passed as arg1, arg2, and arg3 on the command line...

```
i=(args[0]as int)+1
r={i--;i=i<0?39:i;print"$i "}
l={i=++i%40;print"$i "}
M={j,c->while(i!=j as int){c()}}
120.times{r()}
M(args[1],r)
40.times{l()}
M(args[2],l)
M(args[3],r)

```

# Answer
> 1 votes
# Perl 5, 129 + 1 (-a) = 130 bytes

```
sub c{$f=pop;do{say$f;$f+=$_[0];$f=$f==-1?39:$f==40?0:$f}while$f-$_[1]}$p=3;c(2*!$p-1,@F[$_,$p]),$p=$_ for 3,3,3,0,0,1,2;say$F[2]

```

Try it online!

**How?**

```
sub c{                       # Takes 3 parameters: increment, ending position, starting position
  $f=pop;                    # first place to start counting
  do{
    say$f;                   # output current position
    $f+=$_[0];               # move position
    $f=$f==-1?39:$f==40?0:$f # roll over when passing zero
  }while$f-$_[1]             # stop when ending positition reached
}

# @F gets defined by the -a command line option
# @F holds the combination followed by the starting position

$p=3;                       # starting position is in array index 3, this variable will track the array index of
                            # the current position on the dial

c(2*!$p-1,@F[$_,$p]),$p=$_  # call the movement function (c), setting direction to the left (1) or right (-1) as needed
                            # based on the array index of the previous position (go left when moving from array index 0)
for 3,3,3,0,0,1,2;          # list of the array index of the next position

say$F[2]                    # output final position

```

# Answer
> 1 votes
## Python 2, 262 bytes

It feels so long. But there is also a lot of turning going on.

```
def f(l,s):
 r=lambda a,b,c=1:range(a,b,c)
 a=r(39,l[0],-1);b=r(l[0],-1,-1)
 c=r(l[1],l[2]-1,-1)if l[2]<l[1]else r(l[1],-1,-1);c.extend(r(39,l[2]-1,-1))
 return'  '.join(`x`for x in sum([r(s,-1,-1),a,b,a,b,a,b,r(39,l[0],-1),r(l[0],40),r(0,40),r(0,l[1]+1),c],[]))

```

Try it online!

I think I can concatenate some parts better in my last line but I am still new to code golf and I don't know how to tackle that list combination in a short way.

Any Ideas on improving this?

# Answer
> 0 votes
# Haskell, ~~135~~ 112 bytes

```
s!t=[s..39]++[0..mod(t-1)40]
s#t=[s,s-1..0]++[39,38..mod(t+1)40]
(a%b)c s=[s#s,s#s,s#s,s#a,a!a,a!b,b#c,[c]]>>=id

```

Try it online!

*Saved 23 bytes thanks to Laikoni*

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


# Question
Title: Proper army (Canadian Air Cadet) squadron formation
(Note: I'm not in the army so feel free to correct me if my formation is wrong, but I will not be changing the question. I will change any terminology mistakes though, because I'm trying to avoid air-cadet-specific wording choices)

(Note: this follows the standards for Canadian Air Cadets, not any actual army thing)

# Challenge

Given some configurations for a squadron, output what it should look like.

You will use 1 non-whitespace character to represent people.

### Configuration

The configuration will consist of a mandatory non-empty list, a mandatory positive integer, and an optional positive integer. The list represents the number of people per "squad", the mandatory integer represents the maximum number of rows, and the optional integer represents the number of "squads" in the squadron; in other words, the length of the list.

Each squad looks like this (without the commanders):

```
X X X X X
X   X X X
X   X X X

```

This would be a squad with 13 people in 3 rows.

A squad must be strictly wider than it is tall, unless it's a single person, in which case it's 1 × 1. It must also be as tall as possible (within the restriction for the number of rows); that is, once it is one larger than a perfect square, it should form another row. An exception is that when there are 5 people, it should still be a single row.\** The gap is always placed in the second column from the left, starting from the second row and moving downwards. For example, with 28 people and 5 rows maximum:

```
X X X X X X
X   X X X X
X   X X X X
X X X X X X
X X X X X X

```

Then, after the squad is formed, a commander is to be placed 2 rows above and below the squad, in the exact centre. For odd width squads:

```
    X

X X X X X
X X X X X
X X X X X

    X

```

And for even width squads:

```
   X

X X X X
X X X X
X X X X

   X

```

Hopefully you now understand how an individual squad is formed. Then, to form a squadron, each squad has 7 blank columns between it. For example, with a maximum row count of 3 and three squads of size 15, 16, and 17:

```
                      X

    X                X                 X

X X X X X       X X X X X X       X X X X X X
X X X X X       X   X X X X       X   X X X X
X X X X X       X   X X X X       X X X X X X

    X                X                 X

```

Then, in the final step, a commander is placed two rows above the row of front commanders, directly in the centre of the squadron, to the left if it has even width. In the example above, that would be the `X` at the very top.

The final output may contain trailing whitespace on each line and an optional trailing newline.

Here's a reference implementation: Try It Online! (Python 3)

# Input

Input will be given in any flexible format with the 3 components listed above: `list, int[, int]`.

# Rules

* Standard loopholes apply
* Output must be in this exact format (of course, you may choose the character to use)
* Newline may be CR, LF, or CRLF
* Trailing whitespace is allowed
* Trailing newline is allowed

\**Except our squadron's Flag Party formed a 3x2 pseudorectangle :P

# Answer
> 2 votes
# Python 3, 308 314 309 305 269 bytes

Input is the number rows in a squad and a list with a single integer for each squad, indicating the number of persons in the squad.

Could probably be golfed quite a bit.

**Edit:** +6 bytes, fixed a bug for squads with the same number of persons as rows

**Edit:** -6 bytes thanks to @Mr.Xcoder

**Edit:** -36 bytes by combining everything to one function

```
def z(r,l,v=" ",z="X "):q=[z,v]+[(v*6).join(([z.center((w//r+(w%r>0))*2),v]+[r*[z],[z+[z,v*2][I*w%r and r>=w%r+I]+z*(w//r+(w%r>0)-2)for I in range(r)]][w>r]+[v,z.center((w//r+(w%r>0))*2)])[i]for w in l)for i in range(r+4)];return"\n".join(p.center(len(q[2]))for p in q)

```

Try it online!

# Answer
> 1 votes
## Batch, 628 bytes

```
@echo off
call:s 1 %1 %4
call:s 2 %2 %4
call:s 3 %3 %4
set s=%s1%X%s1%       %s2%X%s2%       %s3%X
echo %s1%    %s2%    %s3%X
echo(
echo %s%
echo(
for /l %%i in (1,1,%4)do call:r %%i
echo(
echo %s%
exit/b
:q
set/ah=h%1,f=f%1
call set x=%%x%1%%
if %2 gtr %f% set x=X  %x:~3%
if %2 gtr %h% set x=%x:X= %
set r=%r%%x%
exit/b
:r
set r=
for %%j in (1 2 3)do call:q %%j %1
if not "%r: =%"=="" echo %r%
exit/b
:s
set h=%3
if %2==5 set h=1
:t
set/aw=~-%2/h+1
if %w% leq %h% set/ah-=1&goto t
set x=X
for /l %%i in (2,1,%w%)do call set x=%%x%% X
set/ah%1=h,f%1=%2-h*~-w
set x%1=%x%
set s%1=%x:X=%

```

Takes the three squad sizes and the height as parameters. Explanation:

```
call:s 1 %1 %4
call:s 2 %2 %4
call:s 3 %3 %4

```

Calculate the dimensions of each squad.

```
set s=%s1%X%s1%       %s2%X%s2%       %s3%X

```

Calculate the squad commanders. The `sN` variables hold a number of spaces equal to half the width in characters of the squads rounded down, so adding this on both sides centres each commander.

```
echo %s1%    %s2%    %s3%X
echo(

```

Calculate and output the position of the front commander. This is similar to the case of the individual commanders except for the additional spacing between the squads, which has to be rounded up to allow for the `sN` being rounded down.

```
echo %s%
echo(

```

Output the first row of individual commanders.

```
for /l %%i in (1,1,%4)do call:r %%i

```

Output the squads.

```
echo(
echo %s%
exit/b

```

Finish by outputting the second row of per-squad commanders.

```
:q
set/ah=h%1,f=f%1
call set x=%%x%1%%

```

Get the height, full width rows and full width cadet string for the squad.

```
if %2 gtr %f% set x=X  %x:~3%

```

If this is not a full width row, remove the second cadet.

```
if %2 gtr %h% set x=%x:X= %

```

If all the rows have already been output, remove all the cadets.

```
set r=%r%%x%
exit/b

```

Add any remaining cadets to the overall row.

```
:r
set r=
for %%j in (1 2 3)do call:q %%j %1
if not "%r: =%"=="" echo %t%
exit/b

```

Given a row in `%1`, add each squad's cadets for that row and output the result.

```
:s
set h=%3
if %2==5 set h=1
:t
set/aw=~-%2/h+1
if %w% leq %h% set/ah-=1&goto t

```

Calculate the number of rows and columns for this squad.

```
set x=X
for /l %%i in (2,1,%w%)do call set x=%%x%% X

```

Calculate the full width cadet string for this squad.

```
set/ah%1=h,f%1=%2-h*~-w
set x%1=%x%

```

Calculate the number of full width rows and save all the results in per-squad variables.

```
set s%1=%x:X=%

```

Also calculate the half-width string for centring purposes.

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