title: Is it a valid Parker Square

text:
# Question
Title: Is it a valid Parker Square
5 Years ago, this happened, and then it became sort of a meme.

# Challenge

The Challenge today is, to check if a "magic square" is a valid parker square.
What is a **Real Magic square**?

* All the numbers must be natural or sometimes 0
* The sum of rows, columns and diagonals must be same.
* There must be no repeating numbers

What Matt tried to achieve is a real magic square but with all the numbers being squares.
But what he did is a semi-magic square, sometimes called The Parker Square.

What **is** a valid parker square (rules made by me)?

* It must be a \\$3\times3\\$ "magic square"
* There **must** be at least one number that appear twice in the square
* The rows and columns must add up to the same number
* At least one diagonal must add up to the same number too.
* Each number must be the square of an integer

# Rules

* Input must be given in a form of a list (flat or 2-dimensional), or just 9 inputs from top left to bottom right
* Input is guaranteed to represent a \\$3×3\\$ square
* Output must be a Boolean, 1 or 0, no output or some output
* Standard Loopholes apply
* This is , so the shortest code in each language wins!

# Examples

```
Classic Parker Square:
In: [841, 1, 2209, 1681, 1369, 1, 529, 1681, 841]
Out: True

0-Square
In: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Out: 1

Mirrored Square:
In: 4, 9, 1, 9, 1, 9, 1, 9, 4
Out: 0

Random Square:
In: 1, 2, 4, 3, 4, 9, 8, 9, 0
Out: False

Real Magic Square:
In: [[8, 1, 6], [3, 5, 7], [4, 9, 2]]
Out:

Pythagorean triple (by Arnauld):
In: [25, 0, 0, 0, 16, 9, 0, 9, 16]
Out: false

Non integer (Suggested by Luis):
In: [841.45, 1, 2209, 1681, 1369, 1, -529, 1681, 841]
Out: false

Almost real magic square of squares (Suggested by Jonathan):
In: [[16129, 2116, 3364], [4, 12769, 8836], [5476, 6724, 9409]]
Out: 0

```

Disclaimer: I put magic square in quotes, because most people don't think it is a magic square if the numbers repeat. But it doesn't mean it is easy to make a "magic square" with only a few numbers repeating, all squares and on of the diagonals working. Good work Matt!

# Answer
> 8 votes
# 05AB1E, ~~25~~ 23 bytes

-1 byte thanks to Grimmy!

```
Â‚εÅ\ªIø«OË}àI˜ÐÙÊsÅ²PP

```

Try it online! or Try all cases!

**Commented:**

```
Â‚               # pair the input with its reverse
  ε        }     # map over each of them:
   Å\            #   take the main diagonal
     ª           #   append this to the input
      Iø         #   push the input transposed
        «        #   and concatenate this to the list
         O       #   sum rows, columns and the diagonal
          Ë      #   are all sums equal?
            à    # is one of the two results a 1?

I˜               # push the input and flatten it
  Ð              # triplicate
   ÙÊ            # does the uniquified flat input not equal the flat input?
     s           # swap to flattened input
      Å²         # for every number: is it a square integer?
        P        # are all square?

P                # take the product (AND reduction) of all results

```

# Answer
> 6 votes
# Vyxal, 34 bytes

```
Ṙ"vÞDƛh∑;??øTJv∑$Mƛf≈;a?fDU≠$∆²AWΠ

```

Try it Online!

Bug fixes make it even messier.

# Answer
> 6 votes
# , ~~106~~ ~~105~~ 104 bytes

```
function(m,`?`=colSums)all(table(m)<2)|sd(c(?m,s<-?t(m)))|any(m^.5%%1)|sum(diag(m))-s&&sum(m[1:3*2+1])-s

```

Try it online!

Output is reversed\*: `TRUE` if it is *not* a Parker square, `FALSE` otherwise.

**Ungolfed code** (still the right way around):

```
is_parker_square=
function(m){
    twice=any(table(m)-1) # some number must appear twice
    rowscols=!sd(c(rowSums(m),s<-colSums(m))) # rows & cols must have same sum
    diags=any(c(sum(diag(m)),sum(diag(m[3:1,])))==s) # at least one diag must have same sum
    squares=!any(m^.5%%1) # all numbers are squares
    twice && rowscols && diags && squares
}

```

\*Add +5 bytes to output `TRUE` for a Parker square.

# Answer
> 6 votes
# JavaScript (ES7),  ~~129~~  120 bytes

Expects a flat array of 9 values. Returns **0** for Parker, or **1** for non-Parker.

```
a=>new Set([A,B,C,D,E,F,G,H,I]=a).size>8|a.some(x=>x**.5%1)|[D+E+F,G+H+I,A+D+G,B+E+H].some(x=>x-A-B-C)|E+I!=B+C&E+G!=A+B

```

Try it online!

Or **117 bytes** if we can just return truthy / falsy values.

### How?

We split the input array into 9 distinct variables.

```
A B C
D E F
G H I

```

At the same time, we turn the input array into a set and check its size. If it's greater than \\$8\\$, then all values are distinct and this is not a Parker square.

```
new Set([A, B, C, D, E, F, G, H, I] = a).size > 8

```

We test whether at least one of the values is not a square:

```
a.some(x => x ** .5 % 1)

```

We test the sum of the values in the 2nd row, 3rd row, 1st column and 2nd column. If one of them is not equal to the sum of the values in the 1st row, this is not a Parker square.

```
[D + E + F, G + H + I, A + D + G, B + E + H].some(x => x - A - B - C)

```

**Note**: We don't have to test the 3rd column. It's trivial to prove that we have \\$F+I=A+B\\$ (and therefore \\$C+F+I=A+B+C\\$) if all other sums described above are correct.

Finally, we test whether both diagonals have an invalid sum:

```
E + I != B + C & E + G != A + B

```

# Answer
> 4 votes
# Jelly,  ~~27~~  25 bytes

```
S;§fƑⱮ,UŒDḢ$€§ƲẸȧÆ²Ȧȧ⁸FQƑ

```

Parker: `0`, non-Parker: `1` \- just like it always seems to be! ;p

**Try it online!**

### How?

```
S;§fƑⱮ,UŒDḢ$€§ƲẸȧÆ²Ȧȧ⁸FQƑ - Link: 3 by 3 matrix, M
S                         - column sums (M)
  §                       - row sums (M)
 ;                        - (column sums) concatenate (row sums)
              Ʋ           - last four links as a monad - f(M):
       U                  -   reverse each row (of M)
      ,                   -   (M) pair (reversed row version)
           $€             -   for each:
        ŒD                -     diagonals
          Ḣ               -     head
             §            -   sums -> [sum(main diagonal), sum(anti-diagonal)]
     Ɱ                    - map with:
    Ƒ                     -   is invariant under:
   f                      -     (column-and-row-sums) filter keep (diagonal-sum)
               Ẹ          - any?
                 Æ²       - is square (vectorises across M)
                ȧ         - logical AND -> 0 or [[is r1c1 square?,...],...]
                   Ȧ      - contains no zero when flattened?
                    ȧ⁸    - logical AND with M -> 0 or M
                      F   - Flatten -> [0] or flattened M
                        Ƒ - is invariant under:
                       Q  -   deduplicate

```

# Answer
> 4 votes
# , 59 57 bytes

```
((<.@%:-:%:)*]>&#~.)@,*3>+/(2#.{.~:])@,1&#.,],&(2{+//.)|.

```

Try it online!

* `(<.@%:-:%:)` All are perfect squares.
* `]>&#~.` Length of uniq is less than length (ie, has repeats)
* The remainder first creates a single list of all 8 relevant sums (cols, rows, diagonals):
    + `],&(2{+//.)|.` Get the `/` diagonal sum of both the input and the input with rows reversed. This gives us both diagonal sums.
    + `1&#.,` Prepend row sums.
    + `+/...,` Prepend col sums.
* `{.~:]` Turn that list into a boolean list indicating which elements are *not* equal to the first element.
* `2#.` Interpret that result as a binary number.
* `3>` Check if it is less than 3 (will only be true if at most 1 diagonal fails to match the other sums)

# Answer
> 3 votes
# JavaScript (Node.js), ~~165 163~~ 161 bytes

```
l=>l.some(e=>e**.5%1)|(I=([c,i=3])=>l[c]+l[c+=i]+l[c+=i]!=l[0]+l[1]+l[2])([0,4])&I([2,2])|[[0],[1],[2],[3,1],[6,1]].some(I)|l.every(e=>l.map(g=>z+=g==e,z=0)|z<2)

```

Try it online!

This feels too long.

Outputs 1 for non-Parker and 0 for Parker.

+38 to fix bug

# Answer
> 3 votes
# MATL, 30 bytes

```
t!GXdGPXd&hsdXB2>GX^1\=Gun9<vA

```

Input is a 3×3 matrix. Output is `1` if it is a Parker square, `0` if not.

Try it online! Or verify all test cases.

### Explanation

```
t!    % Implicit input: 3×3 matrix. Duplicate
GXd   % Push input again. Diagonal as a column vector
GPXd  % Push input, flip vertically. Diagonal as a column vector (this is the
      % anti-diagonal of the input)
&h    % Concatenate everything horizontally. This gives a 8×3 matrix whose
      % columns are: the 3 columns of the input, the 3 rows of the input, the
      % diagonal and the anti-diagonal
s     % Sum of eah column. Gives a row vector of length 8 (*)
d     % Consecutive differences. Gives a row vector of length 7
XB    % Convert from binary expansion to number. This treats nonzero values in
      % the input as 1
2>    % Is it greater than 3? (**) This gives false if and only if all entries
      % in (*) are equal except perhaps the last or second-to-last, but not both
      % (The result will be false for a valid input)
GX^   % Push input. Square root of each entry
1\    % Modulo 1. (***) (All entries give 0 for a valid input)
=     % Equal? Since the modulus is always less than 1, equality means that all
      % entries in (***) were 0, as was (**). (This gives a matrix containing
      % only true for a valid input)
Gun   % Push input again, unique elements as a row vector, number of elements
9<    % Less than 9? (True for a valid input)
v     % Concatenate everything into a column vector
A     % All: gives true if all entries are true. Implicit display

```

# Answer
> 2 votes
# Python 3.8 (pre-release), ~~154~~  144 bytes

```
lambda a:1-any([len({*a})>8,{(s:={sum(a[i%7:i%5*3:i%4])-a[4]for i in b"\r@@@+?"}).pop()}-{a[0]+a[8],a[2]+a[6]},s,sum(i<0 or i**.5%1for i in a)])

```

`@` represents unprintables chars

Outputs 1 for Parker, 0 for not Parker

Try it online!

A pretty messy solution ^^

## How it works:

* `1-any([...])` will return 1 if all elements are `False`
* `len({*a})>8` length of the set of `a`, returne `True` if equal to `9` (no duplicates)
* `(s:={sum(a[i%7:i%5*3:i%4])-a[4]for i in b"\r@@@+?"})` create the set of the sums of all lines and columns (name it `s`). I used the impicit conversion of bytes into ints to store the values for the slices.
* `{ .pop()}-{a[0]+a[8],a[2]+a[6]}` remove an element of `s` and verify if it is equal to the sum of one diagonal. I used set substraction. If it is present, return the empty set (=\> False) else, return itself (=\>True)
* `s` verify if `s` is empty (=\> False if `s` had exactly one element before the pop)
* `sum(i<0 or i**.5%1for i in a)` verify both than i is positive and i is a square. If any `i` is lower than 0, `i<0` will be True and the sum will no longer be nul. If any `i` is not a sqare, `i**.5` (sqrt(i)) will have a decimal part and `i**.5%1` won't be nul.

---
Tags: code-golf, math, decision-problem, grid, matrix
---


title: Sum of set bits from 1 to n

text:
# Question
Title: Sum of set bits from 1 to n
Given an integer \\$ n \\$ \\$ (n \ge 1) \\$, return/output the total number of set bits between \\$ 1 \\$ and \\$ n \\$ inclusive. To make the problem more interesting, **your solution must run with a time complexity of** \\$ \mathcal{O}((\log n)^k) \\$ **or better, for some constant** \\$ k \\$ **(AKA poly-logarithmic time complexity)**.

This is OEIS A000788, not including \\$ n = 0 \\$. Here are the first 100 numbers:

```
1, 2, 4, 5, 7, 9, 12, 13, 15, 17, 20, 22, 25, 28, 32, 33, 35, 37, 40, 42, 45, 48, 52, 54, 57, 60, 64, 67, 71, 75, 80, 81, 83, 85, 88, 90, 93, 96, 100, 102, 105, 108, 112, 115, 119, 123, 128, 130, 133, 136, 140, 143, 147, 151, 156, 159, 163, 167, 172, 176, 181, 186, 192, 193, 195, 197, 200, 202, 205, 208, 212, 214, 217, 220, 224, 227, 231, 235, 240, 242, 245, 248, 252, 255, 259, 263, 268, 271, 275, 279, 284, 288, 293, 298, 304, 306, 309, 312, 316, 319

```

This is , so the shortest code in bytes wins.

# Answer
# K (ngn/k), ~~45~~ 32 bytes

```
{+/b*1+(q!'x)+-2!q*<q:2/=#b:2\x}

```

Try it online!

*Golfing ideas thanks to @ngn and @coltim*

The OEIS page contains a curious PARI program:

```
a(n)=if(n==0,0,m=logint(n,2);r=n%2^m;m*2^(m-1)+r+1+a(r));

```

which has a recursion depth of \\$\mathcal{O}(\log n)\\$ and each recursive call involves constant number of arithmetic operations (and therefore meets the time complexity requirement).

I translated this recursive formula to vectorized operations on the bit pattern of n, keeping array dimensions to the number of bits of n, so every built-in op takes polylog time of n.

```
1  0  1  1 0 0 // n = 44 -> 115
5  4  3  2 1 0 // m
16 8  4  2 1 0 // 2^(m-1)
12 12 4  0 0 0 // n mod 2^(m-1)
93    17 5     // m * 2^(m-1) + n mod 2^(m-1) + 1,
               // keeping only ones in the bits of n
sum = 115

```

