title: Find the BCD difference of a number

text:
# Question
Title: Find the BCD difference of a number
# BCD difference

Given an integer n, convert it to BCD (binary-coded decimal) by replacing each decimal digit with its 4-digit binary representation

```
 234 -> 0 0 1 0 0 0 1 1 0 1 0 0

```

Then rotate the list of binary digits in order to find the largest and smallest numbers, representable by this list without other rearrangements.

```
max: 1 1 0 1 0 0 0 0 1 0 0 0  (the entire list rotated left 6 times)
min: 0 0 0 0 1 0 0 0 1 1 0 1 (the entire list rotated right 2 times)

```

Convert these numbers back to decimal, treating the list of bits as regular binary and subtract the smallest from the largest:

```
1 1 0 1 0 0 0 0 1 0 0 0 -> 3336
0 0 0 0 1 0 0 0 1 1 0 1 -> 141

3336 - 141 -> 3195

```

The output is the difference of the largest and smallest numbers found.

Test cases:

```
234 -> 3195
1234 -> 52155
12 -> 135
975831 -> 14996295
4390742 -> 235954919
9752348061 -> 1002931578825

```

# Answer
> 7 votes
## Wolfram Language (Mathematica), ~~89~~ 88 bytes

*Thanks to Jenny\_mathy for saving 1 byte.*

```
i=IntegerDigits;Max@#-Min@#&[#~FromDigits~2&/@NestList[RotateRight,Join@@i[i@#,2,4],#]]&

```

Try it online!

This is terribly inefficient, because it generates **n** rotations of the BCD of **n**, which is way more than we need. We can make this is a bit more efficient by saving the result of the `Join@@` in `k` and replacing the `#` at the end with `Length@k`. That lets us generate a scatterplot quite easily:

I'm really intrigued by the contrast of local structure and overall chaos.

# Answer
> 6 votes
# Jelly, 13 bytes

```
Dd4d2FṙJ$ḄṢIS

```

Try it online!

### How it works

```
Dd4d2FṙJ$ḄṢIS  Main link. Argument: n

D              Decimal; convert n to base 10 (digit array).
 d4            Divmod 4; map each digit d to [d/4, d%4].
   d2          Divmod 2; map each [d/4, d%4] to [[d/8, d/4%2], [d%4/2, d%2]].
     F         Flatten the resulting 3D binary array.
      ṙJ$      Take all possible rotations.
         Ḅ     Convert each rotation from binary to integer.
          Ṣ    Sort the resulting integer array.
           I   Take the forward differences.
            S  Take the sum.

```

# Answer
> 4 votes
# Python 3, ~~115~~ 108 bytes

*thanks to Jonathan Frech for -7 bytes*

```
k=''.join(f'{int(i):04b}'for i in input())
v=[int(k[i:]+k[:i],2)for i in range(len(k))]
print(max(v)-min(v))

```

Try it online!

# Answer
> 4 votes
# PowerShell, 153 bytes

```
$b=[char[]]-join([char[]]"$args"|%{[convert]::toString(+"$_",2).PadLeft(4,'0')})
($c=$b|%{$x,$y=$b;[convert]::ToInt64(-join($b=$y+$x),2)}|sort)[-1]-$c[0]

```

Try it online!

Stupid lengthy .NET calls to convert to/from binary really bloats the length here. ;-)

We take input as `$args`, wrap it in a string, then cast it as a `char`-array. We loop over each digit, `convert`ing the digit `toString` in base `2` (i.e., turning the digit into a binary number), then `.padLeft` to make it a four-digit binary number. That resulting array of strings is then `-join`ed into a single string and re-cast as a `char`-array before being saved into `$b`.

Next, we loop over `$b`, which just makes sure we loop enough times to account for every rotation. Each iteration, we peel off the first character into `$x` and the remaining characters into `$y` using multiple assignment. Then, we merge them back together into `$b=$y+$x` to move the first element to the end, i.e., effectively rotating the array by one. That's `-join`ed into a string, which is used as the input to the `convert` call to turn the string from binary base `2` into an `Int64`. We then `sort` all of those resultant numbers and store them into `$c`. Finally, we take the biggest `[-1]` and subtract the smallest `[0]`. That's left on the pipeline and output is implicit.

# Answer
> 4 votes
# Ohm v2, 15 bytes

```
€b4Ü. 0\;Jγó↕]a

```

Try it online!

Explanation:

```
€b4Ü. 0\;Jγó↕]a  Main wire, arguments: a (integer)

€       ;        Map the following over each digit of a...
 b                 Convert to binary
  4Ü               Right-justify w/ spaces to length 4
    . 0\           Replace all spaces with zeroes
         J       Join together binary digits
          γó     Get all possible rotations and convert back to decimal
            ↕    Find the minimum *and* maximum rotation
             ]a  Flatten onto stack and get the absolute difference

```

# Answer
> 4 votes
## JavaScript (ES6), ~~118~~ ~~100~~ 99 bytes

```
f=
n=>(g=m=>Math[m](...[...s=(`0x1`+n-0).toString(2)].map(_=>`0b${s=0+s.slice(2)+s[1]}`)))`max`-g`min`
```

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

Edit: Saved 11 bytes thanks to @RickHitchcock. Saved 1 byte thanks to @ETHproductions. Explanation: The `0x1` prefix causes the input to get reparsed as a hexadecimal number, whose binary is the same as the BCD of the original number with a 1 prefix (I think this is golfier than any other way of padding to a multiple of 4 digits). Excluding the prefix, which is changed from 1 to 0, the resulting string is then rotated at each possible position and converted from binary back to decimal. Finally the maximum and minimum are subtracted.

# Answer
> 3 votes
# Python 2, ~~115~~ 113 bytes

* Saved some bytes thanks to ovs.
* Saved two bytes thanks to Mr. Xcoder.

```
b="".join(format(int(n),"04b")for n in`input()`)
b=[int(b[s:]+b[:s],2)for s in range(len(b))]
print max(b)-min(b)

```

Try it online!

# Answer
> 3 votes
# Pyth, 29 bytes

```
Ksm.[\04.Bsd`Q-eJSmi.<Kd2lKhJ

```

Try it here! or Check out the test suite.

# Answer
> 3 votes
# Husk, 18 bytes

```
§-▼▲mḋUMṙNṁȯtḋ+16d

```

Try it online!

There should be a shorter way to convert a digit into its 4-bit binary representation...

### Explanation

```
§-▼▲mḋUMṙNṁȯtḋ+16d
                 d    Get the list of digits of the input
          ṁȯ          For each digit...
              +16      add 16
             ḋ         convert to binary
            t          drop the first digit
       MṙN            Rotate the list by all possible (infinite) numbers
      U               Get all rotations before the first duplicated one
    mḋ                Convert each rotation from binary to int
§-▼▲                  Subtract the minimum from the maximum value

```

# Answer
> 3 votes
# APL (Dyalog), ~~37~~ 34 bytes

```
{(⌈/-⌊/)2⊥¨(⍳⍵)∘.⌽⊂,↑(4⍴2)∘⊤¨⍎¨⍕⍵}

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog), 31 bytes

Full program body. Prompts for number from STDIN. Prints result to STDOUT.

```
(⌈/-⌊/)2⊥¨(⍳≢b)⌽¨⊂b←,⍉(4/2)⊤⍎¨⍞

```

Try it online!

prompt for line of text from STDIN

`⍎¨` execute (evaluate) each (character)

`(``)⊤` encode (anti-base) in the following number system:

`4/2` four binary bits

transpose

`,` ravel (flatten)

`b←` store in `b` (for *b*inary)

enclose (so that we will use this entire list for each rotation)

`(``)⌽¨` rotate (left) by each of the following amounts:

`≢b` length of `b`

**i**ndices of that

`2⊥¨` decode each from base-2.

`(``)` apply the following tacit function to that

`⌈/` the max(-reduction)

`-` minus

`⌊/` the min(-reduction)

# Answer
> 2 votes
# Jelly, 21 bytes

```
DB0;$4¡€ṫ€-3FṙJ$ḄµṀ_Ṃ

```

Try it online!

# Answer
> 2 votes
# Mathematica, ~~110~~ 99 bytes

```
Max@#-Min@#&[#~FromDigits~2&/@Partition[s=Join@@Tuples[{0,1},4][[IntegerDigits@#+1]],Tr[1^s],1,1]]&

```

Try it online!

# Answer
> 2 votes
# Retina, ~~96~~ 89 bytes

```
.
@@@$&
@(?=@@[89]|@[4-7]|[2367])
_
T`E`@
\d
_
.
$&$'$`¶
O`
_
@_
+`_@
@__
s`(_+).*\W\1

_

```

Try it online! Somewhat slow, so link only includes a small test case. Edit: Saved 7 bytes thanks to @MartinEnder. Explanation:

```
.
@@@$&

```

Prefix three `@`s to each digit. (These represent the `0`s of the BCD, but are golfier.)

```
@(?=@@[89]|@[4-7]|[2367])
_

```

Change the `@`s to `_`s (representing the `1`s of the BCD) where appropriate.

```
T`E`@
\d
_

```

Fix up the last digit of the BCD.

```
.
$&$'$`¶

```

Generate all of the rotations.

```
O`

```

Sort them into ascending order.

```
_
@_
+`_@
@__

```

Convert them to unary.

```
s`(_+).*\W\1

_

```

Subtract the first from the last number, ignoring intermediate numbers, and convert to decimal.

# Answer
> 2 votes
# Ruby, <sub>~~96~~</sub> 91 bytes

```
->n{r=""
n.digits.map{|d|r="%04b"%d+r}
s=r.chars.map{(r=r[1..-1]+r[0]).to_i 2}
s.max-s.min}

```

Try it online!

* Saved 5 bytes thanks to displayname

# Answer
> 2 votes
# PHP, ~~156~~ 153 bytes

```
<?foreach(str_split($argv[1])as$n)$s.=str_pad(decbin($n),4,0,0);for(;$i<$a=strlen($s);)$r[]=bindec(substr($s,$i).substr($s,0,$i++));echo max($r)-min($r);

```

Try it online!

# Answer
> 2 votes
# Python 3, 141 bytes

```
def f(a):a=''.join([format(int(i),'#010b')[-4:]for i in str(a)]);b=[int(''.join(a[-i:]+a[:-i]),2)for i in range(len(a))];return max(b)-min(b)

```

Try it online

# Answer
> 2 votes
# Haskell, 130 bytes

```
r=foldl1
f x=max#x-min#x
f#x|s<-show x=r((+).(2*)).r f.take(sum$4<$s).iterate(drop<>take$1)$do d<-s;mapM(pure[0,1])[1..4]!!read[d]

```

Try it online!

## Explanation / Ungolfed

Since we're going to use `foldl1((+).(2*))` to convert from binary to decimal, we might as well not use `maximum` and `minimum` but rather `foldl1 max` (or same with `min` respectively) and use a short `r = foldr1`.

Now, let us define an operator `f#x` which converts `x` to BCD, generates all rotations, reduce these using `f` and convert it to decimal:

```
f # xs
  | s <- show xs
  = foldr1 ((+).(2*))                             -- convert from binary to decimal
  . foldr1 f                                      -- reduce by either max or min
  . take (4 * length s)                           -- only keep 4*length s (ie. all "distinct" rotations)
  . iterate (drop<>take $ 1)                      -- generate infinite list of rotations
  $ do d<-s; mapM (pure[0,1]) [1..4] !! read [d]  -- convert to BCD

```

Now it's only a matter of using this operator once with `max` and once with `min` and subtracting their results:

```
f x = max#x - min#x

```

# Answer
> 2 votes
# Japt `-x`, 20 bytes

```
®¤ùT4Ã¬¬£ZéY ì2Ãn äa

```

Try it online!

Input as an array of digits.

Explanation:

```
®¤                      #Map each digit to base 2
  ùT4Ã                  #Pad each one to 4 places
      ¬                 #Join them to a single binary string
       ¬                #Split them to an array of single characters
        £      Ã        #For each index Y in that array:
         ZéY            # Get the array rotated Y times
             ì2         # Convert the array from binary to decimal
                n       #Sort the results
                  äa    #Get the absolute difference between each element
                        #Implicitly output the sum

```