How the solution works:

```
{+/b*1+(q!'x)+-2!(<q)*q:2/=#b:2\x}  x:n
                            b:2\x   b:bit pattern of n
                      q:2/=#b   q:reversed powers of 2
                          =#    identity matrix of size #b
                        2/      evaluate in base 2 column-wise
              -2!(<q)*q    m*2^(m-1) for m in #b-1..0
                  <q       grade up q; the power is in decreasing order
                           so it gives #b-1..0
              -2!(  )*q    multiply 2^m and divide by 2
       (q!'x)+    add n%2^m
     1+           add 1
 +/b*             add the terms corresponding to one bits

```
> 13 votes

# Answer
# JavaScript (ES6),  ~~57 54 53~~  52 bytes

```
n=>(i=0,g=b=>b--&&(n>>b&1&&b+i+i++<<b)+g(b))(32)/2+i

```

Try it online!

This is designed for 32-bit integers and always performs 32 iterations, no matter the input value.

The following version performs \\$\lfloor log\_2(n)\rfloor+1\\$ iterations instead, but this is really pointless since bitwise operations on vanilla JS numbers  \[1\]  are limited to 32 bits anyway:

```
n=>(i=0,g=b=>b--&&(n>>b&1&&b+i+i++<<b)+g(b))(32-Math.clz32(n))/2+i

```

Try it online!

\[1\]: i.e. without using BigInts or a Big Integer library

### How?

As mentioned by Emeric Deutsch in A001787, the total sum of set bits between \\$1\\$ and \\$2^k-1\\$ is:

$$k\times 2^{k-1}$$

Below is an illustration of the first few terms:

```
       1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
       V \___/ \_____________/ \_____________________________________/
count: 1   3          8                           20
sum  : 1   4          12                          32

```

Because we only need one extra bit to go from \\$2^k-1\\$ to \\$2^k\\$, the total sum of set bits between \\$1\\$ and \\$2^k\\$ is:

$$k\times 2^{k-1}+1$$

In order to compute the total sum of set bits between \\$1\\$ and an arbitrary integer \\$N\\$ of \\$M+1\\$ bits, we can use the above formula for each set bit at position \\$0\le b\le M\\$ in \\$N\\$. But we also have to take the total number of set bits at a position higher than \\$b\\$ into account, because they have to be counted several times.

We end up with:

$$\sum\_{b=0}^{M} B(b)\times(b\times 2^{b-1}+1+S(b)\times 2^b)$$

where:

* \\$B(b)\\$ is the value of the bit \\$b\\$ (0-indexed)
* \\$S(b)=\sum\_{i=b+1}^{M} B(i)\\$

Here is an ungolfed implementation.

In the golfed version, we go from the most to the least significant bit and keep track of the number of set bits in `i`. Besides, we ignore the `+1` in the formula and add `i` at the very end of the process instead.
> 13 votes

# Answer
# JavaScript (ES6), 51 bytes

```
f=(n,i=0,p=1<<i)=>n<p?0:f(n,i+1)+(n&p&&n%p+1+p*i/2)

```

Try it online!

Let we denote

$$ n = \left(\overline{b\_mb\_{m-1}\dots b\_2b\_1b\_0}\right)\_2 $$

Then

$$ f\left(n\right)=\sum\_{i=0}^{m} b\_i \cdot \left(\left(n \bmod 2^i\right) + 1 + 2^{i-1}\cdot i\right) $$

This function loops from \\$0\\$ to \\$m\\$ with constant time each loop. And we have

$$ m = \mathcal{O}\left(\log n\right) \ $$

It would be 55 bytes to handle larger numbers (BigInt).
> 6 votes

# Answer
# Python 3, ~~106~~ 104 bytes

```
def f(A):
 A+=1;a=0
 for i in range(32):
  x=2<<i;d,r=A//x,A%x;a+=d*x/2
  if 2*r>x:a+=r-x/2
 return a

```

Try It Online!!

This is designed for 32-bit integers, here I am using float to save some bytes from "//" operator, I hope you won't mind \\$x.0\\$ instead of \\$x\\$, further bytes can be reduced if I allow hardcoding input by user.

P.S. This is my first answer, hope to hear some suggestions.
> 4 votes

# Answer
# Charcoal, 28 bytes

```
ＮθＩΣＥ⮌↨θ²⁺×÷θＸ²⊕κＸ²κ×ι⊕﹪θＸ²κ

```

Try it online! Explanation: For a given bit position `k`, the sum of the bits at position `k` from `1` to `n` depends on whether the `k`th bit of `n` is `0` or `1`:

* If the `k`th bit of `n` is `0`, then the bits at position `k` are of the form `0...1...0...1...0...1...0..0`. Each run of `2ᵏ⁺¹` integers contributes `2ᵏ` bits.
* If the `k`th bit of `n` is `1`, then the bits at position `k` are of the form `0...1...0...1...0...1...0...1..1`. This means that there are `(n mod 2ᵏ)+1` extra `1` bits to account for.

Since the number of bits is O(log n), this is the major factor in the time complexity of the algorithm.

```
Ｎθ                              Input `n` as an integer
       θ                        `n`
      ↨ ²                       Converted to base 2
     ⮌                          Reversed so LSB first
    Ｅ                           Map over bits
            θ                   Input `n`
           ÷                    Integer divide by
              ²                 Literal 2
             Ｘ                  Raised to power
                κ               Index `k`
               ⊕                Incremented
          ×                     Multiplied by
                  ²             Literal 2
                 Ｘ              Raised to power
                   κ            Index `k`
         ⁺                      Plus
                     ι          Current bit
                    ×           Multiplied by
                        θ       Input `n`
                       ﹪        Modulo
                          ²     Literal `2`
                         Ｘ      Raised to power
                           κ    Index `k`
                      ⊕         Incremented
   Σ                            Take the sum
  Ｉ                             Cast to string
                                Implicitly print

```
> 2 votes

# Answer
# Python 3, 81 bytes

```
def f(A):
 c=0
 while A>1:
  a=len(bin(A))-3;A=A%(2**a);c+=2**a*a/2+A
 return c

```

Try it online!

For exponentials of 2 -1 every bit is flipped 50% of the time so the total sum of bits is `n*(# of bits)/2` this gets done recursively. For every further recursion we also need to add up the first bits that get progessively ignored.
> 1 votes

# Answer
# Python 3, 64 bytes

```
f=lambda n:n and(2*f(n//2)+n//2+1if n%2else f(n/2)+f(n/2-1)+n/2)

```

Try it online!

from the recurrence relation: a(0) = 0, a(2n) = a(n)+a(n-1)+n, a(2n+1) = 2a(n)+n+1
> 1 votes

# Answer
# Python 3.8 (59 bytes)

```
f=lambda n:n and(r:=2**(m:=len(bin(n))-3))*m/2+n%r+1+f(n%r)

```

Here is my attempt 2, since `dingledooper` noted that my previous attempt was not polylog time complexity.

Also, the golfiness can probably be improved by using walrus operator in python3.8

I used the formula found from "a curious PARI program on the OEIS page": `a(n) = if (n==0, 0, m = logint(n, 2); r = n % 2^m; m*2^(m-1) + r + 1 + a(r));`

My ungolfed code is:

```
def a(n):
    output = 0.0
    while n:
        logn = n.bit_length() - 1 # log(n) in base 2, golfed: len(bin(n))-3
        n = n % (2 ** logn) # strip top bit, golfed: n%r
        output += logn*2**(logn-1) + n + 1 # golfed: m*r/2+n%r+1
    return output

```
> 1 votes

---
Tags: code-golf, binary, restricted-complexity
---


title: Construct ASCII arches

text:
# Question
Title: Construct ASCII arches
I like ascii art and I get bored a lot, so I found some ascii characters and started to make random things, 8-bit mario castle, mazes, and arches. I found that the arches could easily be stacked in a neat way.

```
╔═══════╗
║╔═════╗║
║║╔═══╗║║
║║║╔═╗║║║
╨╨╨╨─╨╨╨╨

```

# Challenge

Create a program, function, or any other standard format that accepts an integer that is greater than or equal to 0 (unless you are doing the bonus) and outputs ascii art with the amount of arches specified.

# Test Cases

Input:

```
7

```

Output:

```
╔═════════════╗
║╔═══════════╗║
║║╔═════════╗║║
║║║╔═══════╗║║║
║║║║╔═════╗║║║║
║║║║║╔═══╗║║║║║
║║║║║║╔═╗║║║║║║
╨╨╨╨╨╨╨─╨╨╨╨╨╨╨

```

Alt:

```
+-------------+
|+-----------+|
||+---------+||
|||+-------+|||
||||+-----+||||
|||||+---+|||||
||||||+-+||||||
||||||| |||||||
---------------

```

Input:

```
1

```

Output:

```
╔═╗
╨─╨

```

Alt:

```
+-+
| |
---

```
* If the integer is 0 then don't output anything
* This question will be in utf-8, each character will count as a "byte"
* This is so the shortest answer wins.
* You have the option of using `+-+` instead of `╔═╗`, `---` instead of `╨─╨`, and `|` instead of

# Bonus (not decided whether to allow this on the alternate version because it wouldn't be as hard)

-10% if the program supports negative numbers and flips the arches like so

```
╥╥╥╥─╥╥╥╥
║║║╚═╝║║║
║║╚═══╝║║
║╚═════╝║
╚═══════╝

```

# Answer
> 1 votes
# CJam, 59 bytes

```
qi:Lg"^Za"a{_0=1'Z3*tsa\{'[2*\*}%+}L(*'rL*a2*N*a+9462ff+N**

```

Try it here!

# Answer
> 2 votes
## Python 2, 106 bytes (94 chars)

```
n=input();j=1
exec"s=j/2*'║';print s+'╔'+'═'*(2*n-j)+'╗'+s;j+=2;"*n
if n:t='╨'*n;print t+'─'+t

```

Pretty straightforward. Prints line by line with a changing number of horizontal and vertical bars. The last line is printed separately.

I feel like I'm missing some optimizations. The fact that the chars are multiple bytes means you can't do something like `'║╨'[n>0]`, so I didn't find a good way to print the last line in the loop. It's ugly that there's so much manipulation going on with the counter. I'd like update strings directly, like `s+='║'`, but the index is also used for horizontal bars.

# Answer
> 2 votes
# Perl, 78 82 chars

```
$n='─';$_='══'x pop;while(s/══//){print"$s╔═$_╗$s\n";$s.="║";$n="╨$n╨"}$s&&print$n

```

Sadly, I couldn't figure out a way to take advantage of the bonus without increasing the size by more than 10%. I may yet prevail.

**Ungolfed**

Pretty straightforward, really. Builds up bottom line (`╨$n╨`) incrementally, while shortening top line (`══`) by two characters, ending when it can no longer be shortened, so I don't have to mess with counters.

```
 $n = '─'; # Bottom line
 $_ = '══'x pop; # "Top" line, length from commandline argument
 while (s/══//) { # Shorten top line by two characters
     print "$s╔═$_╗$s\n"; # Print current line with $s (sides)
     $s .= "║";           # Append vertical bar to sides
     $n  = "╨$n╨";        # Widen bottom line
 }
 $s && print $n; # Print bottom line if input is not 0

```

# Answer
> 1 votes
# Bash, 124 bytes (112 characters)

```
printf -vh %$1s
b=${h// /╨}
h=${h// /═}
for((n=$1;n--;)){
echo $v╔$h${h:1}╗$v
h=${h#?}
v+=║
}
(($1))&&echo $b─$b

```

Sample run:

```
bash-4.3$ bash ascii-arch.sh 7
╔═════════════╗
║╔═══════════╗║
║║╔═════════╗║║
║║║╔═══════╗║║║
║║║║╔═════╗║║║║
║║║║║╔═══╗║║║║║
║║║║║║╔═╗║║║║║║
╨╨╨╨╨╨╨─╨╨╨╨╨╨╨

bash-4.3$ bash ascii-arch.sh 1
╔═╗
╨─╨

bash-4.3$ bash ascii-arch.sh 0

```

# Answer
> 1 votes
# Japt `-R`, 29 bytes

Uses `+` & `-`. Sacrificed 4 bytes to handle the *bloody* input validation!

```
©Æ'+²¬q-p´UÑÄÃpS û| p-pNÑÄ)ªP

```

Try it

---

## Explanation

```
                                  :Implicit input of integer U
©                                 :Logical AND with U
 Æ                                :Map the range [0,U)
  '+                              :  Literal "+"
    ²                             :  Repeat twice
     ¬                            :  Split
      q                           :  Join with
       -                          :   Literal "-"
        p                         :   Repeat
         ´U                       :    Decrement U
           Ñ                      :    Multiply by 2
            Ä                     :    Add 1
             Ã                    :End mapping
              pS                  :Push a space
                 û|               :Centre pad each element with "|" to the length of the longest element
                    p     )       :Push
                     -            : Literal "-"
                      p           : Repeat
                       N          :  The array of inputs (which will be cast to an integer if we perform a mathematical operation on it)
                        ÑÄ        :  Multiply by 2 and add 1
                           ª      :Logical OR
                            P     :The empty string
                                  :Implicitly join with newlines and output

```

# Answer
> 0 votes
# JavaScript (ES6), 101 characters

```
f=(n,i=0)=>n?i-n?(b="║"[r="repeat"](i))+`╔${"═"[r]((n-i)*2-1)}╗${b}
`+f(n,i+1):(g="╨"[r](n))+"─"+g:""

```

## Explanation

Recursive function that prints each line

```
f=(n,i=0)=>              // f = recursive function, i = current line (default = 0)
  n?                     // if n != 0
    i-n?                 // if we are not in the last line, print the line
      (b="║"[r="repeat"](i))+`╔${"═"[r]((n-i)*2-1)}╗${b}
`+f(n,i+1)               // add the output of the next line
    :(g="╨"[r](n))+"─"+g // if we ARE in the last line, print the last line
  :""                    // print nothing if n = 0

```

## Test

Test does not use default parameter for browser compatibility.

```
var solution = f=(n,i)=>n?(i|=0)-n?(b="║"[r="repeat"](i))+`╔${"═"[r]((n-i)*2-1)}╗${b}
`+f(n,i+1):(g="╨"[r](n))+"─"+g:""
```

```
<input type="number" oninput="result.textContent=solution(+this.value)" />
<pre id="result"></pre>
```

# Answer
> 0 votes
# PHP (109 chars)

```
$s='';for($b=($n=$argv[1])?'─':'';$n--;){echo$s.'╔═'.str_repeat('══',$n)."╗$s\n";$s.='║';$b="╨{$b}╨";}echo$b;

```

Still need to get rid of that str\_repeat but most alternatives won't handle mulyibyte chars.

```
$s = '';
// Initialise $b (bottom) to '─' or '' for n==0
for ($b = ($n = $argv[1]) ? '─' : ''; $n--;) {
    // Echo sides + arch + sides
    echo $s . '╔═' . str_repeat('══', $n) . "╗$s\n";
    // Growing sides
    $s .= '║';
    // Growing bottom
    $b = "╨{$b}╨";
}
// Show bottom
echo $b;

```

# Answer
> 0 votes
# Retina, 79 chars

```
.+
$0$*═$0$*═╗
^═
╔
+`(║*)╔═(═+)═╗║*$
$0¶$1║╔$2╗║$1
(\S+)$
$0¶$1
T`═╔╗║`─╨`\S+$

```

Try it online.

This uses a new feature in Retina that replaces a decimal number `\d+` with a list of that many characters `$0$*═`.

# Answer
> 0 votes
# Swift (209 bytes)

Probably Swift is not the best language for this, this is my first time trying to do a code golf challenge:

```
func *(l:String,r: Int)->String{return r>0 ?l+(l*(r-1)):""}
let n=Int(readLine()!)!
for i in 0...(n-1){let a=("║"*i)+"╔═";let b=a+("══"*(n-1-i))+"╗"+("║"*i);print(b)};print("╨"*n+"─"+"╨"*n)

```

# Answer
> 0 votes
# Ruby, 90 bytes (74 characters)

```
->n{n.times{|i|puts ?║*i+?╔+?═*((n-i)*2-1)+?╗+?║*i}>0&&puts(?╨*n+?─+?╨*n)}

```

Sample run:

```
2.1.5 :001 > ->n{n.times{|i|puts ?║*i+?╔+?═*((n-i)*2-1)+?╗+?║*i}>0&&puts(?╨*n+?─+?╨*n)}[7]
╔═════════════╗
║╔═══════════╗║
║║╔═════════╗║║
║║║╔═══════╗║║║
║║║║╔═════╗║║║║
║║║║║╔═══╗║║║║║
║║║║║║╔═╗║║║║║║
╨╨╨╨╨╨╨─╨╨╨╨╨╨╨
 => nil

2.1.5 :002 > ->n{n.times{|i|puts ?║*i+?╔+?═*((n-i)*2-1)+?╗+?║*i}>0&&puts(?╨*n+?─+?╨*n)}[1]
╔═╗
╨─╨
 => nil

2.1.5 :003 > ->n{n.times{|i|puts ?║*i+?╔+?═*((n-i)*2-1)+?╗+?║*i}>0&&puts(?╨*n+?─+?╨*n)}[0]
 => false

```

# Answer
> 0 votes
# Haskell, ~~151~~ 162 bytes

```
r=replicate
c=concat
f n=putStr$unlines[c[r i '║',"╔",r(2*(n-i)-1)'═',"╗",r i '║']|i<-[0..n-1]]++c[r n '╨',r(signum n)'─',r n '╨']
main=readLn>>=f

```

Edit: I forgot to deal with `0` as input

# Answer
> 0 votes
# , 54 chars / 95 bytes

```
⩥ïⓜᵖ⟮ ⍘|ď⟯$+`+⦃⟮⍘-ď (ï⟯-$)*2-1)}+`+Ⅰ$;ï⅋ᵖⅠï+⬭+Ⅰï,Ⅱ*2+1

```

`Try it here (Firefox only).`

# Explanation

```
⩥ïⓜᵖ⟮ ⍘|ď⟯$+`+⦃⟮⍘-ď (ï⟯-$)*2-1)}+`+Ⅰ$;ï⅋ᵖⅠï+⬭+Ⅰï,Ⅱ*2+1 // implicit: ï=input, $=mapped item
                                                       // PHASE 1
⩥ïⓜ                                                   // create a range to map over
    ᵖ                                                  // push to stack:
     ⟮ ⍘|ď⟯$                                            // | repeated $ times
           +`+⦃⟮⍘-ď (ï⟯-$)*2-1)}+`                      // & +[- repeated 2$-1 times]+
                                 +Ⅰ$;                  // & | repeated $ times
                                                       // PHASE 2
                                     ï⅋                // if ï>0
                                       ᵖ               // push to stack 2 items:
                                        Ⅰï+⬭+Ⅰï,      // | repeated $ times & [space] & | repeated $ times
                                                 Ⅱ*2+1 // and - repeated 2ï+1
                                                       // implicit stack output, newline-separated

```

NOTE: this makes use of good ol' copy blocks to get at the spots where ordinary variable declaring could not reach.

# Answer
> 0 votes
# Sed, 97 bytes (81 characters)

(96 bytes (80 characters) code + 1 character command line option)

```
s/.(.*)/2&\13/
t
:
H
s/(.+)11(.+)/4\1\24/
t
y/1234/─╨╨╨/
H
g
s/\n//
y/1234/═╔╗║/

```

Input expected as unary integer.

Sample run:

```
bash-4.3$ sed -r 's/.(.*)/2&\13/;t;:;H;s/(.+)11(.+)/4\1\24/;t;y/1234/─╨╨╨/;H;g;s/\n//;y/1234/═╔╗║/' <<< '1111111'
╔═════════════╗
║╔═══════════╗║
║║╔═════════╗║║
║║║╔═══════╗║║║
║║║║╔═════╗║║║║
║║║║║╔═══╗║║║║║
║║║║║║╔═╗║║║║║║
╨╨╨╨╨╨╨─╨╨╨╨╨╨╨

bash-4.3$ sed -r 's/.(.*)/2&\13/;t;:;H;s/(.+)11(.+)/4\1\24/;t;y/1234/─╨╨╨/;H;g;s/\n//;y/1234/═╔╗║/' <<< '1'
╔═╗
╨─╨

bash-4.3$ sed -r 's/.(.*)/2&\13/;t;:;H;s/(.+)11(.+)/4\1\24/;t;y/1234/─╨╨╨/;H;g;s/\n//;y/1234/═╔╗║/' <<< ''

```

# Sed, 105 bytes (75 characters)

(104 bytes (74 characters) code + 1 character command line option)

```
y/1/═/
s/.(.*)/╔&\1╗/
t
:
H
s/(.+)══(.+)/║\1\2║/
t
y/╔║╗═/╨╨╨─/
H
g
s/\n//

```

Input expected as unary integer.

Sample run:

```
bash-4.3$ sed -r 'y/1/═/;s/.(.*)/╔&\1╗/;t;:;H;s/(.+)══(.+)/║\1\2║/;t;y/╔║╗═/╨╨╨─/;H;g;s/\n//' <<< '1111111'
╔═════════════╗
║╔═══════════╗║
║║╔═════════╗║║
║║║╔═══════╗║║║
║║║║╔═════╗║║║║
║║║║║╔═══╗║║║║║
║║║║║║╔═╗║║║║║║
╨╨╨╨╨╨╨─╨╨╨╨╨╨╨

bash-4.3$ sed -r 'y/1/═/;s/.(.*)/╔&\1╗/;t;:;H;s/(.+)══(.+)/║\1\2║/;t;y/╔║╗═/╨╨╨─/;H;g;s/\n//' <<< '1'
╔═╗
╨─╨

bash-4.3$ sed -r 'y/1/═/;s/.(.*)/╔&\1╗/;t;:;H;s/(.+)══(.+)/║\1\2║/;t;y/╔║╗═/╨╨╨─/;H;g;s/\n//' <<< ''

```

# Answer
> 0 votes
# Canvas, 15 bytes

```
-＊+∔］⤢：↷±ｎ│Ｌ-×∔

```

Try it here!

Explanation:

```
{    ]            map over 1..input
 -*                 repeat "-" counter times
   +∔               append "+" to that
      ⤢           transpose
       :          create a duplicate of that
        ↷±        rotated 90°, then reversed horizontally
          n       overlap the 2
           |      and palindromize horizontally with 1 overlap
            L     get the with of that
             -×   repear "-" that many times
               ∔  and add vertically to the rest of the output

```

# Answer
> 0 votes
# Vyxal, 30 bytes

```
(\|n*\++⁰n--øm,)\|*ð+øm¶+⁰d›-,

```

Try it Online!

```
(              )               # Input times...
 \|n*                          # (iteration number) |s
     \++                       # With a plus appended
        ⁰n--                   # And (input - iteration number) minuses
            øm,                # Palindromed and outputted
                \|*            # Input |s
                   ð+          # Plus a space
                     øm        # Palindromised
                       ¶+      # Plus a newline
                         ⁰d›   # (2(iteration number) + 1)
                            -, # Minuses appended, and outputted

```

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


title: Build ASCII ladders

text:
# Question
Title: Build ASCII ladders
Given an input of two integers *n* and *m*, output an ASCII ladder of length *n* and size *m*.

This is an ASCII ladder of length 3 and size 3:

```
o---o
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
o---o

```

This is an ASCII ladder of length 5 and size 1:

```
o-o
| |
+-+
| |
+-+
| |
+-+
| |
+-+
| |
o-o

```

This is an ASCII ladder of length 2 and size 5:

```
o-----o
|     |
|     |
|     |
|     |
|     |
+-----+
|     |
|     |
|     |
|     |
|     |
o-----o

```

To be specific:

* The length (*n*) represents how many squares the ladder is made up of.
* The size (*m*) represents the width and height of the interior of—that is, not counting the "borders"—each square.
* Each square is made up of the interior area filled with spaces, surrounded by `-`s on the top and bottom, `|`s on the left and right, and `+`s at all four corners.
* Borders between squares merge together, so two lines in a row with `+--...--+` merge into one.
* The corners of the entire ladder are replaced with the character `o`.
* You may optionally output a trailing newline.

The length of the ladder (*n*) will always be ≥ 2, and the size (*m*) will always be ≥ 1.

Input can be taken as a whitespace-/comma-separated string, an array/list/etc., or two function/command line/etc. arguments. The arguments can be taken in whichever order is most convenient / golfiest.

Since this is , the shortest code in bytes wins.

Tip: The examples above can also be used as test cases.

# Answer
> 4 votes
# Pyth, 34 bytes

```
.NjjNm*QTvz*2YjC:M++J"+|o"m"- -"QJ

```

Test suite

Takes arguments newline separated on STDIN.

Uses a helper function, `:`, which builds each type of vertical string from three characters, then replicates as necessary, transposes and joins on newlines.

# Answer
> 11 votes
# Ruby, 71

```
->m,n{h=0;(?o+?+*(n-1)+?o).chars{|c|puts [?|+' '*m+?|]*h,c+?-*m+c;h=m}}

```

**ungolfed in test program**

```
f=->m,n{
  h=0                             #The number of | above the 1st rung is 0
  (?o+?+*(n-1)+?o).chars{|c|      #Make a string of all the rung ends o++...++o and iterate through it
    puts [?|+' '*m+?|]*h,         #draw h vertical segments |  ...  |
      c+?-*m+c                    #and a rung with the correct ends
    h=m                           #The number of | above all rungs except the 1st is m
  }
}

f[gets.to_i,gets.to_i]

```

# Answer
> 9 votes
# CJam, ~~43~~ 42 bytes

I'm not sastified by the score. But I'm not Dennis, right?

```
q~:Z;'-'o{[\Z*1$N]}:X~['-_'+X\'|XZ*]@*1>1$

```

Input is 2 space separated items. Length first

```
2 3
o---o
|   |
|   |
|   |
+---+
|   |
|   |
|   |
o---o

```

Explanation

```
q~:Z;'-'o{[\Z*1$N]}:X~['-_'+X\'|XZ*]@*1>1$
q~                                         e# read input
  :Z;                                      e# Record the size in Z and discard
     '-'o{[\Z*1$N]}:X~                     e# Create the initial line (and final). also creates a shorcut to do this later
           \                               e# Capture two arguments
            Z*                             e# The separator is repeated size times
              1$                           e# Repeat the first argument
                N                          e# Add newline
                                           e# X is a function to create line in a ladder
                      ['-_'+X\'|XZ*]       e# Design the repeating part
                                    @*     e# Repeat the pattern n times
                                      1>   e# Discard the initial
                                        1$ e# Since the final line is same than the initial, we just write it.
                                           e# Implicit printing

```

# Answer
> 7 votes
# JavaScript (ES6), 89

... repeat, repeat, repeat ...

```
(n,m,R=x=>x.repeat(m),b=R(`|${R(' ')}|
`),d=`o${c=R('-')}o
`)=>d+R(b+`+${c}+
`,m=n-1)+b+d

```

**Test**

```
F=(n,m,R=x=>x.repeat(m),b=R(`|${R(' ')}|
`),d=`o${c=R('-')}o
`)=>d+R(b+`+${c}+
`,m=n-1)+b+d

// Less golfed
U=(n,m)=>
{
  var R=x=>x.repeat(m),
      a=R(' '),
      b=R(`|${a}|\n`);
      c=R('-'),
      d=`o${c}o\n`;
  m=n-1;
  return d+R(b+`+${c}+\n`)+b+d
}

function test() {
  var i=I.value.match(/\d+/g)
  if (i) O.textContent=F(+i[0],+i[1])
  console.log(i,I.value)
}

test()
```