# Answer
> 1 votes
# Perl 5, ~~97~~ ~~91~~ 89 + 2 (`-F`) = ~~99~~ ~~93~~ 91 bytes

```
$a=sprintf"%04b"x@F,@F;@r=sort{$b<=>$a}map{oct"0b".($a=(chop$a).$a)}(@F)x4;say$r[0]-pop@r

```

Try it online!

# Answer
> 1 votes
# Pyth, 24/26 bytes

```
s.+Smi.>Gd2l=Gsm.[\04.Bs

```

Takes input as a quoted string. 26 bytes if it needs to take input as an integer; append `dz` in that case.

Test Cases (input as strings, 24 bytes)

Test Cases (input as numbers, 26 bytes)

# Answer
> 1 votes
# J, 43 bytes

```
3 :'(>./-<./)#.(i.@#|."0 1]),}.#:8,"."0":y'

```

Try it online!

Sometimes tacit style makes things difficult. But there's probably a way to do it tacit style that's a lot more concise than this. I think I remember a better way to split a number to digits other than `"."0@":` but I can't seem to recall it...

### Explanation

```
3 :'(>./-<./)#.(i.@#|."0 1]),}.#:8,"."0":y'
                                         y  the input (integer)
                                       ":   convert to string
                                   "."0     evaluate each char (split to digits)
                                 8,         prepend 8
                               #:           debase 2
                             }.             behead (remove the 8)
                            ,               ravel (flatten)
               (i.@#|."0 1])                create a list of rotations
                    |.    ]                   rotate the list
                      "0 1                    for each number on the left
                i.@#                          range 0 ... length - 1
             #.                             convert rotations back to base 10
    (>./-<./)                               max minus min

```

The prepending and removing 8 is to ensure that the right number of zeroes are present (J will reshape its arrays to be the size of their maximum length element, and 8 is 4 digits in binary so it is used).

# Answer
> 1 votes
# APL(NARS), 34 chars, 68 bytes

```
{(⌈/-⌊/)2⊥¨{⍵⌽a}¨⍳≢a←∊⍉(4⍴2)⊤⍎¨⍕⍵}

```

some little test:

```
  h←{(⌈/-⌊/)2⊥¨{⍵⌽a}¨⍳≢a←∊⍉(4⍴2)⊤⍎¨⍕⍵}
  h 9752348061
1002931578825
  h 0
0

```

---
Tags: code-golf, binary, base-conversion
---


title: A spiral sequence

text:
# Question
Title: A spiral sequence
# Background

OEIS sequence A272573 describes a spiral on a hexagonal grid as follows:

> Start a spiral of numbers on a hexagonal tiling, with the initial hexagon as a(1) = 1. a(n) is the smallest positive integer not equal to or previously adjacent to its neighbors.

The sequence begins

```
1, 2, 3, 4, 5, 6, 7, 4, 6, 8, 5, 9, 8, 10, 2, 11, ...

```

Here's an illustration of the spiral pattern:

* `a(11) != 1` because then `3` and `1` would be adjacent in two places.
* `a(11) != 2` because then `3` and `2` would be adjacent in two places.
* `a(11) != 3` because then `3` would be adjacent to itself.
* `a(11) != 4` because then `3` and `4` would be adjacent in two places.
* Therefore `a(11) = 5`.

# Challenge

The challenge is to write a program that computes A272573. This is , so shortest code wins.

# Answer
> 23 votes
# JavaScript (ES6),  ~~267 .. 206~~  199 bytes

Returns an array containing the \\$N\\$ first terms of the sequence.

```
n=>(F=v=>++i<n?F([...v,(A=N[i]=[1,!j++||d+1,j%L?d:(j%=L*6)?++d:L++&&d++].map(k=>N[k=i-k].push(i)&&k),g=k=>v[E='every']((V,x)=>V-k|N[x][E](y=>A[E](z=>v[y]-v[z])))?k:g(-~k))()]):v)([L=1],N=[[i=j=d=0]])

```

Try it online!

## How?

### Definitions

By convention, we will call ***corner-cell*** a cell that has only one edge in common with the previous layer of the spiral and ***side-cell*** a cell that has two edges in common with the previous layer. As suggested by Ourous, we can also think of them as order-1 cells and order-2 cells, respectively.

Corner-cells are shown in yellow below. All other cells are side-cells (except the center cell which is a special case).

### About cell neighbors

We don't really need to keep track of the coordinates of the cells on the grid. The only thing that we need to know is the list of neighbor cells for each cell in the spiral at any given time.

In the following diagrams, neighbors in the previous layer are shown in light shade and additional neighbors in the current layer in darker shade.

A cell has **2 neighbors** among the previous cells if:

* it's the first side-cell of a new layer (like **8**)
* or it's a corner-cell, but not the last one of the layer (like **9**)

A cell has **3 neighbors** among the previous cells if:

* it's a side-cell, but not the first one of the layer (like **10**)
* or it's the last corner-cell of the current layer (like **19**)

### Implementation of cell neighbors

The index of the current cell (starting at \\$1\\$) is stored in \\$i\\$. The list of neighbors of a cell \\$n\\$ is stored in \\$A\[n\]\\$.

For obscure golfing reasons, we first compute the opposite offsets of the neighbors. For instance, \\$1\\$ means \\$-1\\$, which means *the previous cell*.

```
[                    //
  1,                 // the previous cell is always a neighbor of the current cell
  !j++ || d + 1,     // if this is not the first cell of the layer, the cell at -(d + 1)
                     // is a neighbor (otherwise, we insert 1 twice; doing it that way
                     // saves bytes and having duplicate neighbors is not a problem)
  j % L ?            // if this is a side-cell:
    d                //   the cell at -d is a neighbor
  :                  // else (corner-cell):
    (j %= L * 6) ?   //   if this is not the last cell:
      ++d            //     insert the dummy duplicate neighbor at -(d + 1); increment d
    :                //   else (last cell):
      L++ && d++     //     the cell at -d is a neighbor; increment L; increment d
]                    //

```

In the above code:

* \\$L\\$ is the index of the current layer, starting at \\$1\\$ (and not counting the center cell).
* \\$j\\$ is the index of the current cell within the current layer, going from \\$1\\$ to \\$6\times L\\$.
* \\$d\\$ is the distance of the current cell to those of the previous layer. It is incremented each time we go through a corner cell.

We then process a `map()` loop which converts the offsets \\$k\\$ into indices (\\$i-k\\$) and push the current cell as a new neighbor for all neighbor cells, to enforce neighborhood symmetry.

```
.map(k =>
  N[k = i - k].push(i) && k
)

```

### Finding the next term of the sequence

Now that we have an up-to-date list of neighbors for all cells, we can finally compute the next term \\$k\\$ of the sequence, using another recursive helper function.

The value of a cell \\$n\\$ is stored in \\$v\[n\]\\$.

```
( g =                 // g = recursive function taking
  k =>                // the candidate value k
    v.every((V, x) => // for each previous cell of value V at position x, make sure that:
      V - k           //   V is not equal to k
      |               //   OR
      N[x].every(y => //   for each neighbor y of x:
        A.every(z =>  //     for each neighbor z of the current cell:
          v[y] - v[z] //       the value of y is not equal to the value of z
        )             //     end
      )               //   end
    )                 // end
    ?                 // if the above conditions are fulfilled:
      k               //   stop recursion and return k
    :                 // else:
      g(-~k)          //   try again with k + 1
)()                   // initial call to g with k undefined (this will cause V - k to be
                      // evaluated as NaN and force the 1st iteration to fail)

```

# Answer
> 7 votes
# Clean, ~~284~~ ~~279~~ ~~272~~ 262 bytes

```
import StdEnv
l=[0,-1,-1,0,1,1]
c(u,v)(p,q)=(u-p)^2+(v-q)^2<2||(u-p)*(q-v)==1
$[h:t]m=hd[[e: $t[(h,e):m]]\\e<-[1..]|and[e<>j\\(u,v)<-m|c h u,(p,q)<-m|q==v,(i,j)<-m|c p i]]

```

#

```
$(scan(\(a,b)(u,v)=(a-u,b-v))(0,0)[(i,j)\\n<-[1..],i<-[1,1:l]&j<-l,_<-[max(~j<<i)1..n]])[]

```

Try it online!

Generates the sequence forever.

**Hexagon Mapping**

Most of the code goes into mapping hexagons uniquely to `(x,y)` coordinates so that there's a single, simple function to determine adjacency which holds for all point mappings.

The mapped points look like this:

```
              ---
        --- < 2,-2> ---       x-axis ___.X'
  --- < 1,-2> === < 2,-1> ---  /__.X'
< 0,-2> === < 1,-1> === < 2, 0>'
  === < 0,-1> === < 1, 0> ===
<-1,-1> === < 0, 0> === < 1, 1>
  === <-1, 0> === < 0, 1> ===
<-2, 0> === <-1, 1> === < 0, 2>.__
  --- <-2, 1> === <-1, 2> ---  \  'Y.___
        --- <-2, 2> ---       y-axis    'Y.
              ---

```

From there, determining adjacency is trivial, and occurs when one of:

* `x1 == x2` and `abs(y1-y2) == 1`
* `y1 == y2` and `abs(x1-x2) == 1`
* `y1 == y2 - 1` and `x2 == x1 - 1`
* `y1 == y2 + 1` and `x2 == x1 + 1`
* `x1 == x2` and `y1 == y2`

**Point Generation**

Notice that when traversing the hexagon in a spiral the differences recur for each layer `n`:

1. `n` steps of `(1,0)`
2. `n-1` steps of `(1,-1)`
3. `n` steps of `(0,-1)`
4. `n` steps of `(-1,0)`
5. `n` steps of `(-1,1)`
6. `n` steps of `(0,1)`

This generates the points in the right order by taking sums of prefixes of this sequence:

```
scan(\(a,b)(u,v)=(a-u,b-v))(0,0)[(i,j)\\n<-[1..],i<-[1,1:l]&j<-l,_<-[max(~j<<i)1..n]]

```

**Bringing it Together**

The code that actually finds the sequence from the question is just:

```
$[h:t]m=hd[[e: $t[(h,e):m]]\\e<-[1..]|and[e<>j\\(u,v)<-m|c h u,(p,q)<-m|q==v,(i,j)<-m|c p i]]

```

Which in turn is mostly filtering by `and[r<>j\\(u,v)<-m|c h u,(p,q)<-m|q==v,(i,j)<-m|c p i]`

This filter takes points from `m` (the list of already-mapped points) by:

* Ignoring natural numbers that are equal to any `j`
* For every `(i,j)` where `i` is adjacent to `p`
* For every `(p,q)` where the value `q` is equal to `v`
* For every `(u,v)` where `u` is adjacent to the current point

---
Tags: code-golf, sequence, hexagonal-grid
---


title: Fill the Bucket

text:
# Question
Title: Fill the Bucket
Your task is to fill the bucket with numbers upto a given input.

### Rules

Numbers occupy the leftmost position then rightmost, then leftmost and so on.

After overflow, the numbers start to gather around the bucket in a similar manner. They occupy position diagonally.

The examples should make it clear what the expected output is (Some rules are mentioned in the examples).

For more then 10, use the rightmost digit

### Examples:

```
The bucket:
|      |  or |      |
|      |     |      |
|      |     |      |
|      |     |      |
|------|     |______|

input:1  (You can start from either 0 or 1)
output:
|      |  (There can be whitespace to the left even if there is no overflow
|      |  but the bucket must not be distorted.)
|      |
|1     |
|------|

input:6
output:
|      |
|      |
|      |
|135642|
|------|

input:8
output:
|      |
|      |
|7    8|
|135642|
|------|

input:23
output:
|913 20|
|357864|
|791208|
|135642|
|------|

input:27
output:
  |913420|
  |357864|
  |791208|
  |135642|
75|------|6

input:30
output:
  |913420|
  |357864|
  |791208|
 9|135642|0
75|------|68

input:40
output:
    |913420|
    |357864|
   5|791208|6
 939|135642|040
7175|------|6828

input:54   (Maximum input for start=1)
    3|913420|4
   13|357864|42
  915|791208|620
 7939|135642|0408
57175|------|68286

```

This is **code-golf** so shortest code wins.

# Answer
> 9 votes
# JavaScript (Node.js),  ~~145~~  143 bytes

A hard-coded pattern (see **here** for more maths).