```
N,M: <input id=I value="3,5" oninput=test()>
<pre id=O></pre>
```

# Answer
> 6 votes
# C#, 1412 bytes

... My first CodeGolf attempt, Not likely to win but it works so here we go:

```
using System;

namespace Ascii_Ladders
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 0;
            int m = 0;

            Console.Write("Please enter Height: ");
            n = int.Parse(Console.ReadLine());
            Console.Write("Please Enter Width: ");
            m = int.Parse(Console.ReadLine());

            Console.Write("o");
            for (int i = 0; i < m; i++)
            {
                Console.Write("-");
            }
            Console.WriteLine("o");

            for (int k = 0; k < n; k++)
            {
                for (int i = 0; i < m; i++)
                {
                    Console.Write("|");
                    for (int j = 0; j < m; j++)
                    {
                        Console.Write(" ");
                    }
                    Console.WriteLine("|");
                }
                if (k != n - 1)
                {
                    Console.Write("+");
                    for (int i = 0; i < m; i++)
                    {
                        Console.Write("-");
                    }
                    Console.WriteLine("+");
                }
            }

            Console.Write("o");
            for (int i = 0; i < m; i++)
            {
                 Console.Write("-");
            }
            Console.WriteLine("o");

            Console.ReadKey();
        }
    }
}

```

# Answer
> 6 votes
# Julia, 87 bytes

```
f(n,m)=(g(x)=(b=x[1:1])x[2:2]^m*b*"\n";(t=g("o-"))join([g("| ")^m for i=1:n],g("+-"))t)

```

This is a function that accepts two integers and returns a string.

Ungolfed:

```
function f(n::Int, m::Int)
    # Create a function g that takes a string of two characters and
    # constructs a line consisting of the first character, m of the
    # second, and the first again, followed by a newline.
    g(x) = (b = x[1:1]) * x[2:2]^m * b * "\n"

    # Assign t to be the top and bottom lines. Construct an array
    # of length n where each element is a string containing the
    # length-m segment of the interior. Join the array with the
    # ladder rung line. Concatenate all of this and return.
    return (t = g("o-")) * join([g("| ")^m for i = 1:n], g("+-")) * t
end

```

# Answer
> 5 votes
### Pure bash, ~~132 130 128~~ 127 bytes

Yes I could drop 1 more byte replacing last `${p% *}`, but I prefer this:

```
p=printf\ -v;$p a %$1s;$p b %$2s;o="|$a|\n";h=+${a// /-}+\\n v=${a// /$o}
a=${b// /$h$v}${h//+/o};a=${a/+/o};${p% *} "${a/+/o}"

```

Sample:

```
ladders() {
    p=printf\ -v;$p a %$1s;$p b %$2s;o="|$a|\n";h=+${a// /-}+\\n v=${a// /$o}
    a=${b// /$h$v}${h//+/o};a=${a/+/o};${p% *} "${a/+/o}"
}

ladders 3 4
o---o
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
o---o

ladders 2 1
o--o
|  |
|  |
o--o

```

# Answer
> 5 votes
# pb \- 147 bytes

```
^t[B]>>[B]vw[T!0]{b[43]<[X]b[43]>w[B=0]{b[45]>}v[X-1]w[B=0]{b[124]^}v[X]t[T-1]}t[111]b[T]<w[X!0]{b[45]<}b[T]w[Y!0]{w[B!0]{^}b[124]^}b[T]^>>[B]vb[T]

```

This is the kind of challenge that, by rights, pb should be really good at. Drawing simple pictures with characters is exactly what pb was designed for. Alas, it's just a wordy language I guess.

Takes input length first, followed by size. Takes input in the form of byte values, for example: `python -c 'print(chr(5) + chr(7))' | ./pbi.py ladder.pb`

Look, a fun animation!

With comments:

```
^t[B]            # Save length to T
>>[B]v           # Go to X=size+1, Y=0

w[T!0]{          # While T is not 0:
    b[43]            # Write a '+'
    <[X]b[43]        # Write a '+' on the left side as well
    >w[B=0]{b[45]>}  # Travel back to the right '+', writing '-' on the way
    v[X-1]           # Go down by X-1 (== size)
    w[B=0]{b[124]^}  # Travel back up to the '+', writing '|' on the way
    v[X]             # Go down by X (== size + 1, location of next '+')
    t[T-1]           # Decerement T
}

t[111]           # Save 'o' to T (it's used 4 times so putting it
                 # in a variable saves bytes)

b[T]             # Write an 'o' (bottom right)

<w[X!0]{         # While not on X=0:
    b[45]<           # Travel left, writing '-' on the way
}

b[T]             # Write an 'o' (bottom left)

w[Y!0]{          # While not on Y=0:
    w[B!0]{^}        # Skip nonempty spaces
    b[124]           # Write a '|'
    ^                # Travel up
}

b[T]             # Write an 'o' (top left, replaces existing '+')

^>>[B]v          # Go back to where the size is saved and go to X=size+1, Y=0

b[T]             # Write an 'o' (top right, replaces existing '+')

```

# Answer
> 4 votes
## Haskell, ~~100~~ 97 bytes

```
l#s=unlines$t:m++[t]where _:m=[1..l]>>["+"!"-"]++("|"!" "<$u);t="o"!"-";o!i=o++(u>>i)++o;u=[1..s]

```

Usage example:

```
*Main> putStr $ 4 # 3
o---o
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
o---o

```

How it works:

```
l#s=unlines$t:m++[t]         -- concat top line, middle part and end line
                             -- with newlines between every line
  where                      -- where
  _:m=                       -- the middle part is all but the first line of
     [1..l]>>                -- l times
         ["+"!"-"]           --    a plus-dashes-plus line
         ++("|"!" "<$u)      --    followed by s times a bar-spaces-bar line

  t="o"!"-"                  -- very first and last line
  o!i=o++(u>>i)++o           -- helper to build a line
  u=[1..s]

```

Edit: @Christian Irwan found 3 bytes. Thanks!

# Answer
> 3 votes
# PowerShell, 77 ~~80~~

```
param($l,$s)$a='-'*$s
($c="o$a`o")
(($b=,"|$(' '*$s)|"*$s)+"+$a+")*--$l
$b
$c

```

# Answer
> 3 votes
# brainfuck - 334 bytes

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

```

I expected this to be a lot shorter.

This sets up a "string" that looks like `| (...) |` and one that looks like `+----(...)----+`, printing each one as necessary, with some special casing for the `o`s on the top and bottom.

Requires an interpreter that uses 8-bit cells and allows you to go left from cell 0 (be it into negative cells or looping). In my experience, these are the most common default settings.

With comments:

```
,[<+<<<<+>>>>>-]<[[>>]+[<<]>>-] Get m from input; make a copy
                      Turn it into m cells containing 1 with empty cells between

<----[>---<----]      Put 67 at the beginning (again with an empty cell between)

--[>[+>>]<<[<<]>++++++]  Add 43 to every nonempty cell

>[+.>>]               Add 1 to each cell and print it

-[<+>---]<+++++++    Put 92 after the last 45 (no empty cell!)

>>--[<+>++++++]      Put 43 immediately after the 92

->---[<------->+]    Put 234 after 43

++++++++++           And 10 after that

[<++<]             Add two to the 234; 92; the empty spaces; and left of the 111

+++++[>[++++++>>]<<[<<]>-] Add 30 to each 2; the 94; and the 236

>[-]>.-<<----[>>+++<<----] Erase leftmost 32; Print 111; subtract 68 from it

--[>+<--]>---        Put 124 where the 32 was

<<<<++++++++++.,     Print a newline; override the cell with n from input

[                    n times:

  >[>+>+<<-]>[<+>-]    Make a copy of m

  >[                   m times:

    <<<<                 Look for a flag at a specific cell

    [                    If it's there:

      >>>>>>[.>>]          Go to the 43; print it and every second cell after

      <<[<<]>>-            Clear the flag

    ]

    >>>>>[.>>]           Go to the 124; print it and every second cell after

    <<[<<]>              Go back to the copy of m

  -]

  <<<<+>               Plant the flag

-]

>>>>

[-]----[>---<----]>+ Erase the 124; add 68 to 43

.[>]                 Print it; then head to the end

<<<<<[.<<] Go to the last 45; print it; then print every second cell to the left

```

# Answer
> 2 votes
# Perl, 98 bytes

```
($n,$m)=@ARGV;print$h="o"."-"x$m."o\n",((("|".(" "x$m)."|\n")x$m.$h)x$n)=~s{o(-+)o(?=\n.)}{+$1+}gr

```

# Answer
> 2 votes
# Jolf, 36 bytes

Try it here!

```
ρpi,a+2J+2J"o-| "j"o(.+)o
o.+o'+$1+

```

## Explanation

```
ρpi,a+2J+2J"o-| "j"o(.+)o\no.+o'+$1+
 pi              j                   repeat vertically j times
   ,a+2J+2J"o-| "                    a box with dimensions 2+J
ρ                 "o(.+)p\np.+o'     replace with regex
                                +$1+ with the -...-

```

# Answer
> 1 votes
## C, 122 bytes

```
f(int m,int n,char*s){int i=0,w=3+m++;for(;i<w*m*n+w;++i)*s++=i%w>m?10:" |-+-o"[!(i/w%m)*2+!(i%w%m)+!(i/w%(m*n))*2];*s=0;}

```

Try it online.

# Answer
> 1 votes
# Tcl, 187 bytes

```
lassign $argv n w
set c 0
while { $c < [expr {($w * $n) + ($n + 2)}]} {if {[expr {$c % ($n + 1)}] == 0} {puts "o[string repeat "-" $w ]o"} else {puts "|[string repeat " " $w ]|"}
incr c}

```

This code is made to put into a file with arguments input on the command line. provide number of boxes and width in that order.

# Answer
> 1 votes
# PHP, 81bytes

Expects 2 arguments, passed when calling the PHP command directly. The first one is the size and the 2nd one is the number of steps.

```
$R=str_repeat;echo$P="o{$R('-',$W=$argv[1])}o
",$R("|{$R(' ',$W)}|
$P",$argv[2]);

```

May require some improvements.

# Answer
> 1 votes
# Vyxal, 30 bytes

```
(‛+on¬i:⁰-p,⁰(\|:⁰꘍p,))\o:⁰-p,

```

Try it Online!

```
(                     )        # Length times...
 ‛+on¬i                        # If first iteration, o, else +
       :                       # Duplicate
        ⁰-                     # add (size) minuses
          p,                   # Add the o/+ and print
            ⁰(       )         # Size times
              \|               # A pipe character
                :              # Duplicate
                 ⁰꘍            # Add (size) spaces
                   p,          # Add the pipe and print
                       \o:     # Push two os
                          ⁰-   # Add (size) minuses
                            p, # Add the o and print

```

# Answer
> 0 votes
## Python 2, 94 bytes

```
def F(n,m):a,b,c,d='o|+-';r=[a+d*m+a]+([b+' '*m+b]*m+[c+d*m+c])*n;r[-1]=r[0];print'\n'.join(r)

```

'Ungolfed':

```
def F(n,m):
 # 'o---o'
 r = ['o'+'-'*m+'o']
 # ('|   |'*m+'+---+') n times
 r += (['|'+' '*m+'|']*m+['+'+'-'*m+'+'])*n
 # replace last +---+ with o---o
 r[-1] = r[0]
 print '\n'.join(r)

```

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

```
$_='|'.$"x$F[1].'|';push@a,y/| /+-/r,($_)x$F[1]while$F[0]--;$a[0]=y/| /o-/r;say for@a,$a[0]

```

Try it online!

# Answer
> 0 votes
# Pip `-l`, 35 bytes

```
(^YsXbRLaJW'-)XbWR^('|XbRLaJ'+)WR'o

```

Try it online!

### Explanation

```
(^YsXbRLaJW'-)XbWR^('|XbRLaJ'+)WR'o
                                     a is length, b is size, s is space (implicit)
   sXb                               String containing b spaces
      RLa                            List containing a copies of that string
         JW'-                        Join on "-" and wrap the result in "-" as well
  Y                                  Necessary for operator precedence reasons
 ^                                   Split into a list of characters
(            )Xb                     String-repeat each character in the list b times
                                     This list represents the central columns of the ladder

                    '|Xb             String containing b pipe characters
                        RLa          List containing a copies of that string
                           J'+       Join on "+"
                   (          )WR'o  Wrap in "o"
                  ^                  Split into a list of characters
                                     This list represents the outer columns of the ladder

                WR                   Wrap the left list in the right list, vectorizing

```

### Some other versions

I tried a lot of different approaches trying to catch Pyth...

```
[Y'-XbWR'o;@>(sXbWR'|RLbPE'-XbWR'+RL:a)y]  41
Y^(t**b.1*:t**bX--a.1)" --"@yXbWR"|o+"@y   40
Y'|XbRLaJ'+YyWR'o;Z:sXbRLaJW'-RLbPEyAEy    39
t**:b(" |-o-+"<>2)@_@^t.1M$*Y[ttXa-1].1    39
J*Z:sXbRLaJW'-RLbWR:^('|XbRLaJ'+)WR'o      37
Y^$*Y[t**:btXa-1].1" --"@yXbWR"|o+"@y      37

```

I'm particularly fond of the `t**b` ones, which use math to generate the ladder's vertical pattern:

```
        b           Size; e.g. 3
    t               Preset variable for 10
     **:            Set t to t**b (e.g. 1000)
           a        Length; e.g. 3
            -1      2
         tX         String-repeat (the new value of) t 2 times: 10001000
   [          ]     Put t and the above into a list: [1000; 10001000]
               .1   Append 1 to both of them: [10001; 100010001]
$*(              )  Fold on multiplication: 1000200020001

```

The `1000200020001` can then be used to generate the patterns `o|||+|||+|||o` and `- - - -`, which make up the ladder. Unfortunately, I couldn't get this approach to be shorter than the join/wrap approach.

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


title: I Saw That Coming

text:
# Question
Title: I Saw That Coming
Write a program or function that takes in an integer greater than 1 or less than -1. That is, the input won't be 0, 1, or -1.

If the input is `2`, the output should be:

```
|\_/|
|___|

```

If the input is `3`, the output should be:

```
|\_/\_/|
|______|

```

If the input is `4`, the output should be:

```
|\_/\_/\_/|
|_________|

```

The pattern continues in the same exact manner for larger inputs. For example, if the input is `10`, the output should be:

```
|\_/\_/\_/\_/\_/\_/\_/\_/\_/|
|___________________________|

```

If the input is `-2`, the output should be:

```
 ____
|    |
|_/\_|

```

If the input is `-3`, the output should be:

```
 _______
|       |
|_/\_/\_|

```

If the input is `-4`, the output should be:

```
 __________
|          |
|_/\_/\_/\_|

```

The pattern continues in the same exact manner for smaller inputs. For example, if the input is `-10`, the output should be:

```
 ____________________________
|                            |
|_/\_/\_/\_/\_/\_/\_/\_/\_/\_|

```

The output can be printed or returned as a string with an optional trailing newline. The top right "empty" corner of the output for negative inputs may be a space or it may remain empty.

**The shortest code in bytes wins.**

# Answer
> 1 votes
# Pyth, 45 bytes

```
jtW!J<Q0.b+.[YN+h*3t.aQJY.>[d.<"\_/"J\_)J" ||

```

Try it online: Demonstration or Test Suite

### Explanation:

```
jtW!J<Q0.b+.[YN+h*3t.aQJY.>[d.<"\_/"J\_)J" ||  implicit: Q = input number
    J<Q0                                       assign Q < 0 to J
                           [           )       create a list with
                            d                    * the string " "
                             .<"\_/"J            * the string "\_/" rotated to
                                                   the left by J
                                     \_          * the string "_"
                         .>             J      rotate to the right by J
                                         " ||  the string " ||"
        .b                                     binary mapping, N iterates
                                               over list, Y over string:
           .[YN+h*3t.aQJ                         pad Y with N to reach a string
                                                 of length 3*(abs(Q)-1)+1-J
          +             Y                        and append Y
 tW!J                                           remove the first line if Q > 0
j                                               print each on separate line

```

# Answer
> 4 votes
# CJam, ~~56~~ ~~50~~ 49 bytes

```
ri_(z"\_/"*'_@0>{\4>W<_,@*SooNoS}|1$,*]${'|\'|N}/

```

Try it online in the CJam interpreter.

### How it works

```
ri     e# Read an integer from STDIN and push it on the stack.
_(z    e# Push a copy, decrement it and apply absolute value.
       e# For positive n, (n -> n-1) and (-n -> n+1).
"\_/"* e# Repeat the string that many times.
'_     e# Push an underscore.
@0>    e# Check if the original integer is positive.
{      e# If it isn't:
  \    e#   Swap the generated string with the underscore.
  4>W< e#   Discard the string's first 4 and last character.
       e#   This makes the pattern of the bottom row start and end with an
       e#   underscore, truncating it to the correct length in the process.
  _,   e#   Push the length of a copy.
  @*   e#   Repeat the underscore that many times.
  So   e#   Print a space.
  oNo  e#   Print the underscores, then a linefeed.
  S    e#   Push a space.
}|     e#
1$,    e# Retrieve the strings length.
*      e# Repeat the underscore or space that many times.
]$     e# Wrap the two generated strings in an array and sort it.
{      e# For each string:
  '|\  e#   Push a vertical bar and swap the string on top of it.
  '|N  e#   Push a vertical bar and a linefeed.
}/     e#

```

# Answer
> 3 votes
# Pyth, ~~56~~ 54 bytes

I'm golfing Pyth on a phone with the online interpreter. That's a totally great idea.

**Update 2015-10-15:** I rewrote the thing (still on my phone, lol) and saved 2 bytes, of which one could've been done with the original too.

```
J<Q0Ljb"||"jPW!J_WJ[y<>*K+J*3t.aQ"\_/"JKy*K?Jd\_+d*K\_

```

Try it online.

# Answer
> 2 votes
## Minkolang 0.8, 100 bytes

```
"|"nd0`u!vbd3*["_"]"|"25*"|"1g["\_/"]"|"(O).
"[d~g1"_"<.)O(" "D*3R~1"_"*52"|"D*3R1dg2"| "*52"|"]"\/_

```

Just builds up the stack and then prints it all out at once. I'm sure this could be golfed but I've already spent a lot of time on this...

# Answer
> 1 votes
# JavaScript (ES6), ~~111~~ 98 bytes

Optimal technique discovered! Turns out removing all those interpolators from the template strings saves a *lot* of bytes. Perhaps it could still be made shorter, perhaps not. In any case, ES6 template strings (and arrow functions) are awesome. :)

```
x=>(x>0?`|\\_/A|
|___A|`:` ___A_
|   A |
|_/\\A_|`).replace(/(...)A/g,(_,y)=>y.repeat(x>0?x-1:~x))