1-indexed.

```
n=>`    g|EGIJHF|h
   e]|?ACDB@|^f
  c[U|9;=><:|V\\d
 aYSO|357864|PTZb
_WQMK|------|LNRX\``.replace(/[3-h]/g,c=>(x=Buffer(c)[0])<n+51?x%10:' ')

```

Try it online!

*Saved 2 bytes thanks to @tsh*

# Answer
> 8 votes
# JavaScript (ES6),  ~~144 ... 139~~  137 bytes

A mathematical approach (see **here** for less maths).

0-indexed.

```
n=>(y=4,g=x=>~y?(X=x>8?17-x:x,k=X<y?g:X<5?24-(z=4+y-X)*~z+y*2:y*6+X*2-18,~X?X^5?k<0?'-':(k+=x>8)<n?k%10:' ':'|':`
`)+g(~X?-~x:!y--):'')()

```

Try it online!

### How?

The output is built character by character, with \\$y\\$ decreasing from \\$4\\$ to \\$0\\$ and \\$x\\$ increasing from \\$0\\$ to \\$18\\$ on each row.

We define:

$$X=\begin{cases}x&\text{if }x\le 8\\17-x&\text{if }x\>8\end{cases}$$

By writing the full values rather than just the unit digits, we get the following table:

```
 x |  0  1  2  3  4  5  6  7  8 |  9 10 11 12 13 14 15 16 17 18
 X |  0  1  2  3  4  5  6  7  8 |  8  7  6  5  4  3  2  1  0 -1
---+----------------------------+-------------------------------
 4 | .. .. .. .. 52 || 18 20 22 | 23 21 19 || 53 .. .. .. .. \n
 3 | .. .. .. 50 42 || 12 14 16 | 17 15 13 || 43 51 .. .. .. \n
 2 | .. .. 48 40 34 || 6  8  10 | 11 9  7  || 35 41 49 .. .. \n
 1 | .. 46 38 32 28 || 0  2  4  | 5  3  1  || 29 33 39 47 .. \n
 0 | 44 36 30 26 24 || -- -- -- | -- -- -- || 25 27 31 37 45 \n

```

This table is essentially symmetric across the y-axis, except that the values on the left side are even and the values on the right side are their odd counterparts.

We define:

$$k=\begin{cases}24+(4+y-X)(5+y-X)+2y&\text{if }X\<5\\6y+2X-18&\text{if }X\>5\end{cases}$$

$$k'=\begin{cases}k&\text{if }x\le 8\\k+1&\text{if }x\>8\end{cases}$$

And for each cell, we append:

* a linefeed if \\$X=-1\\$
* a pipe if \\$X=5\\$
* a hyphen if \\$k\<0\\$
* a space if \\$X\<y\\$ or \\$k'\>n\\$ (where \\$n\\$ is the input)
* \\$k' \bmod 10\\$ otherwise

### Commented

```
n => (                                // main function taking n
  y = 4,                              // start with y = 4
  g = x =>                            // g = recursive function taking x
    ~y ?                              // if y is not equal to -1:
      ( X = x > 8 ? 17 - x : x,       //   compute X
        k = X < y ?                   //   if X is less than y:
          g                           //     set k to a non-numeric value
        :                             //   else:
          X < 5 ?                     //     if X is less than 5:
            24 - (z = 4 + y - X) * ~z //       apply the 'side numbers' formula
             + y * 2                  //
          :                           //     else:
            y * 6 + X * 2 - 18,       //       apply the 'middle numbers' formula
        ~X ?                          //   if X is not equal to -1:
          X ^ 5 ?                     //     if X is not equal to 5:
            k < 0 ?                   //       if k is less than 0:
              '-'                     //         append a hyphen
            :                         //       else:
              (k += x > 8) < n ?      //         update k to k'; if it's less than n:
                k % 10                //           append the unit digit of k'
              :                       //         else:
                ' '                   //           append a space
          :                           //     else (X = 5):
            '|'                       //       append a pipe
        :                             //   else (X = -1):
          `\n`                        //     append a linefeed
      )                               //
      + g(~X ? -~x : !y--)            //   update x and y, and do a recursive call
    :                                 // else (y = -1):
      ''                              //   stop recursion
)()                                   // initial call to g with x undefined

```

# Answer
> 3 votes
# Python 2, 170 bytes

```
I=input()
s="    u|SUWXVT|v\n   sk|MOQRPN|lt\n  qic|GIKLJH|djr\n oga]|ACEFDB|^bhp\nme_[Y|------|Z\`fn"
i=1
exec"s=s.replace(chr(64+i),[`i%10`,' '][i>I]);i+=1;"*55
print s

```

Try it online!

# Answer
> 3 votes
# Java 10, 168 bytes

```
n->"    g|EGIJHF|h\n   e]|?ACDB@|^f\n  c[U|9;=><:|V\\d\n aYSO|357864|PTZb\n_WQMK|------|LNRX`".chars().forEach(c->System.out.print(c<46|c==124?(char)c:c<n+51?c%10:" "))

```

Port of *@Arnauld*'s JavaScript answer (so also 1-indexed, and outputting `-` as bottom). If you like this answer, make sure to upvote him as well!

Try it online.

**Explanation:**

```
n->                      // Method with integer parameter and no return-type
  "    g|EGIJHF|h\n   e]|?ACDB@|^f\n  c[U|9;=><:|V\\d\n aYSO|357864|PTZb\n_WQMK|------|LNRX`"
                         //  String containing the bucket and magic string
   .chars().forEach(c->  //  Loop over the characters (as integers)
     System.out.print(   //   Print:
       c<46|c==124?      //    If the character is "\n", " ", "-", or "|":
        (char)c          //     Output the character as is
       :c<n+51?          //    Else-if the character value is smaller than the input + 51:
        c%10             //     Output a digit: the character value modulo-9
       :                 //    Else:
        " "))            //     Output a space

```

# Answer
> 1 votes
# 6502 machine code (C64), 130 bytes

```
00 C0 20 9B B7 A9 C0 65 65 85 FB A2 00 BD 2B C0 F0 1A 10 12 C5 FB 90 04 A9 20
D0 0A 69 70 C9 3A 90 04 E9 0A B0 F8 20 D2 FF E8 D0 E1 60 20 20 20 20 F5 7D D3
D5 D7 D8 D6 D4 7D F6 0D 20 20 20 F3 EB 7D CD CF D1 D2 D0 CE 7D EC F4 0D 20 20
F1 E9 E3 7D C7 C9 CB CC CA C8 7D E4 EA F2 0D 20 EF E7 E1 DD 7D C1 C3 C5 C6 C4
C2 7D DE E2 E8 F0 0D ED E5 DF DB D9 7D 2D 2D 2D 2D 2D 2D 7D DA DC E0 E6 EE 00

```

This uses a modified version of the "preformatted" approach of some other answers. It contains a full string of the bucket, but the digits are replaced by values starting from `0xC1`, while any characters for direct printing are in the range `0x01`-`0x7f`.

The C64 charset doesn't include a pipe (`|`) character, it's therefore replaced with the similar-looking PETSCII character `0x7d`.

### Online demo

Usage: `SYS49152,[n]` (1-indexed, e.g. `SYS49152,54` for the full output)

**Commented disassembly**:

```
         00 C0       .WORD $C000        ; load address
.C:c000  20 9B B7    JSR $B79B          ; get unsigned byte from commandline
.C:c003  A9 C0       LDA #$C0           ; add #$C0 (+ carry = #$C1) ...
.C:c005  65 65       ADC $65            ; ... to parameter
.C:c007  85 FB       STA $FB            ; and store in $FB
.C:c009  A2 00       LDX #$00           ; loop index
.C:c00b   .loop:
.C:c00b  BD 2B C0    LDA .bucket,X      ; loop over encoded string
.C:c00e  F0 1A       BEQ .done          ; null-terminator -> done
.C:c010  10 12       BPL .out           ; positive (bit 7 clear) -> output
.C:c012  C5 FB       CMP $FB            ; compare with parameter+#$C1
.C:c014  90 04       BCC .digit         ; smaller -> convert to digit
.C:c016  A9 20       LDA #$20           ; otherwise load space character
.C:c018  D0 0A       BNE .out           ; and output
.C:c01a   .digit:
.C:c01a  69 70       ADC #$70           ; add offset to '0' (#$30)
.C:c01c   .check:
.C:c01c  C9 3A       CMP #$3A           ; greater than '9' (#$39) ?
.C:c01e  90 04       BCC .out           ; no -> to output
.C:c020  E9 0A       SBC #$0A           ; otherwise subtract 10 (#$a)
.C:c022  B0 F8       BCS .check         ; and check again
.C:c024   .out:
.C:c024  20 D2 FF    JSR $FFD2          ; output character
.C:c027  E8          INX                ; next index
.C:c028  D0 E1       BNE .loop          ; and repeat loop
.C:c02a   .done:
.C:c02a  60          RTS                ; exit ....
.C:c02b   .bucket:
.C:c02b  20 20 20    [...]              ; "encoded" string for bucket

```

# Answer
> 0 votes
# Charcoal, 64 bytes

```
Ｎθ³↑⁵‖Ｍ←Ｆ²«‖Ｊ⁻³ι±¹Ｆ⊘⁺θ¬ι«↖Ｉ﹪⁺⊗κ⊕ιχＭ§”)⊟E≡≦⌈▷⊖ü∕”κ§”)⊟＆hXτtD(λＭ”κ

```

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

```
Ｎθ

```

Input the number.

```
³↑⁵‖Ｍ←

```

Draw half of the bucket and then mirror it to complete the bucket.

```
Ｆ²«

```

Loop for each side of the bucket.

```
‖Ｊ⁻³ι±¹

```

Reflect the bucket so that we can draw in a consistent direction on both loops, and jump to the position of the first digit on that side of the bucket.

```
Ｆ⊘⁺θ¬ι«

```

Loop over the number of digits on that side of the bucket.

```
↖Ｉ﹪⁺⊗κ⊕ιχ

```

Print the next digit and move the cursor up and left.

```
Ｍ§”)⊟E≡≦⌈▷⊖ü∕”κ§”)⊟＆hXτtD(λＭ”κ

```

Adjust the cursor position by reading the offsets from two compressed strings, `003003003005203004000500` (horizontal offsets) and `11011011011510200300040000` (vertical offsets). These offsets take the above cursor movement into account which conveniently means that they never have to be negative.

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


title: Hollow out an array

text:
# Question
Title: Hollow out an array
## The task

This challenge is very simple. Your input is a rectangular 2D array of integers, sized at least 1×1. It can be taken in any reasonable format. Your output shall be the input array, but with all entries *not* on the first or last row or column set to `0`. It must be in the same format as the input.

For example, if the input array is

```
67  4 -8  5 13
 9 13 42  4 -7
 1  1  3 -9 29
16 99  8 77  0

```

then the correct output is

```
67  4 -8  5 13
 9  0  0  0 -7
 1  0  0  0 29
16 99  8 77  0

```

## Rules and scoring

You can write a full program or a function, and functions are allowed to modify the input in place instead of returning it. The lowest byte count wins, and standard loopholes are disallowed.

## Test cases

These are formatted as nested lists to make copy-pasting easier.

```
[[3]] -> [[3]]
[[7,2,8]] -> [[7,2,8]]
[[3],[5],[12],[-6]] -> [[3],[5],[12],[-6]]
[[99,98,97],[88,87,86]] -> [[99,98,97],[88,87,86]]
[[6,7],[8,9],[10,11]] -> [[6,7],[8,9],[10,11]]
[[-1,-2,-3],[1,2,3],[5,5,5]] -> [[-1,-2,-3],[1,0,3],[5,5,5]]
[[67,4,-8,5,13],[9,13,42,4,-7],[1,1,3,-9,29],[16,99,8,77,0]] -> [[67,4,-8,5,13],[9,0,0,0,-7],[1,0,0,0,29],[16,99,8,77,0]]
[[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0]] -> [[0,1,0,1,0],[1,0,0,0,1],[0,0,0,0,0],[1,0,0,0,1],[0,1,0,1,0]]

```

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

If you want to include multiple numbers (e.g. because you've improved your score or you want to list interpreter flags separately), make sure that the actual score is the *last* number in the header:

```
## Perl, <s>50</s> 43 + 2 (-p flag) = 45 bytes

```

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

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

```

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

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

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

# Answer
# MATL, 9 bytes

```
0HJ_ht4$(

```

Input is in the format

```
[67  4 -8  5 13;  9 13 42  4 -7;  1  1  3 -9 29; 16 99  8 77  0]

```

*EDIT (June 12, 2016): to adapt to changes in the language, the link below has `_` replaced by `q`*.

**Try it online**!

```
0           % Push a 0: value that will be assigned into the array
HJ_h        % Vector [2, -1j]: this corresponds to index 2:end-1 for rows
t           % Duplicate: same index for columns
4$(         % Assignment indexing with 4 inputs: array, new value, row and col indices
            % Since the first input (array) to this function is currently missing, it's
            % implicitly taken at this point from stdin
            % Implicitly display stack contents, which is the modified array

```
> 13 votes

# Answer
# Jelly, ~~18~~ ~~17~~ ~~15~~ 9 bytes

```
0W&ṖZ
ÇÇ^

```

Try it online! or verify all test cases.

### Background

This approach is based on @Sp3000's Jelly answer, specifically on his idea to take advantage of vectorized operations between lists of different lengths.

We start by taking the bitwise AND of **0** and every integer in the first row of the input. Due to automatic vectorization, this can be achieved by taking the bitwise AND of **\[0\]** and the input without its last row. **0** is paired with the first row, resulting in a row of zeroes. Since the remaining rows have no counterpart in **\[0\]**, they are left untouched.

Now we transpose the result, apply the above transformation once again (effectively removing the last column and zeroing out the first), and transpose again.

For the input

```
 67   4  -8   5  13
  9  13  42   4  -7
  1   1   3  -9  29
 16  99   8  77   0

```

this results in

```
  0   0   0   0
  0  13  42   4
  0   1   3  -9

```

Now, we take the bitwise XOR of this result and the original matrix. XORing an integer with itself yields **0**. XORing an integer with **0** (or not XORing it at all) yields the same integer. This hollows the matrix out.

### How it works

```
0W&ṖZ    Helper link. Argument: M (matrix)

0W       Yield [0].
   Ṗ     Yield M, without its last row.
  &      Take the bitwise AND of both.
    Z    Zip the result.

ÇÇ^      Main link. Input: A (matrix)

Ç        Call the helper link on A.
 Ç       Call the helper link on the result.
  ^      Take the bitwise XOR of the result and A.

```
> 12 votes

# Answer
## Java 7, as a fully named function: 85

```
void f(int[][]a){for(int i=0,j;++i<a.length-1;)for(j=1;j<a[i].length-1;)a[i][j++]=0;}

```

You could lambda this down in Java 8 to remove a few bytes, but I don't really do that.
> 11 votes

# Answer
## Mathematica, 27 bytes

```
(a=#;a[[2;;-2,2;;-2]]=0;a)&

```
> 8 votes

# Answer
## , ~~33~~ 48 bytes

I know, R isn't made for golfing. But it is made for positional indexing... Loading up an example;

```
a <- matrix(c(67,4,-8,5,13,9,13,42,4,-7,1,1,3,-9,29,16,99,8,77,0), ncol=5, byrow=TRUE)
a
#      [,1] [,2] [,3] [,4] [,5]
# [1,]   67    4   -8    5   13
# [2,]    9   13   42    4   -7
# [3,]    1    1    3   -9   29
# [4,]   16   99    8   77    0

```

Replace the value at any position not on the edge row or column, with 0:

```
x <- function(a){a[-c(1,nrow(a)),-c(1,ncol(a))]<-0;a}

x(a)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]   67    4   -8    5   13
# [2,]    9    0    0    0   -7
# [3,]    1    0    0    0   29
# [4,]   16   99    8   77    0

```

Also checking a 2-column test:

```
b <- matrix(c(99,98,97,88,87,86), ncol=2, byrow=TRUE)
b
#     [,1] [,2]
#[1,]   99   98
#[2,]   97   88
#[3,]   87   86

x(b)
#     [,1] [,2]
#[1,]   99   98
#[2,]   97   88
#[3,]   87   86

```

Posterity: previous attempt

```
# a[2:(nrow(a)-1),2:(ncol(a)-1)]<-0 # previous attempt

```

Testing all examples:

```
tests <- read.table(text="[[3]] -> [[3]]
                          [[7,2,8]] -> [[7,2,8]]
                          [[3],[5],[12],[-6]] -> [[3],[5],[12],[-6]]
                          [[99,98,97],[88,87,86]] -> [[99,98,97],[88,87,86]]
                          [[6,7],[8,9],[10,11]] -> [[6,7],[8,9],[10,11]]
                          [[-1,-2,-3],[1,2,3],[5,5,5]] -> [[-1,-2,-3],[1,0,3],[5,5,5]]
                          [[67,4,-8,5,13],[9,13,42,4,-7],[1,1,3,-9,29],[16,99,8,77,0]] -> [[67,4,-8,5,13],[9,0,0,0,-7],[1,0,0,0,29],[16,99,8,77,0]]
                          [[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0]] -> [[0,1,0,1,0],[1,0,0,0,1],[0,0,0,0,0],[1,0,0,0,1],[0,1,0,1,0]]")
tests$cols <- c(1,3,1,3,2,3,5,5)
tests$V1 <- gsub("\\[|\\]","",tests$V1)
tests$V1 <- paste0("c(",tests$V1,")")
tests$V3 <- gsub("\\[|\\]","",tests$V3)
tests$V3 <- paste0("c(",tests$V3,")")

testfn <- function(testno) {
  intest <- matrix(eval(parse(text=tests$V1[testno])), ncol=tests$cols[testno], byrow=TRUE)
  intest <- x(intest)
  outtest <- matrix(eval(parse(text=tests$V3[testno])), ncol=tests$cols[testno], byrow=TRUE)
  return(identical(intest, outtest))
}

sapply(seq_len(nrow(tests)), testfn)
# [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

```
> 7 votes

# Answer
# GNU Sed, 31

* Thanks to @manatwork for saving 4 bytes.

Version 4.2.2 or earlier, prior to this commit (discussion).

Score includes +1 for `-r` option.

Input rows are newline separated. Elements on each row are single-line separated.

```
1n
$n
:
s/ -?\w+ / : /
t
y/:/0/

```

### Explanation

```
1n                   # 1st line: print unchanged, then load next line
$n                   # last line: print unchanged, then load next line (i.e. EOF and stop)
:                    # unnamed label
s/ -?\w+ / : /       # substitute a number in spaces with a `:` in spaces
t                    # If the above matched, jump back to the label and try again
y/:/0/;              # transliterate `:` to `0`

```

Try it online.
> 6 votes

# Answer
# Octave, 34 bytes

```
function h(M) M(2:end-1,2:end-1)=0

```

Note that the input requires semicolons to separate array rows:

```
h([[3];[5];[12];[-6]])

```

### Explanation:

Octave (and MATLAB) array indices are 1-based. Specifying a range of `Array(1:end)` will give you all elements of the (one-dimensional, in this example) array. `Array(2:end-1)` will give you all of the elements *except* the first and last.

```
M(2:end-1,2:end-1)=0

```

sets to `0` all elements not in the first or last row or column:

```
>> A = [[-1,-2,-3];[1,2,3];[5,5,5]]
A =

  -1  -2  -3
   1   2   3
   5   5   5

>> h(A)
M =

  -1  -2  -3
   1   0   3
   5   5   5

```

If one of the dimensions is less than or equal to 2, the range `end-1` is **less** than 2, therefore the end of the range `(2:end-1)` is less than the beginning. In this case, Octave ignores the range and does nothing. This is analogous to the `for` loop:

```
for (int i=2; i < 2; i++) {...}

```

The stop condition is true on the first iteration, so we fall out of the loop.

```
>> A = [[6,7];[8,9];[10,11]]
A =

    6    7
    8    9
   10   11

>> h(A)
M =

    6    7
    8    9
   10   11

```
> 5 votes

# Answer
# Mathematica ~~81~~ 76 bytes

```
(d=Dimensions@m;q=MemberQ;m Boole@Array[{1,d[[1]]}~q~#||{1,d[[2]]}~q~#2&,d])&

```

---

## How it works

Assume that the input array is stored in `m`. The dimensions of `m` are {4,5}\`

```
(m={{67,4,-8,5,13}, {9,13,42,4,-7}, {1,1,3,-9,29}, {16,99,8,77,0}})//MatrixForm

```

---

Each cell in the following array, `a`, is True if the cell is either in the first or (`||`) in last row or in the first or last column; otherwise it is False.

```
(d=Dimensions@m;a=Array[MemberQ[{1,d[[1]]},#]||MemberQ[{1,d[[2]]},#2]&,d])&[m]//MatrixForm

```

---

Applying the function `Boole` to the array converts True to 1 and False to 0.

```
b = Boole[a]

```

---

Multiply the matrix `m` by `b`. This multiplies each cell in m by the corresponding cell in b.

```
m b

```
> 5 votes

# Answer
## Jelly, 12 bytes

```
ZṖṖ1;¥€
¬ÇÇ×

```

I think this works, still wrapping my head around Jelly. Try it online!

*(Thanks to @Dennis for -2 bytes)*

Works by multiplying the input array by an arrays of 1s and 0s one dimension smaller each way. For example, for `[[67,4,-8,5,13],[9,13,42,4,-7],[1,1,3,-9,29],[16,99,8,77,0]]` we multiply element-wise by

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

```

### Full explanation

```
[Helper link - argument is a matrix]
Z           Zip
 ṖṖ         Pop last two elements, or [:-2]
   1;¥€     Append a 1 in front of every row

[Main link]
¬           Not, turning 0s to 1s and everything else to 0s. Even though some zeroes
            turn into 1s, it's fine because we multiply element-wise at the end,
            and 0*1 = 0
 ÇÇ         Perform helper link twice
   ×        Multiply element-wise

```
> 5 votes

# Answer
## ES6, ~~52~~ ~~48~~ 46 bytes

```
f=a=>a.map((b,i)=>i&&a[i+1]+.5?b.map?f(b):0:b)

```

Edit: Saved 4 bytes thanks to @user81655. Saved a further 2 bytes thanks to @ETHproductions.
> 5 votes

# Answer
# Julia, ~~50~~ 35 bytes

```
A->A[2:size(A,1)-1,2:size(A,2)-1]=0

```

This is an anonymous function that accepts an array and modifies it in place. To call it, assign it to a variable.

The approach here is quite simple: For the *n* by *m* input array *A*, we assign *A*<sub>*ij*</sub> = 0 for all *i* = 2, ..., *n*-1 and *j* = 2, ..., *m*-1 by constructing ranges of indices. The ranges may be empty, like if *n* or *m* = 1, in which case no replacement is done.

Try it online

Saved 15 bytes thanks to Dennis!
> 4 votes

# Answer
# Javascript, ~~62~~ ~~59~~ 56 bytes

```
s=>s.replace(/(^.*|\n\s*\S+)|\S+(?= .*\n)/g,(a,b)=>b||0)

```

This approach expects an string as argument. You can see what the regex do here: https://regex101.com/r/kC6xA8/3
> 4 votes

# Answer
## C, 62 bytes

```
y;f(a,b,c)int **a;{for(b--;b-->1;)for(y=1;y<c-1;)a[b][y++]=0;}

```

Hope it's ok to take in array length/width as parameters. I played around with memset/bzero a little bit, but multiplying by `sizeof(int)` drastically increased the code size.

EDIT: 55 bytes if we can further bend the rules and store our array as characters since the input is only a single digit each.

```
x;
#define f(a,b,c) for(x=1;x<b-1;)bzero(a[x++]+1,c-2);

```

EDIT: Thanks Washington Guedes for the tip!
> 4 votes

# Answer
# Mathematica, 55 bytes

```
#-Unitize@ArrayFilter[Det,Power~Array~Dimensions@#,1]#&

```

---

**Test case**

```
%[RandomInteger[9,{5,5}]]
(*
  {{8,8,3,6,5},
   {7,0,0,0,4},
   {2,0,0,0,7},
   {3,0,0,0,5},
   {8,6,1,0,8}}
*)

```

---

**Explanation**

The main idea of this answer is the same as DavidC's answer (first construct a mask matrix, and then multiply it to the original matrix), but the construction of mask matrix is different.

`ArrayFilter[f,list,r]` maps `f` onto every element of `list` within a radius of `r`.

```
ArrayFilter[f,{1,2,3,4,5},1]
(* { f[{1,1,2}], f[{1,2,3}], f[{2,3,4}], f[{3,4,5}], f[{4,5,5}] } *)

```

Note that boundary elements are duplicated where there are insufficient neighbors. When `list` is of 2-dimensions, this feature works well together with `Det` to give the desired result, since duplicated columns or rows on four boundaries vanish the determinants.

```
ArrayFilter[Det,Power~Array~{4,4},1]
(*
  {{0, 0,  0,    0},
   {0, 12, 72,   0},
   {0, 48, 1152, 0},
   {0, 0,  0,    0}}
*)

```

where `Power~Array~{4,4}` guarantees the determinants on inner positions to be non-zero. And

```
1-Unitize@%
(*
  {{1,1,1,1},
   {1,0,0,1},
   {1,0,0,1},
   {1,1,1,1}}
*)

```

gives the mask matrix.
> 4 votes

# Answer
## Python, 50 bytes

```
def f(a):
 for l in a[1:-1]:l[1:-1]=[0]*(len(l)-2)

```

Accepts a list of lists, and modifies it in place. Python's slice syntax is not inconvenient for this task.

I learned that multiplying a list by a negative number results in an empty list, which allows the above code to work on small inputs.
> 4 votes

# Answer
# Java 8, as a lambda function: ~~82~~ ~~83~~ 95 chars/bytes

Lambda Signature: `int[][] -> (void)` (i.e. `Consumer<int[][]>`)

```
(a)->{int[]v={1,1};while(++v[0]<a.length){while(++v[1]<a[0].length)a[v[0]-1][v[1]-1]=0;v[1]=1}}

```

**EDIT** Made a mistake, I thought that a\[x, y\] was the xth row and the yth col. Clearly it should be a\[x\]\[y\] though!

**EDIT** I forgot to test the code, and I need to set the column back to zero every time inside the loop, +12 bytes. :/
> 3 votes

# Answer
# Perl 6, 28 bytes

```
{.[1..*-2]»[1..*-2] »=»0}

```

This modifies the input in-place

### Usage

```
my @test-cases = (
  [[3],] => [[3],],
  [[7,2,8],] => [[7,2,8],],
  [[3],[5],[12],[-6]] => [[3],[5],[12],[-6]],
  [[99,98,97],[88,87,86]] => [[99,98,97],[88,87,86]],
  [[6,7],[8,9],[10,11]] => [[6,7],[8,9],[10,11]],
  [[ -1,-2,-3],[1,2,3],[5,5,5]] => [[ -1,-2,-3],[1,0,3],[5,5,5]],
  [[67,4,-8,5,13],[9,13,42,4,-7],[1,1,3,-9,29],[16,99,8,77,0]] => [[67,4,-8,5,13],[9,0,0,0,-7],[1,0,0,0,29],[16,99,8,77,0]],
  [[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0]] => [[0,1,0,1,0],[1,0,0,0,1],[0,0,0,0,0],[1,0,0,0,1],[0,1,0,1,0]],
);

use Test;
plan +@test-cases;

for @test-cases {
  my $k = .key;
  {.[1..*-2]»[1..*-2] »=»0}( $k ); # <==
  ok $k eqv .value
}

```

```
1..8
ok 1 -
ok 2 -
ok 3 -
ok 4 -
ok 5 -
ok 6 -
ok 7 -
ok 8 -

```
> 3 votes

# Answer
# JavaScript ES6, ~~69~~ ~~66~~ 57 bytes

```
Y=>Y.map((X,y)=>X.map((N,x)=>x*y&&X[x+1]+.5&&Y[y+1]?0:N))

```

### How it works

This solution maps through each y-index `y` and x-index `x` in the input and decides whether or not to throw it out based on these two indices. There are four cases which we need to keep:

* `x` is 0
* `y` is 0
* `x` equals the length of the inner array, minus 1
* `y` equals the length of the outer array, minus 1

We can take care of the first two with a little multiplication: `x*y` returns `0` iff either `x` or `y` are 0, and a positive integer otherwise. Now for the third: we could check if `X.length>x+1`, but that takes a lot of bytes. Another way to do this is to check if the item ahead is falsy, namely `undefined`, which is what you get when trying to access a non-existent item. However, this also matches if the next item is `0`, so we add 0.5 to make sure that doesn't happen:

```
1 + 0.5 = 1.5 (truthy)
0 + 0.5 = 0.5 (truthy)
-1 + 0.5 = -0.5 (truthy)
undefined + 0.5 = NaN (falsy)

```

Finally, the fourth point: since the outer array has only arrays inside, and any array is truthy, we can just check `Y[y+1]`. Now with `?0:N`, we convert it to `0` if all of the above turned out truthy; `N` otherwise. And that's it!
> 3 votes

# Answer
# Retina, ~~31 24~~ 22

```
(?<=¶.+ )\S+(?= .*¶)
0

```

Saved 2 bytes thanks to randomra

Try it online!

There is probably a better way to do it, as this is just a pretty basic multi-line replacement. Essentially we find each number that is preceded by a newline, some number of characters and a space, and is immediately followed by a space and then and is eventually followed by a newline. These numbers are then all replaced with `0`.

This will not preserve column padding, but I don't think that's a problem.
> 3 votes

# Answer
## Haskell, ~~59~~ 58 bytes

```
k _[x]=[x]
k f(x:y)=x:(f<$>init y)++[last y]
f=k(k(\_->0))

```

### Expanded

```
onInner :: (a -> a) -> [a] -> [a]
onInner _ [x]    = [x]
onInner f (x:xs) = x : map f (init xs) ++ [last xs]

hollowOut :: [[Int]] -> [[Int]]
hollowOut =
   onInner       -- leave first and last line alone
     (onInner    -- leave first and last entry per line
       (const 0) -- replace entries by 0
     )

```
> 3 votes

# Answer
# Groovy, 70 bytes

This isn't very creative, but it's short!

```
g={a->for(i=1;i<a.size()-1;i++)for(j=1;j<a[i].size()-1;)a[i][j++]=0;a}

```

## Explanation

Closure with one arg

```
g={a->

```

Iterate over the inner array, skipping the first and last elements

```
for(i=1;i<a.size()-1;i++)

```

Iterate over middle items in the inner array

```
for(j=1;j<a[i].size()-1;)

```

Set the elements to `0` and return `a`

```
a[i][j++]=0;a}

```

## Tests

```
assert g([[3]]) == [[3]]
assert g([[7, 2, 8]]) == [[7, 2, 8]]
assert g([[3], [5], [12], [-6]]) == [[3], [5], [12], [-6]]
assert g([[99, 98, 97], [88, 87, 86]]) == [[99, 98, 97], [88, 87, 86]]
assert g([[6, 7], [8, 9], [10, 11]]) == [[6, 7], [8, 9], [10, 11]]
assert g([[-1, -2, -3], [1, 2, 3], [5, 5, 5]]) == [[-1, -2, -3], [1, 0, 3], [5, 5, 5]]
assert g([[67, 4, -8, 5, 13], [9, 13, 42, 4, -7], [1, 1, 3, -9, 29], [16, 99, 8, 77, 0]]) == [[67, 4, -8, 5, 13], [9, 0, 0, 0, -7], [1, 0, 0, 0, 29], [16, 99, 8, 77, 0]]
assert g([[0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]]) == [[0, 1, 0, 1, 0], [1, 0, 0, 0, 1], [0, 0, 0, 0, 0], [1, 0, 0, 0, 1], [0, 1, 0, 1, 0]]

```
> 2 votes

# Answer
## Pyth, 18 bytes

```
Qjbm:dSttld0P.Qe.Q

```

Explanation

```
                   - autoassign Q=eval(input())
                   - autoassign .Q = map(eval, rest_of_input)
Q                  - imp_print(Q)
   m        P.Q    -  [V for d in .Q[:-1]]
      Sttld        -     range(1, len(d)-2+1)
    :d     0       -    assign_indexes(d, ^, 0)
 jb                - "\n".join(^)
               e.Q - imp_print(.Q[-1])

```

Input arrays are separated by newlines

Try it here
> 2 votes

# Answer
# R, ~~71~~ ~~64~~ 57 Bytes

```
function(m){if(all((y<-dim(m)-1)>1))m[2:y[1],2:y[2]]=0;m}

```

*edit* -7 bytes by explicitly dealing with \<2-row or \<2-column matrices explicitly *edit2* -7 bytes by assigning dimensions of matrix while checking the size
> 2 votes

# Answer
## C++, ~~80~~ 79 bytes

Expects the array as `int**` with given sizes `n` and `k`:

```
void p(int**c,int n,int k){for(int j,i=1;1+i<n;++i)for(j=1;j+1<k;)c[i][j++]=0;}

```

An alternative that works for any type that has `size()` and `value_type & operator[](int)` (98 bytes):

```
template<class C>void p(C&c){for(int j,i=1;1+i<c.size();++i)for(j=1;j+1<c[i].size();)c[i][j++]=0;}

```

### Expanded version

```
template <class Container>
void hollowOut(Container & ctn){
    const auto size = ctn.size();

    for(typename Container::size_type i = 1; i + 1 < size; ++i) {
        const auto inner_size = ctn[i].size();

        for(decltype(inner_size) j = 1; j + 1 < inner_size; ++j) {
            ctn[i][j] = 0;
        }
    }
}

```
> 1 votes

# Answer
## PHP, ~~82~~ ~~81~~ ~~80~~ 71 bytes

```
function(&$z){for(;$z[++$i+1];)for(;0 .$z[0][++$$i+1];)$z[$i][$$i]=0;};

```

Run like this:

```
php -r '$f = function(&$z){for(;$z[++$i+1];)for(;0 .$z[0][++$$i+1];)$z[$i][$$i]=0;};   $z=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]; $f($z); print_r($z);'

```
* Saved a byte by assuming constant size rows (thx to manatwork)
* Saved a byte by making it an anonymous function
* Saved 7 bytes by using truthyness of next array item, preventing calls to `count`, which is a way too long name for codegolf
> 1 votes

# Answer
## APL, ~~17 bytes~~ 15 bytes

```
{⍵×(⌽∨⊖)1∊¨⍳⍴⍵}

```

### How it works

* `⍳⍴⍵` generates a 2D array where all the cells contain the coordinates of all the cells of the argument.
* `1∊¨` searches in each such cell if there's a 1 and returns a 1 if so, or 0 otherwise. This builds a matrix where the first row and the first column are 1s and all the rest are 0.
* `(⌽∨⊖)` combines with logical "or" two version of the matrix, one reversed along the first and one reversed along the last axis.
* `⍵×` is the standard multiplication.
> 1 votes

# Answer
# APL (Dyalog Classic), 12 bytes

```
⊢-(⍉0⍪1↓⌽)⍣4

```

Try it online!

`⍉⌽⍵` is normally rotation (reverse horizontally and transpose)

here we combine it with `0⍪1↓⍵` which replaces the first row with zeroes (drop one row, then concatenate 0 on top) into a single train: `⍉0⍪1↓⌽`

`⍣4` repeats 4 times

`⊢-` subtracts from the original matrix
> 1 votes

# Answer
# 05AB1E, 11 bytes

```
4FøεNĀ*}R}^

```

Try it online or verify all test cases.

**Explanation:**

```
4F       }    # Loop 4 times:
  ø           #  Transpose/zip; swapping rows/columns
   ε   }      #  Map over the matrix (takes the input implicitly in the first iteration)
    NĀ        #   Trutify the index (0 remains 0; everything else becomes 1)
      *       #   Multiply all values in the current row of the matrix with it
        R     #  Reverse the matrix
          ^   # Bitwise-XOR the resulting matrix with the (implicit) input-matrix
              # (and output implicitly)

```

**Example run:**

```
Input:       [[67,4,-8,5,13],[9,13,42,4,-7],[1,1,3,-9,29],[16,99,8,77,0]]

Iteration 1:
 Zip:         [[67,9,1,16],[4,13,1,99],[-8,42,3,8],[5,4,-9,77],[13,-7,29,0]]
 Map:         [[0,0,0,0],[4,13,1,99],[-8,42,3,8],[5,4,-9,77],[13,-7,29,0]]
 Reverse:     [[13,-7,29,0],[5,4,-9,77],[-8,42,3,8],[4,13,1,99],[0,0,0,0]]

Iteration 2:
 Zip:         [[13,5,-8,4,0],[-7,4,42,13,0],[29,-9,3,1,0],[0,77,8,99,0]]
 Map:         [[0,0,0,0,0],[-7,4,42,13,0],[29,-9,3,1,0],[0,77,8,99,0]]
 Reverse:     [[0,77,8,99,0],[29,-9,3,1,0],[-7,4,42,13,0],[0,0,0,0,0]]

Iteration 3:
 Zip:         [[0,29,-7,0],[77,-9,4,0],[8,3,42,0],[99,1,13,0],[0,0,0,0]]
 Map:         [[0,0,0,0],[77,-9,4,0],[8,3,42,0],[99,1,13,0],[0,0,0,0]]
 Reverse:     [[0,0,0,0],[99,1,13,0],[8,3,42,0],[77,-9,4,0],[0,0,0,0]]

Iteration 4:
 Zip:         [[0,99,8,77,0],[0,1,3,-9,0],[0,13,42,4,0],[0,0,0,0,0]]
 Map:         [[0,0,0,0,0],[0,1,3,-9,0],[0,13,42,4,0],[0,0,0,0,0]]
 Reverse:     [[0,0,0,0,0],[0,13,42,4,0],[0,1,3,-9,0],[0,0,0,0,0]]

Bitwise-XOR:  [[67,4,-8,5,13],[9,0,0,0,-7],[1,0,0,0,29],[16,99,8,77,0]]

```
> 1 votes

# Answer
## Perl, 34 + 2 = 36 bytes

```
next if$.==1||eof;s/ .+?(?= )/ 0/g

```

Requires the `-p` flag:

```
$ perl -pE'next if$.==1||eof;s/ .+?(?= )/ 0/g' <<< $'1 2 3\n4 5 6\n7 8 9'
1 2 3
4 0 6
7 8 9

```

How it works:

```
# '-p' Read each line into `$_` and auto prints
next if$.==1||eof; # `$.` is set to to the current line in file (1, 2, ..., n)
                   # and `eof` is true if its the last line
s/ .+?(?= )/ 0/g

```
> 0 votes

# Answer
# Lua, 69 bytes

```
function f(a)for i=2,#a-1 do
for o=2,#a[i]-1 do
a[i][o]=0
end
end end

```

If only I had curly braces instead of dos and ends...
> 0 votes

# Answer
# SmileBASIC, ~~69~~ 51 bytes

```
DEF H A,W,H
FOR I=1TO H-2FILL A,0,W*I+1,W-2NEXT
END

```

~~Filling a 2D area in an array usually would require using FILL in a loop. But it's much easier to work with 2D data on the graphics page, so first the array is copied there.~~

Aww I thought I was so clever using graphics commands... but it turns out calling FILL a bunch of times is actually shorter.

Anyway, function inputs are the array and width/height (This is standard in Smilebasic because there's no way to check the dimensions of an array.)
> 0 votes

# Answer
**Python 3, 106 bytes**

```
lambda a:[[a[x][y]*(not(0<x<len(a)-1and 0<y<len(a[0])-1))for y in range(len(a[0]))]for x in range(len(a))]

```
> 0 votes

# Answer
## Perl 6, 70 bytes

Whole program that reads columns separated by a space and rows separated by newline. Inplace replacement humbly stolen from b2gills.

```
my @a=lines.map:{[.split(' ')]};{.[1..*-2]»[1..*-2] »=»0}(@a);dd @a

```
> -3 votes

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


title: Tips for golfing in Lisp

text:
# Question
Title: Tips for golfing in Lisp
What general tips are these for golfing in Lisp (any dialect)? Please post one tip per answer, and only answers that are specific to a dialect of Lisp (e.g. "remove comments" is not an answer).

Please post the dialect of Lisp your tip applies to with your tip.

# Answer
# Order function parameters to minimize whitespace

Instead of

```
(defun f(a b)(...))
...
(f x(1+ y))

```

try something like

```
(defun f(b a)(...))
...
(f(1+ y)x)

```
> 4 votes

# Answer
# Conditional Output

*GNU Common Lisp*

### `~v^`

The *up-and-out* directive `~^` is most commonly used in a list formatting operation to terminate after the last list item. However, it can also be used with a `v` modifier to consume an argument, in which case it terminates if that argument is zero. This is particularly useful for dealing with the zero produced by `dotimes`.

```
(loop as n from 1 to 10 do(format t"~d~%"n))

(dotimes(n 11)(if(> n 0)(format t"~d~%"n)))

(dotimes(n 11)(format t"~v^~d~%"n n))

```

---

### `format(condition)`

The first argument to `format` can be one of `t`, `nil` a.k.a. `()`, or a stream. If passed `t`, it will output to `stdout`, if `nil` it will return the formatted output as a string. This can be used conditionally output. The above example could be written equally as short as:

```
(dotimes(n 11)(format(> n 0)"~d~%"n))

```

If a value was output, the return value will be `nil`. Because of this, it can also be used as the terminating condition for a `do` loop:

```
(do((n 11))((<(decf n)1))(format t"~d~%"n))

(do((n 11))((format(>(decf n)0)"~d~%"n)))

```

---

### `~[...~]`

The conditional formatter consumes an argument, and selects a formatting string from a list by index. A common use case is with the default formatter `~:;` to select between zero and not zero.

```
(dotimes(n 11)(format t"~v^~[~r~:;~d~]~%"n(mod n 3)n))

```

Conditional formatters can also be nested, in which case each will consume an argument in turn.

---

### `~&`

In each of the examples above, `~%` is used to emit a newline. In most cases, this could be replaced by a literal newline. Another option is to use `~&`, which will emit a newline if and only if the output cursor is not at the start of a line, a.k.a. a `fresh-line`.

Both `~%` and `~&` can also take an argument, with a `v` modifier or as a constant, and will produce as many newlines. They will also both happily accept a negative argument, in which case they emit nothing.

---

### External References

*Practical Common Lisp*
18. A Few FORMAT Recipes

*Common Lisp the Language, 2nd Edition*
22.3.3. Formatted Output to Character Streams
> 4 votes

# Answer
Use `loop` and `format`, which is like `printf` on steroids. `format` includes iteration and conditions, as well as roman numerals, English numbers and English plurals. It is very, very ugly, and very compact.
> 2 votes

# Answer
# Print strings consisting of capital letters via printing atoms

The `princ` function in Common Lisp is short, and will print objects without escape characers. If you print Common Lisp symbols, which have the synax `'symbol-name`, this saves you from needing quotes around what you want to print, and can also save on whitespace. Note that when printing symbols, they will be capitalized. Also, it does not add a newline or a space, so you don't need concatenation.

For example,

```
(princ'hai)

```

will print `HAI`.

And

```
(princ'hai)(princ(read))

```

will print `HAI`, ask for input, and print it back out, e.g. if you type hello, the result is

```
HAIhellohello

```
> 1 votes

# Answer
# Use `1+` and `1-` for increment and decrement

Instead of `(+ a 1)` or `(- b 1)` try `(1+ a)` or `(1- b)`.
> 1 votes

---
Tags: code-golf, tips, lisp
---


title: Convert a number to Korean

text:
# Question
Title: Convert a number to Korean
# Goal

You will be given a positive integer number less than 10^20. You must convert it to Korean.

For example, if the input is `12345`, the output should be `일만이천삼백사십오`.

# Technical details (Small)

Let's starts with simple numbers.

```
// 1 - 9
1 -> 일
2 -> 이
3 -> 삼
4 -> 사
5 -> 오
6 -> 육
7 -> 칠
8 -> 팔
9 -> 구

// 10, 100, 1000
10 -> 십
100 -> 백
1000 -> 천

```

You can concatenate `2` ~ `9` front of `10`, `100`, `1000`.
However, you should not concatenate `1` front of `10`, `100`, `1000`.

```
// 20 = 2 * 10
20 -> 이십

// 300 = 3 * 100
300 -> 삼백

// 9000 = 9 * 1000
9000 -> 구천

// 1000 is just 1000
1000 -> 천

```

For integer less than 10000, below rule is used for pronunciation.

```
// 1234 = 1000 + 200 + 30 + 4
1234 -> 천이백삼십사

// 1002 = 1000 + 2
1002 -> 천이

// 2048 = 2000 + 40 + 8
2048 -> 이천사십팔

// 510 = 500 + 10
510 -> 오백십

// 13 = 10 + 3
13 -> 십삼

```

# Technical details (Large)

Now let's go to the hard part.

First, you need to know some parts used in larger numbers:

```
1 0000 -> 만
1 0000 0000 -> 억
1 0000 0000 0000 -> 조
1 0000 0000 0000 0000 -> 경

```

When Koreans pronounce big numbers

1. Cut it with width 4
2. Convert each of them using methods for less than 10000
3. Combine them with default form of big numbers

Here is some detailed examples. (I added some space to korean for readability)

```
// 12345678 = 1234 5678
// 1234 -> 천이백삼십사
// 5678 -> 오천육백칠십팔
12345678 -> 천이백삼십사 만 오천육백칠십팔

// 11122223333 = 111 2222 3333
// 111 -> 백십일
// 2222 -> 이천이백이십이
// 3333 -> 삼천삼백삼십삼
11122223333 -> 백십일 억 이천이백이십이 만 삼천삼백삼십삼

// 10900000014 = 109 0000 0014
// 109 -> 백구
// 0000 -> (None)
// 0014 -> 십사
10900000014 -> 백구 억 십사

// 100000000 -> 1 0000 0000
// 1 -> 일
// 0000 -> (None)
// 0000 -> (None)
100000000 -> 일 억

```

Here are some more examples.

# Rule

You can make your program gets input from `stdin` and output to `stdout`, or make a function that gets string/integer and returns string.

This is , so answers will be scored in bytes with fewer bytes being better.

# Answer
# Aheui, 1555 bytes

```
살밦발따밝따빠따밦발다빠따다빠밞빠따받다빠따밝발따두
수터더떠벋벓떠뻐더벖떠뻐벍뻐터터떠벌벖떠뻐떠벋벎뻐더
방뺘우차빠발발다빠따빠뚜
우노여뗘뻐떠뻐더벌벌썪러
샦우싹어
아삳부
ㅇ아삭뺘우차빠불
ㅇ유어우여려더벌
ㅇ요ㅇ빠받반타탸우처삳뺘우처밝밤뚜
ㅇㅇ우쑨여텨여볋여뗘여뼈여뎌벅떠벓
ㅇ요아삭뺘우차삳빠박탸유처발불
ㅇㅇ우어ㅇ여따뱖볆뚜텨벎떠뻐떠
ㅇ요ㅇ우어쎤여뎌여별여어
ㅇㅇㅇ빠밤탸우처밣빠따밞다뿌
ㅇ요ㅇ우어쎤여뗘벎더떠벋벓떠
ㅇㅇㅇ빠밦탸우처밞밦따빠뚜
ㅇ뇨ㅇ숙어쎤여뗘벎떠벅터벖
ㅇㅇㅇ빠박탸우처밝밤따밣따북
ㅇ됴ㅇ우어썬여텨더벓벓떠뻐더
ㅇㅇㅇ빠받탸우처밣밝다빠따붇
ㅇ뵬ㅇ우어썬여뎌떠벍벓떠뻐터
ㅇㅇㅇ빠밤탸우처밣밝다빠따붇
ㅇ뵬ㅇ우어썬여뎌떠벌벓떠뻐터
ㅇㅇㅇ빠발탸우처밣밝다빠따뿌
ㅇ묘ㅇ우어썬여뎌떠벎더벌벖떠
ㅇㅇㅇ빠밦탸우처밣밝다빠따빠뚜
ㅇ쇽ㅇ우어썬여뎌떠벓더벓떠뻐벖
ㅇㅇㅇ빠밝탸우처밞밞따빠따붒
ㅇ됴ㅇ우어썬여뗘벓더더벍떠뻐
ㅇㅇㅇ빠밣탸우처발발따발따붒
ㅇ뵥ㅇ우어썬여뗘벎더범떠벓떠
ㅇㅇㅇ빠밟탸우처밝발따빠따붏
ㅇ숃어어어쎤여뎌벓떠벎떠범더
ㅇ마샬우싹샥우파뺘무차파쑨
ㅇㅇ오유여어유여ㅇ며ㅇㅇ우
오ㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇ어
우ㅇㅇ어ㅇㅇ어어
샨희맣어

```

**Try it online!** (trailing new line for input is necessary)

Why not?

Hours of coding, and another hours of packing and layouting. I think it can be golfed furthermore, but it already took so much effort. I really wanted to pack it into a rectangle.

Because 10^20 is larger than 2^64, not every implementation of Aheui will not support 경-scale numbers.
Luckily, Python and pyaheui implementation (which is used on TIO) uses much-larger precision numbers, so it can support not only 경, but more than 해, 자, 양, 구, 간, 정, 재, 극.
And my code can be *easily* extended to use more larger unit suffixes.

This code will not terminate on input `0`, but this spec was not defined in the question (which should output ).

# Explanation-ish Unpacked Code

```
ㅣPush unit suffixes (만, 억, 조, 경) to stack ㄹ
ㅣ
술
밦발따밝따빠따밦발다우
우ㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
빠따다빠밞빠따받다빠따밝발따다다우
우ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
빠밞받따빠따밦발따타타우
우ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
빠밝빠따밦다빠따밣받따다타우
우ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣ
ㅣGet input as number
ㅣ
사방우
우ㅡ어
ㅣ
ㅣSplit input by four digits
ㅣ
ㅣㅣIf input is zero, end the loop
아아뺘우차우
우ㅇㅡ어　ㅣ
ㅣㅣ우ㅡㅡ어
ㅣㅣㅣTake mod 10000 to stack ㄲ
ㅣㅣ빠발발다빠따빠따라싺우
ㅣㅣ우ㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣDivide by 10000
ㅣㅣ발발다빠따빠따나우
ㅣ오ㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣ
ㅣReverse stack ㄲ to stack ㄱ
ㅣ
샦우싹어
우어
ㅣ
ㅣProcess four digits
ㅣ
아우ㅣUse ㄷ stack for index (0, 2, 4, 6)
ㅣ아삳바우
ㅣ우ㅡㅡ어
ㅣㅣ
ㅣㅣㅣConvert four digits into korean
ㅣ아아숙
ㅣㅣㅣㅣIf current multiplier is zero, escape
ㅣㅣㅣ뺘우차우
ㅣ우ㅇㅡ어　ㅣ
ㅣㅣㅣ우ㅡㅡ어
ㅣㅣㅣㅣTake mod 10
ㅣㅣㅣ빠발발다라우
ㅣㅣㅣ우ㅡㅡㅡㅡ어
ㅣㅣㅣㅣIf remainder - 1 is 0 (remainder is 1) and index is 0 (ones digit), push 일 on stack ㄴ
ㅣㅣㅣ빠받반타탸우처삳뺘우처밝밤따밣따박다빠따밣타싼우
ㅣㅣㅣ우ㅡㅡㅡㅡ어ㅡㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣIf remainder is not 0
ㅣㅣㅣ삭뺘우차우
ㅣㅣㅣ우ㅡ어　ㅣ
ㅣㅣㅣㅣ우ㅡㅡ어
ㅣㅣㅣㅣ숟
ㅣㅣㅣㅣㅣIf index is [2, 4, 6], push [십, 백, 천] on stack ㄴ
ㅣㅣㅣㅣ빠박탸우처발발따빠따밞타밞따밞따발다싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠밤탸우처밣빠따밞다빠따밣받따다밞따싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠밦탸우처밞밦따빠따밦타박따밞따싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣㅣ
ㅣㅣㅣㅣㅣIf remainder is [2 ... 9], push [이 ... 구] on stack ㄴ
ㅣㅣㅣㅣ숙
ㅣㅣㅣㅣ빠박탸우처밝밤따밣따박다빠따밣밣다타싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠받탸우처밣밝다빠따받타빠따밣밝따다싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠밤탸우처밣밝다빠따받타빠따밣발따다싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠발탸우처밣밝다빠따빠따밦발다밞따다싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠밦탸우처밣밝다빠따빠따밦빠따밣다밣따다싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠밝탸우처밞밞따빠따밦빠따밝다다밣따싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠밣탸우처발발따발따밦따밣따밤다밞따싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠밟탸우처밝발따빠따밣다밤따밞따밣다싼우
ㅣㅣㅣ우ㅡㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ
ㅣㅣㅣㅣIncrease index, move onto next digit
ㅣㅣㅣ삳박다삭마발발다나우
ㅣㅣ오ㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣ
ㅣㅣㅣPop zero
ㅣ아무
ㅣㅣㅣ
ㅣㅣㅣㅣMove one suffix to stack ㄱ
ㅣㅣㅣㅣIf all suffix has been used, escape
ㅣㅣ아샬우싹삭우
ㅣ우ㅇㅡ어　　ㅣ
ㅣㅣㅣ우ㅡㅡㅡ어
ㅣㅣㅣㅣIf next multiplier is zero, discard next multiplier and suffix, then check next
ㅣㅣㅣㅣIf next multipler is not zero, move suffix to stack ㄴ and continue
ㅣㅣㅣㅣIf all multiplier has been processed, escape
ㅣㅣㅣ야우파뺘우차파싼우
오ㅇㅇㅡㅇㅡㅡㅇㅡㅡㅡ어
우어ㅇㅡ어ㅡㅡㅣ
ㅣㅡ오ㅡㅡ머머어
샨희맣어

```
> 9 votes

# Answer
# Retina 0.8.2, 147 bytes

```
^
0경0조0억0만
\G0?\D?
0천0백0십$&
+`0(\D)(\d+)(\d)
$2$1$3
0(천0백0십0.?|천|백|십)

1(천|백|십)
$1
T`d`_일이삼사오육칠팔구

```

Try it online! Link includes test cases. Explanation:

```
^
0경0조0억0만

```

Insert the symbols for powers of 10,000.

```
\G0?\D?
0천0백0십$&

```

Insert the thousands, hundreds and tens symbols.

```
+`0(\D)(\d+)(\d)
$2$1$3

```

Replace the zeros between the symbols with the input digits.

```
0(천0백0십0.?|천|백|십)

```

Delete zero thousands, hundreds or tens, or a whole power of 10,000.

```
1(천|백|십)
$1

```

Delete the 1 of one thousand, one hundred or one ten.

```
T`d`_일이삼사오육칠팔구

```

Transliterate the remaining digits, deleting any remaining zeros.
> 4 votes

# Answer
# Jelly,  ~~96 95 94~~  92 bytes

```
“Ŀ|ĿtĊỴĊḄİ$Ŀ!Ṫ`ạÞḌlĖḣỴ1ṘƈỤṘḢỌṀpḄẒ‘s2ḅ⁹Ọ
bȷ4DUµż“¢½¿€‘ṁ$Ṛœl€1P€0¦ẠÐfFµ€Ṛµ;"“¡ÆÇÐÑ‘ṚL’$ÐfFḟ0ị¢

```

A monadic link taking a positive integer and returning a list of characters.

**Try it online!** or see a test-suite (numbers referenced in the OP)
...or see assertion of the pastebin values here

### How?

Constructs the parts-characters required as indexes of the list:

```
[1,2,3,4,5,6,7,8,9,10,100,1000,10000,100000000,1000000000000,10000000000000000]
i.e.: 일이삼사오육칠팔구십백천만억조경

```

and indexes into the list. Thus `30210` would become `[3,13,2,11,10]` and then `삼만이백십`

```
“Ŀ|ĿtĊỴĊḄİ$Ŀ!Ṫ`ạÞḌlĖḣỴ1ṘƈỤṘḢỌṀpḄẒ‘s2ḅ⁹Ọ - Link 1, get part-characters: no arguments
“Ŀ|ĿtĊỴĊḄİ$Ŀ!Ṫ`ạÞḌlĖḣỴ1ṘƈỤṘḢỌṀpḄẒ‘      - code-page indices = [199,124,199,116,192,188,192,172,198,36,199,33,206,96,211,20,173,108,194,237,188,49,204,156,185,204,197,181,200,112,172,189]
                                  s2    - split into twos = [[199,124],[199,116],[192,188],[192,172],[198,36],[199,33],[206,96],[211,20],[173,108],[194,237],[188,49],[204,156],[185,204],[197,181],[200,112],[172,189]]
                                    ḅ⁹  - convert from base 256 = [51068,51060,49340,49324,50724,50977,52832,54036,44396,49901,48177,52380,47564,50613,51312,44221]
                                      Ọ - cast to characters = "일이삼사오육칠팔구십백천만억조경"

bȷ4DUµż“¢½¿€‘ṁ$Ṛœl€1P€0¦ẠÐfFµ€Ṛµ;"“¡ÆÇÐÑ‘ṚL’$ÐfFḟ0ị¢ - Main link: integer, n     e.g. 102031
 ȷ4                                                  - 10^4 = 10000
b                                                    - convert (n) to base (10000)    [10,2031]
   D                                                 - convert (each) to base 10      [[1,0],[2,0,3,1]]
    U                                                - reverse each                   [[0,1],[1,3,0,2]]
     µ                      µ€                       - monadic chain for €ach:
              $                                      -   last two links as a monad:
       “¢½¿€‘                                        -     code-page indices = [1,10,11,12]
             ṁ                                       -     mould like             e.g. [1,10] or [1,10,11,12]
      ż                                              -   zip                   [[0,1],[1,10]] or [[1,1],[3,10],[0,11],[2,12]]
               Ṛ                                     -   reverse               [[1,10],[0,1]] or [[2,12],[0,11],[3,10],[1,1]]
                œl€1                                 -   left-strip ones         [[10],[0,1]] or [[2,12],[0,11],[3,10],[]]
                    P€0¦                             -   product @ index 0           [[10],0] or [[2,12],[0,11],[3,10],1]  (Note: the empty product is 1)
                        ẠÐf                          -   filter keep if any            [[10]] or [[2,12],[3,10],1]
                           F                         -   flatten                         [10] or [2,12,3,10,1]
                              Ṛ                      - reverse                        [[2,12,3,10,1],[10]]
                               µ                     - new monadic chain
                                  “¡ÆÇÐÑ‘            - code-page indices = [0,13,14,15,16]
                                ;"                   - zip with concatenation         [[2,12,3,10,1,0],[10,13],14,15,16]
                                         Ṛ           - reverse                        [16,15,14,[10,13],[2,12,3,10,1,0]]
                                             Ðf      - filter keep if:
                                            $        -   last two links as a monad:
                                          L          -     length                      1  1  1   2      6
                                           ’         -     decrement                   0  0  0   1      5
                                                     -                           i.e. [[10,13],[2,12,3,10,1,0]]
                                                     -     (This also removes any 0-sized 10K parts e.g. the [13] from 200001234 -> [16,15,[2,14],[13],[12,2,11,3,10,4,0]])
                                               F     - flatten                        [10,13,2,12,3,10,1,0]
                                                ḟ0   - filter discard zeros           [10,13,2,12,3,10,1]  (Note: not there for multiples of 10000 so cann't simply pop with Ṗ)
                                                   ¢ - call the last link as a nilad  "일이삼사오육칠팔구십백천만억조경"
                                                  ị  - index into                     "십만이천삼십일"

```
> 4 votes

# Answer
# Ruby, 158 bytes

This task has been haunting me for a few days, but after several iterations of tinkering with the code and gaining max 1-2 bytes at a time, I think it isn't going to become much shorter than this, unless somebody points out a conceptually different approach.

```
->n{i=0;n.digits.map{|d|'-만억조경'[i%4>0?'':i/4]+'천-십백'[(i+=1)%4]+'0일이삼사오육칠팔구'[d]}.join.reverse.gsub /(0.){4}.|0.|일(?!-)|-/,''}

```

Try it online!

## Explanation

Takes input as integer and extracts the digits (listed from the least to most significant) using the convenient built-in available since Ruby 2.4.

Then, we combine the corresponding Korean digits with position markers and where necessary, 104 block markers. `-` is a placeholder for the missing markers of lower digits. `천-십백` has such strange ordering because it is rotated by one place to compensate for the fact that we are also incrementing the counter `i` in the same step.

Finally, we reverse the resulting string back to normal direction and remove some redundant stuff with RegEx replacements:

* `(0.){4}.` : 4 * (0+marker) + another marker = a completely empty 104 block.
* `0.` : zeroes at any single position
* `일(?!-)` : ones followed by any meaningful (non-placeholder) markers
* `-` : finally, get rid of the placeholders themselves

## Alternative

Interestingly, a similar approach, but working with string input is just 1 byte longer:

```
->s{i=s.size;s.chars.map{|c|'0일이삼사오육칠팔구'[c.to_i]+'-십백천'[(i-=1)%4]+'-만억조경'[i%4>0?'':i/4]}.join.gsub /(0.){4}.|0.|일(?!-)|-/,''}

```

Try it online!
> 2 votes

# Answer
# Wolfram Language 23 bytes

Mathematica has a built-in for this. (What a surprise!)

```
IntegerName[#,"Korean"]&

```

To save one byte...

```
#~IntegerName~"Korean"&

```
> 2 votes

# Answer
# Haskell, 270 bytes

```
(0#_)_=""
(n#1)_=[" 일이삼사오육칠팔구"!!fromInteger n]
(n#b)(c:r)|d<-div n b=[k |d>1,k<-d#1$r]++[c |d>0]++(mod n b#div b 10)r
t=10^4
(n%1)_=f n
(n%b)(c:r)|d<-div n b=[k |d>0,k<-f d++[c]]++(mod n b%div b t)r
f n|n<t=n#1000$"천백십"|1>0=n%(t^4)$"경조억만"

```

Try it online!

This could probably be improved as there is a bit of duplication but I can't think of a good way of unifying the `#` and `%` operators.

Both of those operators work in a similar way but `#` is for `n<10^4` and `%` is for big numbers. They take the number `n`, the current "base" `b` and a list of characters representing the relevant powers of ten in decreasing order. First I divide `n` by `b` to get `d` and stick it's korean representation in front if it's greater than 1 (in the case of numbers less than ten thousand) or 0 (otherwise). Then I insert the representation of the power itself (which should correspond to `c`) if `d>0`. Then we just recur by modding `n` by `b` and dividing b down to get the base corresponding to the next character.

When we reach `n==1` in `#` We know it's down to a one digit number so we just index into a list (I need `fromInteger` because `Int` isn't large enough to store numbers as large as `10^20`). When `n==1` in `%` then `n` is now `<10^4` so we recur to `#` (via `f`) to do the rest of the number.
> 1 votes

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


title: Find the optimal nim move

text:
# Question
Title: Find the optimal nim move
# The game

Nim is a mathematical strategy game, where 2 players take turns taking items from distinct heaps. On your turn, you must take at least one item, and you may take as many as you want, provided that you only take from one heap. The player that takes the last item wins! This is a solved game. Before I go into the strategy, you can try playing it online here.

# The Strategy

The winning strategy is explained very clearly and simply here at this link. I will explain it using a little bit more technical terms. The way to win this game, is to always take as many items as possible so that the binary-digital-sum is always 0. Consider the following board:

```
         *
       * *
     * * *
   * * * *
 * * * * *
 1 2 3 4 5

```

To find the binary-digital-sum of this board, you must:

1. Convert the number in each row to binary. So we have 001, 010, 011, 100 and 101.
2. Add all the numbers together, and ignore any carrying.

```
 001
 010
 011
 100
+101
----
 001

```

You can also bitwise-xor each number, and this will achieve the same result.

Now, if the sum in this current configuration is 001, then this is not (yet) a winning board. But you can make it a winning board! If we take one item off of columns 1, 3 or 5, the sum will be 0. This is a winning board, which means that, provided you don't make a mistake, the next player to move will lose. So you must always end your turn with a winning board. Lets say you take one item off of column 5. Now the board looks like this:

```
       * *
     * * *
   * * * *
 * * * * *
 1 2 3 4 5

```

As long as you don't screw up, you have a guaranteed win. There is nothing your opponent can do to stop you. Lets say he takes all of the items from column 5.

```
       *
     * *
   * * *
 * * * *
 1 2 3 4 5

```

Where would you go next? Don't scroll down yet, and try to figure it out for yourself.

---

Right now, the sum is 100. The best move (and only winning move) would be to take everything from column 4. That would leave the board like this:

```
     *
   * *
 * * *
 1 2 3 4 5

```

and the sum like this

```
 001
 010
+011
----
 000

```

that means that you are in a winning board! Yay!

# The Challenge

You must write a program or function that, given a nim board, will return a winning move, or a falsey value if there is no winning move.

Your input:

* Will be your languages native list format, where each item in the list corresponds to the number of items in a given column. For example, the input {4, 2, 1, 0, 3} corresponds to the following nim board:

```
*
*           *
*  *        *
*  *  *     *
1, 2, 3, 4, 5

```
* (optional) The number of rows. (For languages like C/C++ where this is not known from the list itself.)

Your output:

* Can go to STDOUT or be returned from the function
* Must be two numbers, 1) the column we are removing from (Remember that the columns are 0-indexed) and 2) the number of items to remove from that row. This could be a 2-item array, a string of the two numbers, etc. Keep in mind that the answer might be more than 2 digits long, so returning the string "111" is not valid because it isn't clear if this means "Remove one item from column eleven" or "Remove eleven items from column one". "1,11" or "11,1" would both be acceptable.
* If there is no answer, return or print a falsy value. If your langauge can only return one type of variable (again, like C/C++), a negative number for the column, or 0 or less for the number to remove would both be acceptable falsey values.
* If the column number or number to remove are too large, this is seen as an invalid output.

# Sample Inputs/Outputs

`[1, 2, 3, 4, 5]` ---\> `[0, 1]` or `[4, 1]` or `[2, 1]`

`[1, 3, 5, 6]` ---\> `[0, 1]` or `[1, 1]` or `[2, 1]`

`[1, 2, 0, 0, 5]` ---\> `[4, 2]`

`[1, 2, 3]` ---\> `ERROR`

If you choose to do a function instead of full program, then you must write a full program to demonstrate the function in action. This will not count towards your full score. Also, programs are expected to run in a reasonable amount of time. I'm not planning to enter any excessively large inputs, so as long as your program isn't doing a brute force search over the entire game tree, you should be fine.

As usual, this is code-golf, so standard loop-holes apply, and answers are counted in bytes.

# Leaderboard

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

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

```
# Language Name, N bytes

```

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

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

```

```
var QUESTION_ID=52356;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
```

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

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

# Answer
> 3 votes
# Pyth, ~~33~~ ~~22~~ ~~21~~ ~~20~~ 19 bytes

```
eS.e*<JxxFQbb,k-bJQ

```

You can try it in the online compiler here.

Thank you to Jakube for removing 12 bytes and Maltysen for removing an additional byte!

This prints a winning move from the current position. If there are no winning moves, it doesn't print anything.

I used the algorithm on wikipedia. Here is the breakdown:

```
  .e              Q    While enumerating every element in the input:
      J                    Assign variable J to:
        xFQ                 Every element of the input bitwise xor'ed together,
       x   b                bitwise xor'ed with the current element of the input
             ,             Create a tuple containing:
              k             The index of the current element, and
               -bJ          the difference between the current element and J
    *<J     b              Put that tuple into a list if J < b, otherwise put an empty tuple
 S                     Sort the list
e                      Print the last element of the list

```

# Answer
> 3 votes
# Pyth, 23 bytes

```
eSs.em*,kd!xxxFQb-bdSbQ

```

Try it online: Demonstration

This iterates over all possible moves and even does sorting. Therefore it has a time-complexity of `O(N*log(N))` and a memory complexity of `O(N)`, where `N` is the sum of the input list or the number of items.

Because of the bad time complexity, this might not be a valid answer. Though it solves all games, that you can play in real life with real objects, instantly.

### Explanation:

```
                          implicit: Q = input list
   .e                 Q   map each (index k, item b) of Q to:
     m              Sb      map each d of [1, 2, ..., b] to:
       ,kd                      the pair (k, d)
      *                       multiplied by
             xFQ                xor of all numbers in Q
            x   b               xor with b
           x     -bd            xor with b-d
          !                     not (1 if xor==0 else 0)

So the input [1, 2, 0, 0, 5] gives [[[]], [[], []], [], [], [[], [4, 2], [], [], []]]

  s                       add all lists to one big list
 S                        sort

Now it looks like this: [[], [], [], [], [], [], [], [4, 2]]

e                         pick the last element and print

```

# Answer
> 3 votes
# CJam, ~~21~~ 20 bytes

Saved a byte compared to original version, and error handling also works now:

```
l~__:^f^.-_:g1#_@=S\

```

Try it online

Input is a CJam array, e.g.:

```
[1 2 3 4 5]

```

If no solution is found, it prints `-1 0`, which meets my understanding of the output requirements.

Explanation:

```
l~      Get input.
__      Make two copies for following operations.
:^      Reduce with xor operator, producing xor of all columns.
f^      xor all input values with the result. For each column, this calculates
        the value that the column would have to change to make the overall
        xor zero. Consider this the "target values".
.-      Subtract the target values from the input values.
_:g     Per element signum of difference between target value and input value.
1#      Find index with value 1, which is the first positive value.
_@=     Get the value at the index.
S\      Put a space between index and value.

```

# Answer
> 1 votes
# Ruby, 95

```
->(a){r=[false,c=0]
a.each{|e|c^=e}
a.each_index{|i|(n=a[i]-(c^a[i]))>0&&n>r[1]?(r=[i,n]):0}
r}

```

I wrote 2 separate anonymous functions. The first, assigned to `f` in the program below, **prints** all solutions, and the second `g` (corresponding to the score above, as it is both shorter and more compliant with the spec) **returns** only the solution which requires removing the greatest number.

in both cases, the digit sum is totalized in `c`. Then the array is looped over and the expression `n=a[i]-(c^a[i])` is used to calculate the number of counters to be removed (obviously this can only be done if it exceeds zero).

in `f`, all possible solutions are printed (if `c` is found to be `0`, `error` is printed without looping.) I was surprised to see that the different piles can require quite different numbers of counters to be removed.

in `g` the output array `r` is only updated if the number of counters to be removed exceeds the previous number. the array r=`[pile index, number to be removed]` is returned. If there is no solution, the number of counters to be removed is always zero, `r` remains unchanged, and the initial value of r=`[false,0]` is returned.

Minor savings are possible if `false` can be changed to for example`"!"` and if any valid solution rather than the largest one can be returned (by deleting `&&n>r[1]`.)

**Formatted in test program**

```
f=->(a){
  c=0
  a.each{|e|c^=e}
  c<1?(p "error"):(a.each_index{
     |i|(n=a[i]-(c^a[i]))>0?(p"#{i},#{n}"):0
   })
}

g=->(a){
  r=[false,c=0]
  a.each{|e|c^=e}
  a.each_index{
     |i|(n=a[i]-(c^a[i]))>0&&n>r[1]?(r=[i,n]):0
  }
  r
}

#Change the following two lines according to the number of values youj want to use for testing.
t=[rand(15),rand(15),rand(15),rand(15)] #Generate some random numbers for testing.
t=[gets.to_i,gets.to_i,gets.to_i]       #User input. Delete this line if you want to test with random numbers.
print t,"\n"

f.call(t)
puts g.call(t)

```

# Answer
> 0 votes
## Mathematica, 73 bytes

```
{f=BitXor;p=Position[#,x_/;BitAnd[x,a=f@@#]==a][[1,1]],(n=#[[p]])-n~f~a}&

```

# Answer
> 0 votes
# JavaScript (ES6), 54 bytes

Returns either the pair `[column, number]` or *false*

```
a=>a.some((n,i)=>r=(n-=n^eval(a.join`^`))>0&&[i,n])&&r

```

Try it online!

### Commented

```
a =>                        // a[] = input array
  a.some((n, i) =>          // for each value n at position i in a[]:
    r = (                   //   save the result of the iteration in r
      n -=                  //   subtract from n:
        n ^ eval(a.join`^`) //     n XOR (all values in a[] XOR'ed together)
    ) > 0                   //   if the above value is positive:
    && [i, n]               //     yield the solution [i, n] and exit the some() loop
                            //   (otherwise: yield false and go on with the next value)
  ) && r                    // end of some(); return r

```

---
Tags: code-golf, game
---