```

# Answer
> 1 votes
# Vyxal, 67 bytes

```
ȧ=[‹`\_/`*\|:„+p,‹3*\_*\|:„+p,|N3*⇩:\_*ðp,ð*\|:„+p,ȧ`\_/`*ḢṪ\|:„+p,

```

Try it Online!

Oof.

# Answer
> 0 votes
## Python 2.7, 144 bytes

This took more bytes than expected. Here's the code.

```
c=int(input())
p,w,n,u=list('| \n_')
a=abs(c)-1
d=3*a
if c>0:
 s=p+"\\_/"*a+p+n+p+u*d+p
else:
 d=d+1
 s=w+u*d+n+p+w*d+p+n+p+"_/\\"*a+u+p
print s

```

# Answer
> 0 votes
**Java, 272 Bytes**

```
String f(int i) {
String p = i>0?"\\_/":"_/\\_",x = "|"+new String(new char[(i<0?-i:i)-1]).replace("\0",p)+"|",
l=new String(new char[x.length()-2]).replace("\0","_");
return i>0?x+"\n|"+l+"|":" "+l+" \n|"+new String(new char[x.length()-2]).replace("\0"," ")+"|\n"+x;
}

```

# Answer
> 0 votes
# SpecBAS - 167 bytes

```
1 INPUT n: DIM s$="\_/","_/\": LET t$=s$(2-(n>0))*(ABS n-1)+("_"*(n<0)),u$="_"*LEN t$
2 TEXT IIF$(n>0,"|"+t$+"|"#13"|"+u$+"|"," "+u$+#13"|"+" "*LEN t$+"|"#13"|"+t$+"|")

```

`IIF$` is an inline `IF` statement, `#13` is a way of embedding newlines into a string (and doesn't always need a "+" if it's between hardcoded strings).

Since a few releases ago, SpecBAS lets you have multiple assignments to one `LET` statement, which helps save some characters.

# Answer
> 0 votes
# Ruby - 113 bytes

Seems too long. I'll try to golf this down a bit more.

```
n=gets.to_i;p,h=n.abs-1,?|;n>0 ? (puts h+'\\_/'*p+h,h+'___'*p+h):(k=p*3+1;puts' '+?_*k,h+' '*k+h,'|_'+'/\\_'*p+h)

```

# Answer
> 0 votes
# Python 2.7, 118 bytes

```
n=input()*3-3
a=-n-6
s=' %s_\n| %s|\n|%s_|'%(a*'_',a*' ',a/3*'_/\\')
if n>0:s='|%s|\n|%s|'%(n/3*'\\_/',n*'_')
print s

```

Getting down from 120 to 118 was fun!

# Answer
> 0 votes
# C#, 185 bytes

C# struggles with golfing repeating strings.

Completely golfed:

```
string S(int n){int m=n>0?n:-n;return string.Format(n>0?"|{0}\n|{1}|":" {1}\n|{2}|\n|_{0}","|".PadLeft(m).Replace(" ",n>0?@"\_/":@"/\_"),"".PadLeft(m=m*3-(n>0?3:2),'_'),"".PadLeft(m));}

```

Indentation and new lines added for clarity:

```
string S(int n){
    int m=n>0?n:-n;
    return string.Format(n>0?"|{0}\n|{1}|":" {1}\n|{2}|\n|_{0}",
        "|".PadLeft(m).Replace(" ",n>0?@"\_/":@"/\_"),
        "".PadLeft(m=m*3-(n>0?3:2),'_'),
        "".PadLeft(m)
    );
}

```

# Answer
> 0 votes
# Powershell - 200 190 186 168 154

Golfed out the equation (4-(($n-2)*3)) to (3*$n-6) along with some extraneous parens and semicolons.

Found that \`n is the equivalent of `[Environment]::NewLine` and that `$s -f [args]` is the equivalent of `[String]::Format`:

```
$n=$args;if($n-gt0){$s="|{1}|{0}|{2}|";$a=$n;$b=$n*3}else{$n*=-1;$s=" {2}{0}|{3}|{0}|_/{1}\_|";$a=$n-2;$b=$c=3*$n-2};$s-f"`n",("\_/"*$a),("_"*$b),(" "*$c)

```

Explanation retains clarifying parentheses:

```
$n=$args;

// Basically a way of coming up with a string to format and the
// necessary counts of repeated characters
if($n-gt0){
  // Placeholder format
  $s="|{1}|{0}|{2}|{3}";
  // Number of repeated "\_/" instances
  $a=$n;
  // Number of repeated "_" instances
  $b=$n*3
} else {
  $n*=-1;
  $s=" {2}{0}|{3}|{0}|_/{1}\_|";
  $a=($n-2);
  $b=(4+(($n-2)*3));
  // Number of repeated " " instances .. not needed for "positive" saw
  $c=$b;
};
[String]::Format($s,[Environment]::NewLine,"\_/"*$a,"_"*$b," "*$c)

```

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


title: Simple Printing Arrows

text:
# Question
Title: Simple Printing Arrows
For golfing practice, I have been doing the assignments in my girlfriend's Intro to Python class. I found that for this assignment, there were multiple strategies that came very close in character count, and I'm sure people here can find even better ways. Although I am most interested in ways to do this in Python, I would like to know the most golfed this program can get, therefore this is code golf and shortest answer wins.

## The Rules:

The assignment is outlined below. The user should be asked to input twice, although the prompts don't have to say anything, and can be in a different order.

Standard loopholes apply.

---

### Assignment 3: Arrows

Write a program that prompts the user for a number of columns, and them prints the pattern as seen below. You can assume that the user will supply positive numbers. Your program should handle both left and right arrows. Here are a few sample runnings:

```
How many columns? 3
Direction? (l)eft or (r)ight: r
*
 *
  *
 *
*
How many columns? 5
Direction? (l)eft or (r)ight: l
    *
   *
  *
 *
*
 *
  *
   *
    *

```

# Answer
# Pyth, 23 bytes

~~May or may not be valid, based on the answer to this comment. Regardless, I found this neat, and, if it is invalid, the other Pyth answers are also invalid. ;)~~ Well, it's valid, because I apparently missed the blatantly obvious. :/

**EDIT:** I WON!!!! YESSS!!!! First time ever! :D

```
j+_J_Wqz\r.e+*dkb*\*QtJ

```

Live demo.
> 8 votes

# Answer
# Pyth, 27

```
j<tQ_Wqz\l++Jm+*\ d\*Q_PJtJ

```

Try it online

The basic idea here is to build one string that, for say 5, looks like this:

```
*
 *
  *
   *
    *
   *
  *
 *
*
 *
  *
   *
    *

```

And then flip it upside down if we get `l` as our input. Then we take all but the last `input-1` lines of this string and print it out.
> 7 votes

# Answer
# Python 2, ~~81~~ 79 bytes

```
c=input()
r=1
l=0
exec"print' '*(%sabs(c-r))+'*';r+=1;"%("c+~"*input())*(2*c-1)

```

Might still be golfable, but we'll see :)
> 7 votes

# Answer
# Pyth, ~~30~~ ~~28~~ 27 bytes

```
VtyQ+*+*tQJqz\r_WJ.a-hNQd\*

```

Try it online.

Apparently I'm currently tied with FryAmTheEggman with a completely different approach. (I think that one is ingenious.)

### Example

```
$ python pyth.py spa.p
r
3
*
 *
  *
 *
*

$ python pyth.py spa.p
l
5
    *
   *
  *
 *
*
 *
  *
   *
    *

```

### Explanation

```
 tyQ                              (columns * 2) - 1
V                               loop N through range(the above)
        tQ                                columns - 1 (maximum number of spaces)
       *                                multiplied by
           qz\r                           1 if direction == "r" else 0
          J                               also save that 1 or 0 to J
      +                               plus
                  .a-hNQ                    abs(N - columns + 1)
               _WJ                      negate that if direction == "r"
     *                  d           that many spaces
    +                    \*       add the star and print

```
> 4 votes

# Answer
# PowerShell, ~~91~~ ~~85~~ 102 Bytes

```
$c=(Read-Host)-1;if(!$c){"*";exit}(@(0..$c+($c-1)..0),@($c..0+1..$c))[(Read-Host)-eq'l']|%{" "*$_+"*"}

```
* Gets the columns, stores it in `$c`. We subtract one because each column also has an `*` and we're only interested in how many spaces are required.
* If the entered value was a `1`, print `*` and exit - rest of the script doesn't make a difference.+
* The next section first gets the direction and tests whether it's `-eq`ual to `l`, then creates an array based on indexing into an array of dynamically generated arrays based on the value of `$c`. Magic. Essentially, this is how many spaces per line we need.
* For example, for `5 r` this collection would hold `(0,1,2,3,4,3,2,1,0)`.
* Takes the array and pipes it into a Foreach-Object `%` loop, where we output a string of X number of spaces, then the `*`

### Example usage:

```
PS C:\Tools\Scripts\golfing> .\simple-printing-arrows.ps1
6
r
*
 *
  *
   *
    *
     *
    *
   *
  *
 *
*

```

Edit - removed variable `$e` by piping the collection directly
Edit2 - correctly accounts for 1 column, now

+ If it's still mandatory to take input for direction for 1-column arrows (I contend it is not), we can swap the positioning of the `Read-Host` and lose a couple more bytes by re-introducing the `$d` variable, for **106**:

```
$c=(Read-Host)-1;$d=Read-Host;if(!$c){"*";exit}(@(0..$c+($c-1)..0),@($c..0+1..$c))[$d-eq'l']|%{" "*$_+"*"}

```
> 4 votes

# Answer
## TI-BASIC, ~~75~~ ~~65~~ ~~57~~ ~~54~~ ~~50~~ 47 Bytes

Thanks to @ThomasKwa for the correct byte calculation and golfing **10 bytes**.

Tested on my **TI-84+ Silver Edition.**

First TI-BASIC submission, golfing suggestions welcome (I don't know many tricks yet). If name plays a factor in memory shown, this one's was 3 characters instead of 1 (I looked at the byte count on my calculator itself). This program is limited by the `output` function's restrictions (I think to arrows of length 4), but I could probably switch to `text`, which displays graphically if that is too low of a length.

```
Prompt L,Str1
Str1="R
For(I,1,2L-1
Output(I,(1-2Ans)abs(I-L)+AnsL+1,"*
End

```

Note that this also doesn't clear the screen or pause it.

I really feel like the equation I'm using can be golfed more. It also feels so wrong to exclude the ending quotation mark.
> 4 votes

# Answer
# Python 2, ~~111~~ ~~109~~ 104 bytes

Pretty simple solution. I'm sure it can be golfed more. For those who don't know, `~x+n` is the same as `n-1-x`.

```
n=input()
r=range(n)
r+=r[-2::-1]
for i in[r,[~x+n for x in r]]['r'>raw_input()]:print"*".rjust(i+1," ")

```

**Try it online**

**Edit**: This was golfed into the last line:

```
if'r'>d:r=[~x+n for x in r]
for i in r:print"*".rjust(i+1," ")

```
> 2 votes

# Answer
## Perl, 85 bytes

```
($-,$_)=<>;$,=$/;@}=map$"x$_.'*',0..--$-;@}=reverse@}if/l/;print@},map$}[$--$_],1..$-

```

Usage:

```
perl 59874.pl <<< '6
r'

```
> 2 votes

# Answer
# Python 2, 89 bytes

```
c=input()-1
d=raw_input()>'l'
for j in range(2*c+1):print' '*(d*c-(2*d-1)*abs(c-j))+'*'

```

Works almost identically to my Pyth answer, just calculating the correct number of spaces on the fly.
> 2 votes

# Answer
# Matlab, ~~109~~ ~~105~~ 96 bytes

*Thanks to @beaker for saving me 9 bytes*.

```
x=eye(input(''));if(input('','s')<114),x=fliplr(x);end
x=x*10+32;disp(char([x;x(end-1:-1:1,:)]))

```
> 2 votes

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

```
f=[' '*n+'*'for n in range(input())]
if'l'==input():f=f[::-1]
print'\n'.join(f+f[-2::-1])

```

A little more lengthy.

---

# Usage

```
$ python2 test.py
3
"l"
  *
 *
*
 *
  *

```
> 2 votes

# Answer
### PowerShell, 104 102 97 bytes

```
# 97 version:
$o=@(($c=(read-host)-1))[(read-host)-eq'l'];($j=2*$c)..0|%{' '*[Math]::Abs($o++%($j+!$j)-$c)+'*'}

3
r
*
 *
  *
 *
*

# Previous 102 version:
$o=@(($c=(read-host)-1))[(read-host)-eq'l'];(2*$c)..0|%{
' '*[Math]::Abs($o++%(2*($c+(!$c+0)))-$c)+'*'}

```

NB. if you want to run it again, open a new PowerShell, or `rv o` to reset the variable state.

Compared to how terse the others are, this hurts. \[Hurts less at 97 than it did at 122\]. Two parts to it, neither of them very surprising; reads a number of columns, uses an array-index-ternary-operator-substitute to get an offset, and runs through a wave function starting at the offset (and a tweak so it doesn't fall over doing `mod 0`).

(And ouch did I spend ages on that wave function, unable to spot my misunderstanding, and typing all the it's-not-LISP-,honest parens).
> 2 votes

# Answer
# PHP, 156 Bytes

```
<?for($c=1+fgets(STDIN);--$c;$s[-$c]=$t[]=sprintf("%{$c}s","*"));arsort($s);$a=fgetc(STDIN)==r?$s+$t:$t+$s;array_splice($a,count($a)/2,1)?><?=join("
",$a);

```

Creates two arrays, like this:

```
$t = [
    0 => "  *"
    1 => " *"
    2 => "*"
]
$s = [
    -1 => "*"
    -2 => " *"
    -3 => "  *"
]

```

then uses array union `$s+$t` or `$t+$s` to combine them and `array_splice` to remove the element in the middle. Finally output using `<?=join()`
> 2 votes

# Answer
# Vyxal `j`, 14 bytes

```
ƛ×⁰\l=[↲¹]↳;øm

```

Try it Online!

11 if 1/0 is allowed

```
ƛ          ;   # Map to...
 ×             # Asterisk
  ⁰\l=[  ]     # If left...
       ↲¹      # Left justify, then push size to right-just by
          ↳    # Right-justify
            øm # Palindromise

```
> 2 votes

# Answer
# Ruby, 118 bytes

```
2.times{l,d=gets.split;l=l.to_i;a=(d=="r"?(0..l-1):(l-1).downto(0)).to_a;(a+a[0..-2].reverse).each{|x| puts "#{' '*x}*"}}

```

`2.times{` -- twice, of course...

`l,d=gets.split;` -- get the input

`l=l.to_i;` -- change length to an integer

`a=(d=="r"?(0..l-1):(l-1).downto(0)).to_a;` -- create an array from the range of 0 to the length

`(a+a[0..-2].reverse).each{|x| puts "#{' '*x}*"}` -- iterate, turn into the strings to make the arrows

Not exactly the greatest golf ever, but, hey.
> 1 votes

# Answer
# PowerShell, ~~98~~ 94 Bytes

```
$c=(Read-Host)-1;$d=Read-Host;if($c){$c..0+1..$c|%{if($d-eq'r'){$_=$c-$_}' '*$_+'*'}}else{'*'}

```

If I could find a way to put the Read-Host for direction inside the foreach-object loop but only prompt for it once I might be able to save a few bytes.

Edit: 94 bytes. Instead of testing for left, test for right (simplifies the loop).

Original 98 byte:

```
$c=(Read-Host)-1;$d=Read-Host;if($c){0..$c+($c-1)..0|%{if($d-eq'l'){$_=$c-$_}' '*$_+'*'}}else{'*'}

```
> 1 votes

# Answer
# Jelly, 15 bytes

```
=”ro⁹ạŒḄ}⁶ẋp”*Y

```

Try it online!

If we can use any values instead of `l` and `r`, then this **11** byte program works for `1` being to the right and `0` to the left.

If we can use any character rather than `*`, we can reduce the programs to **14** and **10** bytes

## How it works

```
=”ro⁹ạŒḄ}⁶ẋp”*Y - Main link. Takes C on the left and n on the right
 ”r             - "r"
=               - Is C = "r"?
    ⁹           - Yield n
   o            - If C ≠ "r", yield n else 1
        }       - To n:
      ŒḄ        -   Bounce; Yield [1, 2, ..., n, ..., 2, 1]
     ạ          - Absolute difference

                  If C = "r", this yields [0, 1, ..., n-1, ..., 1, 0]
                  If C ≠ "r", this yields [n-1, n-2, ..., 0, ..., n-2, n-1]
                  Call the result B

         ⁶      - Yield a space
          ẋ     - For each element k in B, repeat a space k times
            ”*  - Yield "*"
           p    - Cartesian product; This appends "*" to each element in B
              Y - Join on newlines

```
> 1 votes

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

```
i"1l"i=&-:&*&:?!\:1-:}c0.
~/?:<-$?&::&;!?l<oao"*"
1/  \o" "-

```

2 wasted bytes on the bottom line, how irritating!

Due to how input works in \>\<\>, it's not possible to 'wait' for input - the `i` command checks if an input character is available on STDIN. If there is, it pushes the ASCII value of that character, and pushes -1 if not.

This means that, in order to use this program, the number and direction must already be ready on STDIN, e.g. `3r` for a size 3 arrow pointing to the right. I'm not sure if that disqualifies this entry, let me know your thoughts :o)

I'll also write up a description if anyone wants one.
> 0 votes

# Answer
# PHP, 154 bytes

It looks really repetitive, but it does the desired:

```
$c=$argv[1];$b=l==$argv[2]?1:0;$a=$b?$c:-1;function a($a){echo strrev(str_pad('*',$a))."\n";}while($b?--$a:++$a<$c)a($a+1);while($b?++$a<=$c:1<$a--)a($a);

```

Runs from command line like:

```
php arrow.php 5 l
php arrow.php 5 r

```
> 0 votes

# Answer
# Japt `-R`, 14 bytes

Could save at least 3 bytes with looser I/O requirements.

```
õ@'*ùXÃê zVèÊÑ

```

Try it

## 11 bytes

Takes `0/1` as input for `r/l` and uses `1` instead of `*`

```
oç mÄ ê zVÑ

```

Try it

```
õ@'*ùXÃê zVèÊÑ     :Implicit input of integer U & string V
õ                  :Range [1,U]
 @                 :Map each X
  '*               :  Literal "*"
    ùX             :  Left pad with spaces to length X
      Ã            :End map
       ê           :Palindromise
         z         :Rotate clockwise 90° this many times ...
          Vè       :  Count the occurrences in U of
            Ê      :    "l"
             Ñ     :  Multiply by 2
                   :Implicit output joined with newlines

```

```
oç mÄ ê zVÑ     :Implicit input of integers U & V
o               :Range [0,U)
 ç              :For each, repeat space that many times
   m            :Map
    Ä           :  Append 1
      ê         :Palindromise
        zVÑ     :Rotate clockwise 90° V*2 times
                :Implicit output joined with newlines

```
> 0 votes

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


title: The Banach–Tarski Paradox

text:
# Question
Title: The Banach–Tarski Paradox
The Banach–Tarski paradox states that, given a ball in 3‑dimensional space, you can decompose the ball into a finite number of point subsets. These disjoint sets of points can then be reassembled to produce two copies of the initial ball. You would then, theoretically, have two identical balls.

The process of reassembly consists of only moving the aforementioned point subsets and rotating them, while not changing their spacial shape. This can be done with as few as five disjoint subsets.

Disjoint sets have no common elements by definition. Where `A` and `B` are any two point subsets of the initial ball, the common elements between `A` and `B` is an empty set. This is shown in the following equation.

For the disjoint sets below, the common members form an empty set.

---

# The Challenge

Write a program that can take an input ASCII "ball", and output a duplicate "ball".

---

# Input

Here is an example input ball:

```
      ##########
   ###@%$*.&.%%!###
  ##!$,%&?,?*?.*@!##
 ##&**!,$%$@@?@*@&&##
#@&$?@!%$*%,.?@?.@&@,#
#,..,.$&*?!$$@%%,**&&#
 ##.!?@*.%?!*&$!%&?##
  ##!&?$?&.!,?!&!%##
   ###,@$*&@*,%*###
      ##########

```

Each sphere is outlined by pound signs (`#`) and filled with any of theses characters: `.,?*&$@!%`. Every input will be a 22x10 characters (width by height).

---

# Creating a Duplicate

First, each point inside the ball is given a numbered point based on its index in `.,?*&$@!%`. Here is the above example, once numbered:

```
      ##########
   ###7964151998###
  ##86295323431478##
 ##5448269677374755##
#75637896492137317572#
#21121654386679924455#
 ##1837419384568953##
  ##85363518238589##
   ###2764574294###
      ##########

```

Then, each point is shifted up one (nine goes to one):

```
      ##########
   ###8175262119###
  ##97316434542589##
 ##6559371788485866##
#86748917513248428683#
#32232765497781135566#
 ##2948521495679164##
  ##96474629349691##
   ###3875685315###
      ##########

```

Finally, each new point value is converted back to its corresponding character:

```
      ##########
   ###!.@&,$,..%###
  ##%@?.$*?*&*,&!%##
 ##$&&%?@.@!!*!&!$$##
#!$@*!%.@&.?,*!*,!$!?#
#?,,?,@$&*%@@!..?&&$$#
 ##,%*!&,.*%&$@%.$*##
  ##%$*@*$,%?*%$%.##
   ###?!@&$!&?.&###
      ##########

```

---

# Output

These two balls are then output side-by-side, in this form (separated by four spaces at the equators):

```
      ##########                ##########
   ###@%$*.&.%%!###          ###!.@&,$,..%###
  ##!$,%&?,?*?.*@!##        ##%@?.$*?*&*,&!%##
 ##&**!,$%$@@?@*@&&##      ##$&&%?@.@!!*!&!$$##
#@&$?@!%$*%,.?@?.@&@,#    #!$@*!%.@&.?,*!*,!$!?#
#,..,.$&*?!$$@%%,**&&#    #?,,?,@$&*%@@!..?&&$$#
 ##.!?@*.%?!*&$!%&?##      ##,%*!&,.*%&$@%.$*##
  ##!&?$?&.!,?!&!%##        ##%$*@*$,%?*%$%.##
   ###,@$*&@*,%*###          ###?!@&$!&?.&###
      ##########                ##########

```

---

Note: Shifting the point values, and later characters, is symbolic of the rotations performed to reassemble the point subsets (character groupings).

# Answer
> 7 votes
# Pyth, 21 bytes

```
#++Jw*4d.rJ".,?*&$@!%

```

Try it online: Demonstration

Finally a use-case for `.r`.

### Explanation

```
#++Jw*4d.rJ".,?*&$@!%
#                       infinite loop
   Jw                   read a string from input and store it in J
     *4d                4 spaces
        .rJ".,?*&$@!%   rotate the chars of J using this char order
 ++                     combine the 3 strings (J, spaces, rotated) and print

```

The infinite loop breaks, when there is no more input available.

# Answer
> 6 votes
# Matlab, 120

Matlab is not the greatest language for handling strings. `\n` is always considered as two characters, which is quite annoying, and you cannot just make a matrix out of a line-breaked (line-broken?) string, you have to do it manually. At least I did not have to care about the size/padding as every line has the exact same length.

```
a='.,?*&$@!%.';b=input('');b(b>90)=[];b=reshape(b',22,10)';c=b;for k=1:9;c(b==a(k))=a(k+1);end;disp([b,ones(10,4)*32,c])

```

Example Input:

```
'      ##########      \n   ###@%$*.&.%%!###   \n  ##!$,%&?,?*?.*@!##  \n ##&**!,$%$@@?@*@&&## \n#@&$?@!%$*%,.?@?.@&@,#\n#,..,.$&*?!$$@%%,**&&#\n ##.!?@*.%?!*&$!%&?## \n  ##!&?$?&.!,?!&!%##  \n   ###,@$*&@*,%*###   \n      ##########      '

```

Example output:

```
      ##########                ##########
   ###@%$*.&.%%!###          ###!.@&,$,..%###
  ##!$,%&?,?*?.*@!##        ##%@?.$*?*&*,&!%##
 ##&**!,$%$@@?@*@&&##      ##$&&%?@.@!!*!&!$$##
#@&$?@!%$*%,.?@?.@&@,#    #!$@*!%.@&.?,*!*,!$!?#
#,..,.$&*?!$$@%%,**&&#    #?,,?,@$&*%@@!..?&&$$#
 ##.!?@*.%?!*&$!%&?##      ##,%*!&,.*%&$@%.$*##
  ##!&?$?&.!,?!&!%##        ##%$*@*$,%?*%$%.##
   ###,@$*&@*,%*###          ###?!@&$!&?.&###
      ##########                ##########

```

PS: If I can assume the input this way:

```
['      ##########      ','   ###@%$*.&.%%!###   ','  ##!$,%&?,?*?.*@!##  ',' ##&**!,$%$@@?@*@&&## \n#@&$?@!%$*%,.?@?.@&@,#','#,..,.$&*?!$$@%%,**&&#',' ##.!?@*.%?!*&$!%&?## ','  ##!&?$?&.!,?!&!%##  ','   ###,@$*&@*,%*###   ','      ##########      ']

```

I only need 88 characters:

```
a='.,?*&$@!%.';b=input('');c=b;for k=1:9;c(b==a(k))=a(k+1);end;disp([b,ones(10,4)*32,c])

```

# Answer
> 6 votes
# Ruby, 65

```
10.times{b=gets;puts b.chop.tr(',?*&$@!%.','.,?*&$@!%')+'    '+b}

```

Works great when input is taken from a file instead of stdin:

```
ruby banach.rb < ball.txt

```

On the other hand, if you like typing in balls to stdin manually, and want the output at the end, try this 67-byte version:

```
puts (0..9).map{b=gets;b.chop.tr(',?*&$@!%.','.,?*&$@!%')+'    '+b}

```

# Answer
> 4 votes
## Ruby, 102

```
IO.readlines(?a).map(&:chomp).each{|x|puts"#{x+' '*x.count(' ')+?\s*4+x.tr('.,?*&$@!%',',?*&$@!%.')}"}

```

Basically, its just calling `tr` on the input

# Answer
> 4 votes
# Python 3.5, ~~96~~ ~~89~~ 88 bytes

```
s='.,?*&$@!%.  ##';i=1
while i:i=input();print(i,'  ',''.join(s[s.find(y)+1]for y in i))

```

# Python 3.3, ~~103~~ ~~96~~ 95 bytes

```
s='.,?*&$@!%.  ##'
for i in input().split('\n'):print(i,'  ',''.join(s[s.find(y)+1]for y in i))

```

## Explanation

Python 3.3 and 3.5 are listed separately because the way `input()` handles newlines ***in IDLE*** changed. This happened to save 8 bytes, which is cool.

**Note on execution: use IDLE.** If you use a terminal, then the solution for 3.3 is the same as 3.5, but both interleave the input with the output.

I reversed the symbol string `s` to take advantage of Python's negative indexing. Then for each line in the input, I output it, two spaces, and the line with each symbol replaced with its preceding symbol. The reason I only put two spaces is that I used `,` instead of `+`, which adds a space to the printed output. This (`,' ',`) saved me a byte over `+' '*4+`.

**Thanks to xsot** for saving me ~~7~~ 8 bytes. I changed `s.find` to `s.rfind` to allow me to put the spaces and hashes into `s`, thereby removing the need to do a check for `y in s`. Plus, a space was saved. EDIT: changed back to `s.find` because the presence of `##` now allows me to `+1` without worrying about an index-out-of-bounds error.

# Answer
> 4 votes
# sed (39 bytes)

```
h;y/.,?*&$@!%/,?*&$@!%./;H;x;s/\n/    /

```

# Answer
> 4 votes
# CJam, 28 bytes

```
qN/{_".,?*&$@!%"_(+erS4*\N}%

```

Try it online

Explanation:

```
qN/     Get input and split into lines.
{       Start loop over lines.
  _       Copy, since we need to output original.
  ".,?*&$@!%"
          List of characters, in order.
  _       Copy list of characters.
  (+      Rotate the list by popping first character and appending it.
  er      Transliterate.
  S4*     Create 4 spaces.
  \       Swap spaces between original and transliteration.
  N       Add newline.
}%      End of loop over lines.

```

# Answer
> 3 votes
# Retina, ~~45~~ 39 bytes

```
.+
$0  ; $0
T`.,?*&$@!%;`,?*&$@!%. `;.*

```

To run the code from a single file, use the `-s` flag.

The first stage duplicates each line, separated by `" ; "`, to get

```
      ##########        ;       ##########
   ###@%$*.&.%%!###     ;    ###@%$*.&.%%!###
  ##!$,%&?,?*?.*@!##    ;   ##!$,%&?,?*?.*@!##
 ##&**!,$%$@@?@*@&&##   ;  ##&**!,$%$@@?@*@&&##
#@&$?@!%$*%,.?@?.@&@,#  ; #@&$?@!%$*%,.?@?.@&@,#
#,..,.$&*?!$$@%%,**&&#  ; #,..,.$&*?!$$@%%,**&&#
 ##.!?@*.%?!*&$!%&?##   ;  ##.!?@*.%?!*&$!%&?##
  ##!&?$?&.!,?!&!%##    ;   ##!&?$?&.!,?!&!%##
   ###,@$*&@*,%*###     ;    ###,@$*&@*,%*###
      ##########        ;       ##########

```

Then the second stage only affects characters which are found in matches of `;.*`, i.e. only the second half of each line. Those characters are then transliterated via the following correspondence

```
.,?*&$@!%;
,?*&$@!%.

```

Where the first 9 pairs "increment" the characters in the ball and the last pair turns the semicolon into another space.

# Answer
> 3 votes
# Vyxal `ja`, 22 bytes

```
ƛ:`.,?*&$@!%`:ǓĿð4*$++

```

Try it Online!

`a` flag makes Vyxal take all newline-separated inputs as a list.

```
ƛ                      # Map...
 `.,?*&$@!%`           # The characters
            :ǓĿ        # Transliterate input by chars and chars shifted
               ?ð4*+   # Add four spaces to each line of the original
                    $+ # Add the previous, with chars shifted

```

-1 thanks to Razetime

# Answer
> 2 votes
# Python 2, 77 bytes

```
while 1:r=raw_input();print r,'  ',r.translate(' % #@.$   & ? , '*3+'!*'*104)

```

# Answer
> 2 votes
# Perl, 59 bytes

**56 bytes code plus 3 bytes for `-p` as this needs to be saved to a file.**

```
chop($s=$_);$l=',?*&$@!%';eval"y/.$l/$l./";$_="$s    $_"

```

Example usage:

```
$perl -p ball.pl <<< '      ##########
>    ###@%$*.&.%%!###
>   ##!$,%&?,?*?.*@!##
>  ##&**!,$%$@@?@*@&&##
> #@&$?@!%$*%,.?@?.@&@,#
> #,..,.$&*?!$$@%%,**&&#
>  ##.!?@*.%?!*&$!%&?##
>   ##!&?$?&.!,?!&!%##
>    ###,@$*&@*,%*###
>       ##########
> '
      ##########                ##########
   ###@%$*.&.%%!###          ###!.@&,$,..%###
  ##!$,%&?,?*?.*@!##        ##%@?.$*?*&*,&!%##
 ##&**!,$%$@@?@*@&&##      ##$&&%?@.@!!*!&!$$##
#@&$?@!%$*%,.?@?.@&@,#    #!$@*!%.@&.?,*!*,!$!?#
#,..,.$&*?!$$@%%,**&&#    #?,,?,@$&*%@@!..?&&$$#
 ##.!?@*.%?!*&$!%&?##      ##,%*!&,.*%&$@%.$*##
  ##!&?$?&.!,?!&!%##        ##%$*@*$,%?*%$%.##
   ###,@$*&@*,%*###          ###?!@&$!&?.&###
      ##########                ##########

```

# Answer
> 1 votes
# 05AB1E (legacy), 21 bytes

```
|ʒD4ú".,?*&$@!%"DÀ‡«,

```

Uses the legacy version of 05AB1E, because it was possible to use the filter `ʒ` with implicit `y` as a foreach to print, whereas with the new version the actual for-each loop `v` with explicit `y` should be used, which is 1 byte longer.

Try it online.

**Explanation:**

```
|                      # Get the input-lines as list
 ʒ                     # For-each over the lines to print using the filter-builtin:
  D                    #  Duplicate the current line
   4ú                  #  Prepend 4 spaces to this copy
     ".,?*&$@!%"       #  Push this string
                DÀ     #  Duplicate it, and rotate its copy once towards the left
                  ‡    #  Transliterate the space-prepended string with these two strings
                   «   #  Append it to the original duplicated line
                    ,  #  And print with trailing newlines

```

---

Here a version that also works in the new version of 05AB1E (credit to *@Grimy*):

# 05AB1E, 21 bytes

```
TFD?4ú".,?*&$@!%"DÀ‡,

```

Try it online.

**Explanation:**

```
TF                     # Loop 10 times:
  D                    #  Duplicate the (implicit) input-line
   ?                   #  Pop and print the copy without trailing newline
    4ú                 #  Prepend 4 spaces to the input-line
      ".,?*&$@!%"      #  Push this string
                 DÀ    #  Duplicate it, and rotate its copy once towards the left
                   ‡   #  Transliterate the space-prepended string with these two strings
                    ,  #  And print with trailing newlines

```

# Answer
> 0 votes
# Stax, 16 bytes

```
âìè╩Jù╠╕╜☻u$1∞;ⁿ

```

Run and debug it

just a simple ring translation. Takes the input directly through STDIN.

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


title: Golf this Thumb-2 Constant!

text:
# Question
Title: Golf this Thumb-2 Constant!
One thing that is constantly frustrating when golfing ARM Thumb-2 code is generating constants.

Since Thumb only has 16-bit and 32-bit instructions, it is impossible to encode every immediate 32-bit value into a single instruction.

Additionally, since it is a variable length instruction set, some methods of generating a constant are smaller than others.

**I hate that.** Write a program or function that does this work for me so I don't have to think about it. (\*shudder\*)

There are four different variants of the `mov` instruction as well as a pseudo instruction which loads from a constant pool.

They are either 2 bytes, 4 bytes, or 6 bytes long.

These are the following:

1. `movs`: **2 bytes**. Generates any 8-bit **unsigned** value from `0x00` to `0xFF` in the low 8 bits, setting the other bits to `0`.
2. `mov`: **4 bytes**. Generates any 8-bit unsigned value **bitwise rotated any number of bits,** filling the rest with `0` bits.
3. `mvn`: **4 bytes**. The same as `mov`, but generates the **one's complement** of that rotated 8-bit value, filling the rest with `1` bits.
4. `movw`: **4 bytes**. Can set the low 16 bits to any 16-bit **unsigned** value from `0x0000`-`0xFFFF`, and the high 16 bits to 0.
5. `ldr`: **6 bytes**. The last resort. Can generate **any** 32-bit value, but is slow and larger than the other options.

†: Note that this is dramatically oversimplified, the real encoding would make this challenge quite frustrating.

The input will be a 32-bit integer, either by string (base 10 signed/unsigned or hex), `stdin`, or value.

**Every value from `0x00000000` to `0xFFFFFFFF` must be handled.** It is a critical part of the challenge. Watch out for signed shift issues.

However, you can safely assume all inputs will fit into 32 bits, since ARM is a 32-bit architecture.

The output will be the **shortest** instruction to encode this constant.

The output format is whatever is easiest, as long as the values are distinct and you indicate which instruction corresponds to each output.

There will be a few cases where multiple answers are correct. You may either output one of the correct answers, or all of them. However, you must only display the **shortest** answers. So, for example, you must only output `ldr` when none of the other instructions can generate it.

Test cases (values are in hex to show the bit patterns)

```
0x00000000 -> movs
0x00000013 -> movs
0x000000ff -> movs
0x12345678 -> ldr
0x02300000 -> mov
0xffffffff -> mvn
0x00ffffff -> mvn
0x00001200 -> mov or movw
0x11800000 -> mov
0x80000000 -> mov
0x00000100 -> mov or movw
0x0000f00d -> movw
0xfff3dfff -> mvn
0x03dc0000 -> mov
0xf000000f -> mov
0x00003dc0 -> mov or movw
0x0021f300 -> ldr
0x00100010 -> ldr
0xffff0000 -> ldr

```

Standard loopholes apply.

Note that `as` and `objdump` will not help; they will use the real encoding which is wrong.

Being , the smallest answer in bytes per language wins.

# Answer
# JavaScript (ES6), 57 bytes

Returns **false** for "mov", **true** for "movs", **2** for "ldr", **3** for "mvn" or **4** for "movw".

```
f=(n,r)=>n>>8?~n>>8?r>31?n>>16?2:4:f(n>>>31|n*2,-~r):3:!r

```

Try it online!

### Commented

```
f = (              // f is a recursive function taking:
  n,               //   n = input
  r                //   r = rotation counter, initially undefined
) =>               //
  n >> 8 ?         // if some of the upper 24 bits of n are not 0's:
    ~n >> 8 ?      //   if some of the upper 24 bits of n are not 1's:
      r > 31 ?     //     if the input was rotated 32 times (which means
                   //     that we've tried all possible rotations and we
                   //     are back to the original value):
        n >> 16 ?  //       if some of the upper 16 bits of n are not 0's:
          2        //         return 2 for "ldr"
        :          //       else:
          4        //         return 4 for "movw"
      :            //     else:
        f(         //       do a recursive call:
          n >>> 31 //         rotate n by 1 position to the left
          | n * 2, //
          -~r      //         increment r
        )          //       end of recursive call
    :              //   else:
      3            //     return 3 for "mvn"
  :                // else:
    !r             //   return true for "movs" if r is zero'ish
                   //   or false for "mov" if r is greater than 0

```
> 8 votes

# Answer
# Jelly, 29 bytes

```
+Ø%BḊ¹¬ƭṙJ$Ḅ<⁹Ẹ
⁹²>;Ç;Ç;<⁹$TṀ

```

Try it online!

Returns 0, 1, 2, 3, 4 respectively for `ldr`, `movw`, `mov`, `mvn` and `movs`. Probably could be improved.
> 4 votes

# Answer
# C (gcc), ~~105~~ \\$\cdots\\$~~73~~ 72 bytes

Saved 15 bytes thanks to EasyasPi!!!
Saved ~~3~~ 4 bytes thanks to ceilingcat!!!

```
i;z;f(n){for(i=0;z=n>>8,i++<32&&z&&~z;)n=n*2|n<0;i=z?~z?z>>8?4:3:2:i>1;}

```

Try it online!

Returns \\$0,1,2,3,4\\$ for `movs`, `mov`, `mvn`, `movw`, `ldr`.

### Explanation (before some golfs)

```
i;f(n){                         // function taking a 32 bit parameter n
       for(i=0;i++<32           // loop for maximum of 32 times
               &&n>>8           // while there's set bits in the 24 msb
               &&~n>>8;)        // and in the 24 msb of n's 1s compliment
           n=n*2|n<0;           // rotate n 1 bit to the left
       i=                       // return:
         n>>8?~n>>8?            // if these are still truth values then we
                                // must have rotated n 32 times
                    n>>16?      // does the original n have set bits in the
                                // 16 msb?
                          4:    // ldr if it does
                          3:    // movw if it doesn't.
                                // the ones below are because we stopped
                                // looping when we found no/all 1 bits in
                                // the 24 msb
                          2:    // mvn if all 24 msb are set in the
                                // current of a rotation of n
                          i>1;  // mov if there's no set bits in the 24 msb
                                // of the current rotation of n
                                // movs if there's no set bit in the 24 msb
}                               // of n at the start.

```
> 2 votes

# Answer
# MMIX, 96 bytes (24 instrs)

Returns 8 for `movs`, else is a bitfield (1 for `mov`, 2 for `mvn`, 4 for `movw`). 0 is thus for `ldr`.

I'm fairly certain that this can never return 6 or 7.

```
00000000: 3fff0008 4aff0003 e3010008 f8020000  ?”¡®J”¡¤ẉ¢¡®ẏ£¡¡
00000010: 3fffff08 7301ff04 cf040000 e3050000  ?””®s¢”¥Ẇ¥¡¡ẉ¦¡¡
00000020: fe020004 f2030003 f6040002 28010301  “£¡¥ṗ¤¡¤ẇ¥¡£(¢¤¢
00000030: 3b030020 e3020000 e3040020 27040401  ;¤¡ ẉ£¡¡ẉ¥¡ '¥¥¢
00000040: 3fff0338 6302ff01 3bff031f 3f030301  ?”¤8c£”¢;”¤þ?¤¤¢
00000050: c00303ff 5b04fffa c0010102 f8020000  Ċ¤¤”[¥”«Ċ¢¢£ẏ£¡¡

```

```
gt2     SRU   $255,$0,8
        BNZ   $255,0F               // if(!(n >> 8))
        SET   $1,8
        POP   2,0                   // return 8; (movs)
0H      SRU   $255,$255,8
        ZSZ   $1,$255,4             // rv = !(n >> 16) << 2
        NXOR  $4,$0,0               // y = ~n
        SET   $5,0
        GET   $2,rJ
        PUSHJ $3,0F                 // q = f(y, 0)
        PUT   rJ,$2
        2ADDU $1,$3,$1              // rv = rv + q * 2
0H      SLU   $3,$0,32              // f(n, rv): y = n << 32
        SET   $2,0                  // q = 0
        SET   $4,32                 // i = 32
0H      SUBU  $4,$4,1               // loop: i--
        SRU   $255,$3,56
        CSZ   $2,$255,1             // if(!(y >> 56)) q = 1
        SLU   $255,$3,31
        SRU   $3,$3,1
        OR    $3,$3,$255            // y = (y >> 1) | (y << 31)
        PBNZ  $4,0B                 // if(i) goto loop
        OR    $1,$1,$2              // rv |= q
        POP   2,0                   // return(rv)

```

To also support the weird versions of `mov` and `movn`, replace `SET $2,0` (`E3020000`, `ṭ£¡¡`) with the following, at a cost of 40 bytes/10 instructions:

```
    SRU  $255,$0,16     // ?”¡Ñ t = n >> 16
    XOR  $255,$255,$0   // İ””¡ t ^= n
    SLU  $255,$255,48   // ;””0 t <<= 48
    ZSZ  $4,$255,1      // s¥”¢ i = !t (test for top-equals-bottom)
    SLU  $255,$3,24     // ;”¤ð t = y << 24
    ZSZ  $1,$255,$4     // r¢”¥ q = t? 0 : i (test for low-bytes-zero)
    XOR  $255,$255,$3   // İ””¤ t ^= y
    SRU  $255,$255,56   // ?””8 t >>= 56
    CSZ  $1,$255,$4     // b¢”¥ if(!t) q = i (test for all-bytes-equal)
    SRU  $255,$3,56     // ?”¤8 t = y >> 56
    CSZ  $1,$255,$4     // b¢”¥ if(!t) q = i (test for high-bytes-zero)

```
> 2 votes

# Answer
# Charcoal, 56 bytes

```
≔⍘×⊕Ｘ²¦³²Ｎ²θ¿‹Ｌθ⁴¹movs¿‹Ｌθ⁴⁹movw¿№θ×0²⁴mov¿№θ×1²⁴mvn¦ldr

```

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

```
≔⍘×⊕Ｘ²¦³²Ｎ²θ

```

Input the integer, multiply it by 2³²+1, and convert to binary.

```
¿‹Ｌθ⁴¹movs

```

If the length is less than 41, then the original number had 8 bits or fewer, so a `movs` instruction will work.

```
¿‹Ｌθ⁴⁹movw

```

Otherwise if the length is less than 49, then the original number had 16 bits or fewer, so a `movw` instruction will work.

```
¿№θ×0²⁴mov

```

Otherwise if the binary contains a string of 24 `0`s, then they can be rotated to the beginning of the original number, so a `mov` instruction will work.

```
¿№θ×1²⁴mvn

```

Otherwise if the binary contains a string of 24 `1`s, then they can be rotated to the beginning of the original number, so a `mvn` instruction will work.

```
¦ldr

```

Otherwise give up and use `ldr`.

This challenge reminds me of the difficulty of loading immediate values using original ARM instructions, so I wrote a 32-byte program that identifies values that can be loaded into a register via `mov` or `mvn`:

```
≔⍘×⊕Ｘ²¦³²Ｎ⁴θ¿№θ×0¹²mov¿№θ×3¹²mvn

```

Try it online! Link is to verbose version of code. Outputs `mov` if the value can be used directly as an immediate operand, or `mvn` if you can at least load it into a register.
> 1 votes

# Answer
# Z80, ~~59~~ 55 bytes

Input value in `dehl`. Output in `c`, 0, 1, 2, 3, 4 for `ldr`, `mvn`, `mov`, `movw`, `movs` respectively.
Trashes `b` and `a`. This is indeed rather silly.

```
0E 03 7C B7 20 01 0C 7B
B2 C8 AF 4F 3C F5 7A 2F
57 7B 2F 5F 7C 2F 67 7D
2F 6F 06 20 7A 17 CB 15
CB 14 CB 13 CB 12 7C B3
B2 20 03 F1 4F F5 10 EC
F1 D8 37 3C F5 18 D7

```

```
foo:
  ld c,3                // 0E 03    we might want to return 3
  ld a,h                // 7C       is h zero?
  or a                  // B7       the test
  jr nz,hnz             // 20 01    if so,
  inc c                 // 0C       increment c
hnz:                    //          in any case,
  ld a,e                // 7B       load e
  or d                  // B2       or in d
  ret z                 // C8       if both zero return
  xor a                 // AF       clear a and carry
  ld c,a                // 4F       and c
  inc a                 // 3C       actually, set a to 1
  push af               // F5       store a and carry
subr:
  ld a,d                // 7A       complement dehl
  cpl                   // 2F
  ld d,a                // 57
  ld a,e                // 7B
  cpl                   // 2F
  ld e,a                // 5F
  ld a,h                // 7C
  cpl                   // 2F
  ld h,a                // 67
  ld a,l                // 7D
  cpl                   // 2F
  ld l,a                // 6F
  ld b,32               // 06 20    do the following 32 times:
loop:
  ld a,d                // 7A       load D into A
  rla                   // 17       move top bit of A into C flag
  rl l                  // CB 15    do the rest of
  rl h                  // CB 14    the left rotation
  rl e                  // CB 13
  rl d                  // CB 12
  ld a,h                // 7C       or together
  or e                  // B3       the top three
  or d                  // B2       bytes;
  jr nz,nofit           // 20 03    if all zero,
  pop af                // F1       reload old af
  ld c,a                // 4F       load c
  push af               // F5       push it back
nofit:                  //          in any case
  djnz loop             // 10 EC    end loop
  pop af                // F1       reload old af
  ret c                 // D8       return if second time
  scf                   // 37       marker for second time
  inc a                 // 3C       and increment a
  push af               // F5       push those back
  jr subr               // 18 D7    and try again with complement

```

Bonus: another version that also checks for the weird constants, in 75 bytes. (Inserted region between »German guillemets«, changed byte in \*stars\*).

```
0E 03 7C B7 20 01 0C 7B
B2 C8 AF 4F 3C F5 7A 2F
57 7B 2F 5F 7C 2F 67 7D
2F 6F»AB 20 11 7C AA 20
0D AC 28 07 AD 28 04 7D
B7 20 03 F1 4F F5«06 20
7A 17 CB 15 CB 14 CB 13
CB 12 7C B3 B2 20 03 F1
4F F5 10 EC F1 D8 37 3C
F5 18*C3*

```

```
foo:
  ld c,3                // 0E 03    we might want to return 3
  ld a,h                // 7C       is h zero?
  or a                  // B7       the test
  jr nz,hnz             // 20 01    if so,
  inc c                 // 0C       increment c
hnz:                    //          in any case,
  ld a,e                // 7B       load e
  or d                  // B2       or in d
  ret z                 // C8       if both zero return
  xor a                 // AF       clear a and carry
  ld c,a                // 4F       and c
  inc a                 // 3C       actually, set a to 1
  push af               // F5       store a and carry
subr:
  ld a,d                // 7A       complement dehl
  cpl                   // 2F
  ld d,a                // 57
  ld a,e                // 7B
  cpl                   // 2F
  ld e,a                // 5F
  ld a,h                // 7C
  cpl                   // 2F
  ld h,a                // 67
  ld a,l                // 7D
  cpl                   // 2F
  ld l,a                // 6F
// begin insert
  xor e                 // AB       check for e=l
  jr nz,stlp            // 20 11    if not, skip to loop
  ld a,h                // 7C
  xor d                 // AA       check for d=h
  jr nz,stlp            // 20 0D    if not, skip to loop
  xor h                 // AC       check for h=0 (a 0 already)
  jr z,succ             // 28 07    if so, skip to succ
  xor l                 // AD       check for h=l
  jr z,succ             // 28 04    if so, skip to succ
  ld a,l                // 7D
  or a                  // B7       check for l=0
  jr nz,stlp            // 20 03    if not, skip to loop
succ:
  pop af                // F1       reload old af
  ld c,a                // 4F       load c
  push af               // F5       push it back
stlp:
// end insert
  ld b,32               // 06 20    do the following 32 times:
loop:
  ld a,d                // 7A       load D into A
  rla                   // 17       move top bit of A into C flag
  rl l                  // CB 15    do the rest of
  rl h                  // CB 14    the left rotation
  rl e                  // CB 13
  rl d                  // CB 12
  ld a,h                // 7C       or together
  or e                  // B3       the top three
  or d                  // B2       bytes;
  jr nz,nofit           // 20 03    if all zero,
  pop af                // F1       reload old af
  ld c,a                // 4F       load c
  push af               // F5       push it back
nofit:                  //          in any case
  djnz loop             // 10 EC    end loop
  pop af                // F1       reload old af
  ret c                 // D8       return if second time
  scf                   // 37       marker for second time
  inc a                 // 3C       and increment a
  push af               // F5       push those back
  jr subr               // 18 C3    and try again with complement

```
> 1 votes

---
Tags: code-golf, number, decision-problem, integer, bitwise
---