title: Keyboard layouts challenge

text:
# Question
Title: Keyboard layouts challenge
The keyboard layout people commonly use is the **QWERTY** layout as shown below.

But there are also other keyboard layouts:

**DVORAK**

**COLEMAK**

**WORKMAN**

## Your task

Your code will take two inputs: the name of the keyboard layout and a string to transcribe. Your goal is to convert your QWERTY input as if you were typing with the keyboard layout given as first parameter.

### Rules

The input format is free, you can use strings, arrays, etc. Moreover, you can use any three distinct values to represent the layouts to reduce your byte count, but they each have to be representable in 10 bytes or less.

You need only to handle the keys with a white background. Specifically, you must transpose the printable ASCII characters from the QWERTY alphabet to one of the other alphabets:

```
 QWERTY: !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
 DVORAK: !_#$%&-()*}w[vz0123456789SsW]VZ@AXJE>UIDCHTNMBRL"POYGK<QF:/\=^{`axje.uidchtnmbrl'poygk,qf;?|+~
COLEMAK: !"#$%&'()*+,-./0123456789Oo<=>?@ABCSFTDHUNEIMKY:QPRGLVWXJZ[\]^_`abcsftdhuneimky;qprglvwxjz{|}~
WORKMAN: !"#$%&'()*+,-./0123456789Ii<=>?@AVMHRTGYUNEOLKP:QWSBFCDXJZ[\]^_`avmhrtgyuneolkp;qwsbfcdxjz{|}~

```

(Note: this was transcribed by hand by @ETHproductions, so if you see any errors, please point them out!)

### Example

`DVORAK zZxX` as input will give as output `;:qQ`

This is so the shortest answer in bytes wins!

# Answer
# Ruby, ~~258~~ ~~247~~ 238 bytes

```
->c,t{c.tr"#{$f='\'"+,-./<=>?[]{'}}:;B-Z_b-z",%W(-_}w[vzW]VZ/=?+SsXJE>UIDCHTNMBRL"POYGK<QF:{xje.uidchtnmbrl'poygk,qf;
#$f}OoBCSFTDHUNEIMKY:QPRGLVWXJZ_bcsftdhuneimky;qprglvwxjz
#$f}IiVMHRTGYUNEOLKP:QWSBFCDXJZ_vmhrtgyuneolkp;qwsbfcdxjz)[t]}

```

Try it online!

This is a function taking two arguments: the message to be swapped, and a value 0-2 representing the layout to be swapped to, where 0 corresponds to Dvorak, 1 to Colemak, and 2 to Workman.

Fundamentally, I don't think this is much different than the other answers. More readably, it looks like this:

```
def swap_layout(message, layout)
    keyboards = [DVORAK, COLEMAK, WORKMAN] # Omitted here for brevity
    return message.tr(QWERTY, keyboards[layout])
end

```

Ruby's `string#tr` function takes two arguments: a string containing characters to be replaced, and a string containing their replacements. Helpfully, it allows you to specify ranges of characters using `a-z` syntax. The other key space-saving realization is that it's not necessary to include characters that are the same in all four layouts, which allowed me to get rid of all digits, the letter "A" in both upper- and lowercase, and a handful of special characters.

One other weird bit of syntax is the use of `%W()`. This creates an array of strings containing everything inside the parentheses, separated by whitespace. All linebreaks in the submission actually function as element separators. `%W()` also permits string interpolation (which is done with the `#{}` operator) - `%w()` would've been the same thing, but without string interpolation.

I'd also like to take a moment to blame Dvorak for messing with my plans for optimization through its insistence on being totally different than everyone else, all the time; a Qwerty/Colemak/Workman solution could have been so beautifully short...
> 3 votes

# Answer
# JavaScript (ES7), ~~282~~ ~~273~~ ~~251~~ 250 bytes

Takes a keyboard layout ID `k` and an array of characters `a` in currying syntax `(k)(a)`. Returns an array of translated characters.

The layout IDs are:

* DVORAK: \\$-32\\$
* COLEMAK: \\$64\\$
* WORKMAN: \\$160\\$

```
k=>a=>a.map(c=>1/(t=`1_3-2}w[vz8SsW]VZ1XJE>UIDCHTN0BRL"POYGK<QF:/0=0{1xje.uidchtn0brl'poygk,qf;?0+995Oo6SFTD0UNEI0KY:0PRGL2J8sftd0unei0ky;0prgl2j998Ii5VMHRT0YUNEOLKP:0W0BFCD0J6vmhrt0yuneolkp;0w0bfcd0j5`.replace(/\d/g,n=>15**n)[c.charCodeAt()+k])?c:t)

```

Try it online!

### How it works

**Compression**

All three target layouts are stored in a single compressed string, where each character is either:

* a translation character from QWERTY
* a digit representing the number of consecutive characters that do not need to be translated

More specifically, a digit \\$n\\$ is interpreted as the length of the number \\$15^n\\$ in base \\$10\\$:

```
n | 15**n       | length
--+-------------+-------------
0 | 1           | 1
1 | 15          | 2
2 | 225         | 3
3 | 3375        | 4
4 | 50625       | 5 (not used)
5 | 759375      | 6
6 | 11390625    | 8
7 | 170859375   | 9 (not used)
8 | 2562890625  | 10
9 | 38443359375 | 11

```

For instance, `#$%&-()*` in DVORAK is stored as `3-2` because `#$%&` and `()*` have identical mappings in QWERTY and only `-` is an actual translation.

In particular, `0123456789` is mapped the same way on all layouts and never has to be translated. Therefore, there's no possible ambiguity between a digit used for compression and a digit used for translation.

**Decompression**

To decompress the layout string, we replace each digit \\$n\\$ with \\$15^n\\$. For instance, `3-2` is decompressed as `3375-225`.

**Translation**

For each character `c` in `a`, we extract the translation character `t`, using `k` as an offset in the uncompressed layout string, and test whether it's a digit with `1/t`. If so, we output the original character `c` instead.
> 6 votes

# Answer
# Retina, ~~273~~ 270 bytes

```
T`p` !_#-&\-()*}\w[vzdSsW]VZ@AXJ\E>UIDC\HTNMBR\L"P\OYGK<QF:/\\=^{\`axje.ui\dc\htnmbr\l'\p\oygk,qf;?|+~`^D.*
T`p` -9\O\o<-CSFTD\HUN\EIMKY:QPRG\LVWXJZ-csft\d\huneimky;q\prg\lv-xjz-~`^C.*
T`p` -9Ii<-AVM\HRTGYUN\E\O\LKP:QWSBFCDXJZ-avm\hrtgyune\o\lk\p;q\wsbfc\dxjz-~`^W.*
^.

```

Try it online! Prefix the message with a single letter `D`, `C` or `W` for the desired keyboard layout. Unfortunately Retina supports a bunch of magic letters (`p` being the obvious one, but I did manage to slip in a `d`) which all need to be quoted, except I was able to use `v-x` instead of `v\wx`. Edit: Saved 3 bytes thanks to @ETHproductions.
> 4 votes

# Answer
# PHP, 364 Bytes

```
echo strtr($argv[2],($t=[[":;BCDEFHIJKLMNOPRTUVWYbcdefhijklmnoprtuvwy","IiVMHRTYUNEOLKP:WBFCDJvmhrtyuneolkp;wbfcdj"],[":;DEFGIJKLNOPRSTUYdefgijklnoprstuy","OoSFTDUNEIKY:PRGLJsftduneiky;prglj"],["\"'+,-./:;<=>?BCDEFGHIJKLNOPQRSTUVWXYZ[]_bcdefghijklnopqrstuvwxyz{}","_-}w[vzSsW]VZXJE>UIDCHTNBRL\"POYGK<QF:/={xje.uidchtnbrl'poygk,qf;?+"]][ord($argv[1])%3])[0],$t[1]);

```

Array contains 3 arrays where key stands for 0=W, 1=C, 2=D

Try it online!
> 3 votes

# Answer
## Python 2, 422 bytes

Tried to combine layouts with some clever way, but it didn't help much.
Try it online

```
from string import*
Q=' '+printable
D=' '+digits
p,P=punctuation.split(':;')
w='avmhrtgyuneolkp;qwsbfcdxjz'
c='abcsftdhuneimky;qprglvwxjz'
d="uidchtnmbrl'poygk"
K={'C':D+c+c.upper().replace('Y;','Y:')+p+'Oo'+P,'W':D+w+w.upper().replace('P;','P:')+p+'Ii'+P,'D':D+'axje.'+d+',qf;AXJE>'+d.upper().replace("L'",'L"')+'<QF:!_#$%&-()*}w[vzSsW]VZ@/\=^{`?|+~'}
k,s=input().split()
print''.join(map(lambda x:K[k[0]][Q.index(x)],s))

```
> 2 votes

# Answer
# JavaScript (ES6), ~~461~~ ~~409~~ ~~404~~ ~~395~~ 385 bytes

I wrote the original version of the below up on my phone while sitting on a bus and then ran out of time to properly golf it so there's more crunching to follow. Thanks to @ETHproductions for the help so far.

The Keyboard strings were copied directly from the question so blame ~~Antoine~~ ETH for any errors!

This takes an integer representing the keyboard layout (0 for DVORAK, 94 for COLEMAK & 188 for WORKMAN) and an array of the string as arguments by currying - e.g., `f(0)(["z","Z","x","X"])` outputs `;:qQ`.

```
k=>s=>s.map(c=>`!_#$%&-()*}w[vz${a="0123456789"}SsW]VZ@AXJE>UIDCHTNMBRL"POYGK<QF:/\\=^{\`axje.uidchtnmbrl'poygk,qf;?|+~${b="!\"#$%&'()*+,-./"+a}Oo<=>?@ABCSFTDHUNEIMKY:QPRGLVWXJ${d="Z[\\]^_\`a"}bcsftdhuneimky;qprglvwxjz{|}~${b}Ii<=>?@AVMHRTGYUNEOLKP:QWSBFCDXJ${d}vmhrtgyuneolkp;qwsbfcdxjz{|}~`[`${b}:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXY${d}bcdefghijklmnopqrstuvwxyz{|}~`.search(c)+k]).join``

```

---

## Try It

```
f=
k=>s=>s.map(c=>`!_#$%&-()*}w[vz${a="0123456789"}SsW]VZ@AXJE>UIDCHTNMBRL"POYGK<QF:/\\=^{\`axje.uidchtnmbrl'poygk,qf;?|+~${b="!\"#$%&'()*+,-./"+a}Oo<=>?@ABCSFTDHUNEIMKY:QPRGLVWXJ${d="Z[\\]^_\`a"}bcsftdhuneimky;qprglvwxjz{|}~${b}Ii<=>?@AVMHRTGYUNEOLKP:QWSBFCDXJ${d}vmhrtgyuneolkp;qwsbfcdxjz{|}~`[`${b}:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXY${d}bcdefghijklmnopqrstuvwxyz{|}~`.search(c)+k]).join``
o.innerText=f(j.value=0)([...i.value="zZxX"])
i.oninput=j.oninput=_=>o.innerText=f(+j.value)([...i.value].filter(c=>`!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~`.includes(c)))
```

```
<select id=j><option value=0>DVORAK<option value=94>COLEMAK<option value=188>WORKMAN</select><input id=i><pre id=o>
```
> 2 votes

# Answer
# C++, 528 bytes

```
#include <map>
#define M(a,b)a!='\0'?a:b
std::map<char,char>t[3];char*c[]={"\"'+,-./:;<=>?BCDEFGHIJKLMNOPQRSTUVWXYZ[]_bcdefghijklmnopqrstuvwxyz{}","_-}w[vzSsW]VZXJE>UIDCHTNMBRL\"POYGK<QF:/={xje.uidchtnmbrl'poygk,qf;?+","\"'+,-./Oo<=>?BCSFTDHUNEIMKY:QPRGLVWXJZ[]_bcsftdhuneimky;qprglvwxjz{}","\"'+,-./Ii<=>?VMHRTGYUNEOLKP:QWSBFCDXJZ[]_vmhrtgyuneolkp;qwsbfcdxjz{}"};int main(int d,char*v[]){for(int i=1;i<4;i++)for(int j=0;j<68;j++)t[i-1][c[0][j]]=c[i][j];for(int k=0;v[2][k];k++)printf("%c",M(t[v[1][0]-'0'][v[2][k]],v[2][k]));}

```

Run with `./multitrans <0-2> <string>` where 0=Dvorak, 1=Colemak, and 2=Workman.

I added newlines in between to make the code slightly more readable below. This code generates a translation map from the strings where looking up the Qwerty character returns the translation (`t[0]['s'] = 'o'` for s into Dvorak), and then it uses the map to translate. The translation strings are shortened because some characters don't need to be changed ever. It could probably be reduced further, though.

```
#include <map>
#define M(a,b)a!='\0'?a:b
std::map<char,char>t[4];
char*c[4]={
"\"'+,-./:;<=>?BCDEFGHIJKLMNOPQRSTUVWXYZ[]_bcdefghijklmnopqrstuvwxyz{}",
"_-}w[vzSsW]VZXJE>UIDCHTNMBRL\"POYGK<QF:/={xje.uidchtnmbrl'poygk,qf;?+",
"\"'+,-./Oo<=>?BCSFTDHUNEIMKY:QPRGLVWXJZ[]_bcsftdhuneimky;qprglvwxjz{}",
"\"'+,-./Ii<=>?VMHRTGYUNEOLKP:QWSBFCDXJZ[]_vmhrtgyuneolkp;qwsbfcdxjz{}"};
int main(int d,char*v[]){
    for(int i=1;i<4;i++)
        for(int j=0;j<68;j++)
            t[i-1][c[0][j]]=c[i][j];
    for(int k=0;v[2][k];k++)
        printf("%c",M(t[v[1][0]-'0'][v[2][k]],v[2][k]));
}

```

### Extra: Qwerty -\> Dvorak Only (197 bytes)

I recently wrote this code that changes Qwerty into Dvorak, though capitals go untranslated.

```
#include<string>
char*d="\',.pyfgcrlaoeuidhtns;qjkxbmwvz ";std::string t="qwertyuiopasdfghjkl;zxcvbnm,./ ";int main(int c,char*v[]){for(int j=0;j<strlen(v[1]);j++)printf("%c",d[t.find(v[1][j])]);}

```
> 1 votes

# Answer
# 05AB1E, ~~199~~ ~~192~~ 187 bytes

```
žQDIiA¦'mKDuì“"'+,-./:;<=>?[]_{}“«.•4Zl˜η‡#ûwj˜ÐAδO•Duìð“>"<:.',;“S.;“_-}w[vzSsW]VZ/={?+“«ë¹<i.•2¸3'ÐQïK¤)•Duì„:;©ì.•C^ÿ¶₆*γŽ¨ï•Duì„Ooìë.•Brì·=ζW˜ΛlÝδ•Duì®ì.•]X)àƒ₆ä¤QúØM•Duì„Iiì}ð®S.;}‡‡

```

Uses IDs `1` for DVORAK; `2` for COLEMAK and `3` for WORKMAN.
Pushes the ID first, then the string we want to transliterate.

Try it online or verify full ASCII-range for all three.

**Explanation:**

```
žQ                    # Push printable ASCII builtin string:
                      #  “ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~“
  D                   # Duplicate it
   Ii                 # If the input-integer is 1:
     A                #  Push the lowercase alphabet
      ¦'mK           '#  Remove the first character (the 'a') and 'm'
          Duì         #  Prepend an uppercase copy
     “"'+,-./:;<=>?[]_{}“«
                     "#  And then append the string “"'+,-./:;<=>?[]_{}“
     .•4Zl˜η‡#ûwj˜ÐAδO•
                      #  Push compressed string "xje uidchtnbrl poygk qf "
        Duì           #  Prepend an uppercase copy
     ð                #  Push a space " "
      “>"<:.',;“S    "#  Push the characters [">",'"',"<",":",".","'",",",";"]
                 .;   #  Replace the first space with ">", second with '"', etc.
     “_-}w[vzSsW]VZ/={?+“«
                      #  And then append the string “_-}w[vzSsW]VZ/={?+“
   ë                  # Else:
    ¹<i               #  If the input-integer is 2 instead:
       .•2¸3'ÐQïK¤)• '#   Push compressed string "defgijklnoprstuy"
          Duì         #   Prepend an uppercase copy
       „:;            #   Push string ":;"
          ©           #   Store it in the register (without popping)
           ì          #   And then prepend this ":;" in front of the "DEF...def..."-string
       .•C^ÿ¶₆*γŽ¨ï•  #   Push compressed string "sftduneiky prglj"
          Duì         #   Prepend an uppercase copy
       „Ooì           #   And then prepend "Oo"
    ë                 #  Else (so the input-integer is 3):
     .•Brì·=ζW˜ΛlÝδ•  #   Push compressed string "bcdefhijklmnoprtuvwy"
        Duì           #   Prepend an uppercase copy
     ®ì               #   And then prepend ":;" (from the register)
     .•]X)àƒ₆ä¤QúØM•  #   Push compressed string "vmhrtyuneolkp wbfcdj"
        Duì           #   Prepend an uppercase copy
     „Iiì             #   And then prepend "Ii"
    }                 #  After the inner if-else:
     ð                #  Push a space " "
      ®S              #  Push the characters [":",";"] (from the register)
        .;            #  Replace the first space with ":" and the second space with ";"
   }                  # After the outer if-else:
    ‡                 # Transliterate the two strings we created,
                      #  in the duplicate printable ASCII string
     ‡                # And then transliterate the printable ASCII string with this string,
                      #  in the (implicit) string-input
                      # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand how the compressed strings work.
> 1 votes

# Answer
# C, 394 bytes

**Try Online**

```
char*K[3]={"!_#$%&-()*}w[vz0123456789SsW]VZ@AXJE>UIDCHTNMBRL\"POYGK<QF:/\\=^{`axje.uidchtnmbrl'poygk,qf;?|+~",
"!\"#$%&'()*+,-./0123456789Oo<=>?@ABCSFTDHUNEIMKY:QPRGLVWXJZ[\\]^_`abcsftdhuneimky;qprglvwxjz{|}~",
"!\"#$%&'()*+,-./0123456789Ii<=>?@AVMHRTGYUNEOLKP:QWSBFCDXJZ[\\]^_`avmhrtgyuneolkp;qwsbfcdxjz{|}~"};
main(int c,char**v){char*t=v[2];while(*t)putchar(*t>32?K[atoi(v[1])][*t-33]:*t),t++;}

```
> 0 votes

---
Tags: code-golf, string, keyboard
---


title: Closest 7-Distinct-Prime Product

text:
# Question
Title: Closest 7-Distinct-Prime Product
(via chat)

The OEIS entry A123321 lists the sequence of numbers that are the product of seven distinct primes. For brevity, we'll call this a *7DP* number. The first few numbers and their corresponding divisors are below:

```
510510 = 2 * 3 * 5 * 7 * 11 * 13 * 17
570570 = 2 * 3 * 5 * 7 * 11 * 13 * 19
690690 = 2 * 3 * 5 * 7 * 11 * 13 * 23
746130 = 2 * 3 * 5 * 7 * 11 * 17 * 19

```

The challenge here will be to find the closest 7DP number, in terms of absolute distance, from a given input.

### Input

A single positive integer *n* in any convenient format.

### Output

The closest 7DP number to *n*, again in any convenient format. If two 7DP numbers are tied for closest, you can output either or both.

### Rules

* Numbers can be assumed to fit in your language's default `[int]` datatype (or equivalent).
* Either a full program or a function are acceptable.
* Standard loopholes are forbidden.
* This is , so all usual golfing rules apply, and the shortest code wins.

### Examples

```
5 -> 510510
860782 -> 870870
1425060 -> 1438710 (or 1411410, or both)

```

# Answer
# Python, ~~89~~ ~~86~~ 85 bytes

```
f=lambda n,k=0:126^sum(1>>n%i<<7*(n/i%i<1)for i in range(2,n))and f(n+k,k%2*2+~k)or n

```

The algorithm is **O(scary)** to begin with and the recursion doesn't really help, but it works well as long as **n** is sufficiently close to a 7DP number.

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

Test it on repl.it.

### How it works

Python has no primality or factorization built-ins, but we can identify 7DP numbers by the amount and nature of their divisors.

By the multiplication principle, the number of divisors of an integer can be computed as the product of the incremented exponents of its prime factorization. Thus, **σ0(n)** (divisor function) is **2m** whenever **n** is a mDP number.

**σ0(n) = 128** is thus a necessary condition, but it is not sufficient; for example, **σ0(2127) = 128**, but **2127** is clearly not a 7DP number. However, if both **σ0(n) = 128** and no perfect square divides **n** evenly, then **n** is a 7DP number.

For the input **n**, the algorithm consists in inspecting the integers **n**, **n - 1**, **n + 1**, **n - 2**, **n + 2**, etc. and returning the first one that is a 7DP number.

When **f** is called with argument **n**, the following happens:

* The code

```
126^sum(1>>n%i<<7*(n/i%i<1)for i in range(2,n))

```

tests if **n** is *not* a 7DP number as follows.

For all integers **i** such that **1 \< i \< n**, `1>>n%i<<7*(n/i%i<1)` gets evaluated.

+ If **n** is divisible by **i** but not by **i2**, `1>>n%i` yields **1** and `(n/i%i<1)` yields **0**, resulting in
    **1 · 27 · 0 = 1**.
    + If **n** is divisible by **i2**, `1>>n%i` and `(n/i%i<1)` both yield **1**, resulting in **1 · 27 · 1 = 128**.
    + If **n** not not divisible by **i**, `1>>n%i` yields **0**, resulting in **0 · 27 · x = 0**.

The sum of the resulting integers will be **2m \- 2** if **n** is a mDP number (its **2m** divisors, excluding **1** and **n**) and a number greater than **127** if **n** has a perfect square factor. Thus, the sum will be **126** if and only if **n** is a 7DP number.
* For 7DP numbers, the sum is **126**, so XORing it with **126** yields **0**, which is falsy. Thus, the **or** part of the lambda is executed and **f** returns the current value of **n**.
* If **n** is not a 7DP number, XOR will return a non-zero, truthy value. Thus, the **and** part of the lambda is executed.

```
f(n+k,k%2*2+~k)

```

recursively calls **f** with updated values of **n** (the next potential 7DP number) and **k** (the difference between the the new candidate and the one after that).

If **k** is an even, non-negative integer, `k%2*2` yields **0** and `~k` yields **-(k + 1)**. The sum of both results is **-(k + 1)**, which is an odd, negative integer that is **1** greater in absolute value than **k**.

If **k** is an odd, negative integer, `k%2*2` yields **2** and `~k` yields **-(k + 1)**. The sum of both results is **2 - (k + 1) = -(k - 1)**, which is an even, non-negative integer that is **1** unit greater in absolute value than **k**.

This means that **k** takes the values **0, -1, 2, -3, 4, ⋯**.

When added cumulatively to **n0** (the initial value of **n**), the resulting integers are

+ **n0 \+ 0**
    + (**n0 \+ 0) - 1 = n0 \- 1**
    + (**n0 \- 1) + 2 = n0 \+ 1**
    + (**n0 \+ 1) - 3 = n0 \- 2**
    + (**n0 \- 2) + 4 = n0 \+ 2**
    + etc.

making sure the first 7DP number we encounter is as close to **n0** as possible.
> 11 votes

# Answer
# Brachylog, ~~44~~ ~~40~~ 16 bytes

Crossed out 44 is still regular 44 ;(

```
:I=+.>0,.$pPdPl7

```

Example:

```
?- run_from_atom(':I=+.>0,.$pPdPl7',1425060,Z).
Z = 1438710 .

```

Could it be that this language doesn't always suck? I beat Jelly and MATL!

The test case with `5` is the longest and takes about 10 seconds on my machine.

This would be 12 bytes if `$p` was not bugged (we wouldn't need the `>0,.` part)

### Explanation

Brachylog uses constraint logic programming by default for all integer arithmetic. Moreover, the labeling built-in `=` works on possibly infinite domains.

It successively unifies a variable with no constraints (i.e. in `(-inf, inf)`) as such: `0, 1, -1, 2, -2, 3, …`.

Therefore, we can get the closest 7DP number by looking for the first number `I` unified in `(-inf, inf)` (using automatic backtracking), for which `Input + I` is a 7DP number.

```
:I=                Label variables in [Input, I]. I has no constraints and Input is known
   +.              Unify Output with Input + I
     >0,           Output > 0 (wouldn't be needed if $p failed for numbers less than 1)
        .$pP       Unify P with the list of prime factors of Output
            dP     Check that P with duplicates removed is still P
              l7   Check that the length of P is 7

```
> 9 votes

# Answer
# Jelly, 17 bytes

```
Pµạ³,
×⁹ÆRœc7Ç€ṂṪ

```

Works in theory, but takes many years to complete.

---

Here is a version that actually works for the given inputs, but theoretically fails for large inputs:

```
Pµạ³,
50ÆRœc7Ç€ṂṪ

```

Try it here. This generates all primes up to 50, then finds all 7-combinations of primes in that list, and then all their products. Finally, it simply finds the closest element from that list to the given argument.

Of course, once our 7DPs contain primes higher than 50, this will fail. The theoretical version generates all primes up to **256n** for an input **n**, but otherwise works the same way.

## Proof

Let `p(x)` denote the next prime after `x`. An (extremely loose) upper bound for the closest 7DP product to x is:

```
p(x) * p(p(x)) * p(p(p(x))) * ... * p(p(p(p(p(p(p(x)))))))

```

So we only need to check primes in **\[2…p(p(p(p(p(p(p(x)))))))\]**. Bertrand's postulate says that **p(x) ≤ 2x**, so it suffices to check all primes up to **128x**.
> 6 votes

# Answer
# MATL, ~~21~~ ~~17~~ ~~16~~ ~~14~~ 13 bytes

*Thanks to Dennis for a suggestion that removed 4 bytes, and another that saved 1 more byte!*

```
t17*Zq7XN!pYk

```

This works in theory, but runs out of memory for inputs above `6` (online compiler).

A more efficient version uses **21 bytes**, and computes all test cases in about one second:

```
t3e4/k16+_YqZq7XN!pYk

```

Try it online!

## Explanation

### Memory-efficient version

Take input *N* = `860782` as an example. It suffices to consider primes up to *M* = `29`, which is the **first prime that multiplied by `2*3*5*7*11*13` exceeds N**. In this example, `2*3*5*7*11*13*29 = 870870`. The next prime is `31`. Any product involving that prime or greater will be at least `2*3*5*7*11*13*31 = 930930`, and so it's guaranteed **not** to be the solution, because it exceeds `870870` which exceeds *N*.

*M* is computed as the first prime greater than `max(N/(2*3*5*7*11*13), 16)`. The `max` function is used for ensuring that at least `17` is picked. To save a few bytes, the code replaces `2*3*5*7*11*13 = 30030` by `30000`, and function `max` by addition. These changes are valid because they give a larger value.

```
t      % Take input implicitly. Duplicate
3e4/k  % Divide input by 30000 and round down (rounding here is only needed
       % due to a bug in the "next prime" function)
16+    % Add 16
_Yq    % Next prime
Zq     % Prime numbers up to that value
7XN    % Combinations of those primes taken 7 at a time. Gives a 2D array
       % with each combination on a different row
!p     % Product of each row
Yk     % Output product that is closest to the input. Implicitly display

```

### Memory-inefficient version

To further reduce the number of bytes the division can be removed; in fact, it suffices to multiply by `17` (thanks, @Dennis). This ensures that the next prime is included (by Bertrand's postulate) and that the result is at least `17`. This works in theory, but runs out of memory for inputs larger than about `6`.

In the code, the section

```
3e4/k  % Divide input by 30000 and round down (rounding here is only needed
       % due to a bug in the "next prime" function)
16+    % Add 16
_Yq    % Next prime

```

is replaced by

```
17*    % Multiply by 17

```
> 5 votes

# Answer
## Pyke, 32 bytes

```
#PDl 7q.ID}lRlqi*(#)DF-X,)R],She

```

Try it here!

Note this doesn't work online - it times out. This Version only checks for 2 distinct primes and should work faster. When there are 2 numbers of the same distance away from the target, it chooses the lower one.

This goes through all the numbers until it finds one that is bigger than the input and is a 7DP. For each number, it gets rid of it if it isn't a 7DP. It then has a list of 7DPs up to the input with one that is bigger. It then picks the one that is closest to the input.
> 3 votes

# Answer
# Julia, 59 bytes

```
!n=sort(map(prod,combinations(17n|>primes,7))-n,by=abs)[]+n

```

This is *very* inefficient, but it works for the first test case in practice and for the others in theory.

At the cost of 5 more bytes – for a total of **64 bytes** – efficiency can be improved dramatically.

```
!n=sort(map(prod,combinations(n>>14+17|>primes,7))-n,by=abs)[]+n

```

Try it online!

### Background

As mentioned in @LuisMendo's answer, the set of primes we have to consider for the nearest 7DP number is quite small. It suffices for the set to contains a 7DP number that is bigger than the input **n**, which will be true if and only if it contains a prime **p ≥ 17** such that **30300p = 2·3·5·7·11·13·p ≥ n**.

In On the interval containing at least one prime number proves that the interval **\[x, 1.5x)** contains at least one prime number whenever **x ≥ 8**. Since **30030 / 16384 ≈ 1.83**, that means there must be a prime **p** in **(n/30030, n/16384)** whenever **n \> 8 · 30300 = 242400**.

Finally, when **n \< 510510**, **p = 17** is clearly sufficient, so we only need to consider primes up to **n/16384 + 17**.

At the cost of efficiency, we can consider primes up to **17n** instead. This works when **n = 1** and is vastly bigger than **n/16384 + 17** for larger values of **n**.

### How it works

`17n|>primes` and `n>>14+17|>primes` (the bitshift is equivalent to dividing by **214 = 16384**) compute the prime ranges mentioned in the previous paragraph. Then, `combinations(...,7)` computes all arrays of seven different prime numbers in that range, and mapping `prod` over those calculates their products, i.e., the 7DP numbers from which we'll choose the answer.

Next, `-n` subtracts **n** prom each 7DP number, then `sort(...,by=abs)` sorts those differences by their absolute values. Finally, we select the first difference with `[]` and compute the corresponding 7DP number by adding **n** with `+n`.
> 3 votes

# Answer
# Pyth, 30 bytes

```
L&{IPbq7lPby#.W!syMH,hhZa0teZ,

```

Try it online!

Test suite.

(5 takes too long to run)

### Explanation

```
L&{IPbq7lPby#.W!syMH,hhZa0teZ,

L&{IPbq7lPb     Defines a function y, whose argument is b:
 &                  Return if both the following are true:
  {IPb                  the prime factorization contains no duplicate; and:
      q7lPb             the number of prime factors is 7

           y#.W!syMH,hhZa0teZ,   The main programme. Input as Q.
                             ,QQ Implicit arguments, yield [Q,Q].
             .W                  While
               !syMH                   both numbers do not satisfy y:
                    ,hhZ             increment the first number
                          teZ        and decrement the second number
                        a0           while making it non-negative.

```
> 2 votes

# Answer
# Mathematica ~~136 80~~ 75 bytes

This is a straightforward approach, working outwards from `n`.

`n` is a 7-distinct-prime product iff the number of prime factors is 7 (`PrimeNu@#==7`) and none of these factors appears more than once (`SquareFreeQ@#&`).

```
g@n_:=(k=1;While[!(PrimeNu@#==7&&SquareFreeQ@#&)⌊z=n-⌊k/2](-1)^k⌋,k++];z)

```

My earlier submission (136 bytes) found both the first 7-distinct-prime product above `n` and, if it exists, the first 7-distinct-prime product below `n`. It then simply determined which was closer to `n`. If the products were equidistant, it returned both.

The current version checks n-1,n+1,n-2,n+2... until it reaches the first 7-distinct-prime product. This more efficient version adopts the approach Dennis took.

The key advance was in using `⌊k/2](-1)^k⌋` to return the series, 0, 1, -1, 2, -2... The zero is used to check whether `n` is itself a 7-distinct-prime product. For this reason, `Floor`(that is, `⌊...⌋`) is used instead of `Ceiling`.

---

```
g[5]
g[860782]
g[1425060]

```

510510

870870

1438710
> 1 votes

# Answer
# 05AB1E, 10 bytes

```
°Åp7.ÆPs.x

```

Try it online!

Tries all combinations of 7 of the first 10\**input primes. Runs out of memory for inputs greater than 1.

Considerably more efficient 14 bytes version:

```
5°/7+Åp7.ÆPs.x

```

Try it online!

Uses the first (input / 100000 + 7) primes.
> 1 votes

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


title: Simple complexity

text:
# Question
Title: Simple complexity
Output

```
                  #         #  #    #  # #####  ##    #
                  ##        ####    #######  #   #    ##
                ####        ##      ##    #  ### #######
                #  #         #       #    ##### ### #  #
                #  # ### #####   #####    #         #  #
                ####### ###  #  ###  #    ##        ####
                ##    #   #  ###  #  #######        ##
                 #    ##  #####   ##### #  #         #
                ##    #                   #         #  # #####
                 #    ##                  ##        #######  #
                 #######                ####        ##    #  ###
                ### #  #                #  #         #    #####
                    #  #                #  # ### #####    #
                    ####                ####### ###  #    ##
                    ##                  ##    #   #  #######
                     #                   #    ##  ##### #  #
    #  # #####  ##    #                   #
    #######  #   #    ##                  ##
    ##    #  ### #######                ####
     #    ##### ### #  #                #  #
 #####    #         #  #                #  # ###
###  #    ##        ####                #######
  #  #######        ##                  ##    #
  ##### #  #         #                   #    ##
          #         #  # #####   #####  ##    #
          ##        #######  #  ###  #   #    ##
        ####        ##    #  ###  #  ### #######
        #  #         #    #####   ##### ### #  #
        #  # ### #####    #       #         #  #
        ####### ###  #    ##      ##        ####
        ##    #   #  #######    ####        ##
         #    ##  ##### #  #    #  #         #
                                          #
                                          ##
                                        ####
                                        #  #
                                        #  # ###
                                        #######
                                        ##    #
                                         #    ##
                                 #####  ##    #
                                ###  #   #    ##
                                  #  ### #######
                                  ##### ### #  #
                                  #         #  #
                                  ##        ####
                                ####        ##
                                #  #         #
                                  #         #  #    #  # #####
                                  ##        ####    #######  #
                                ####        ##      ##    #  ###
                                #  #         #       #    #####
                                #  # ### #####   #####    #
                                ####### ###  #  ###  #    ##
                                ##    #   #  ###  #  #######
                                 #    ##  #####   ##### #  #
                                ##    #                   #
                                 #    ##                  ##
                                 #######                ####
                                ### #  #                #  #
                                    #  #                #  # ###
                                    ####                #######
                                    ##                  ##    #
                                     #                   #    ##

```

Trailing spaces allowed. Shortest solution wins.

hint0

hint1:

>

---

thanks @Tahg for correcting hint1

# Answer
# SOGL V0.12, ~~17~~ ~~16~~ 14 bytes

```
 #6{³IIč▓┼;I+§

```

Try it Here!

At a later update `č▓` could be removed for 12 bytes - that converts ToS from an array of arrays of characters a multiline string to an array of strings - `[["#","#"],[" ","#"]] -> ["##"," #"]` \- , because  \- horizontal append - doesn't deal well with arrays of arrays of characters - which `I` creates, because it's used for array rotation too. In SOGL an array of arrays of characters should be = array of strings, but many things don't support that yet..

Explanation:

```
 #            push "#"
  6{          6 times do
    ³           create 3 total copies of ToS
     II         rotate clockwise twice
       č▓       normalize as explained above
         ┼      append horizontally
          ;     get the 3rd copy ontop
           I    rotate clockwise
            +   append vertically
             §  reverse horizontally

```
> 12 votes

# Answer
## JavaScript (ES6), ~~233~~ ~~217~~ ~~213~~ ~~198~~ ~~182~~ ~~170~~ ~~163~~ 122 bytes

```
f=_=>[...Array(64)].map((_,x,a)=>a.map(g=(i=(n=64,x),j)=>(n>>=1)?i&n?j&n?g(j,i):` `:j&n?g(i,~j):g(~i,j):`#`).join``).join`
`
document.write(`<pre>${f()}</pre>`)
```

Edit: Saved ~~14~~ 18 bytes thanks to @Shaggy. Saved 3 bytes thanks to @ngn. Saved a further 12 bytes thanks to the two working together. Saved 41 bytes by stealing @user202729's observations that the quarters use reflections rather than rotations. Ungolfed:

```
function f() {
    var s = '';
    for (var i = 0; i < 64; i++) {
        for (var j = 0; j < 64; j++) {
            var x = i, y = j, c = '#'; // Default to #
            // Each non-blank quadrant maps to to the original
            // image by doubling and a reflection. Repeat
            // this six times unless we hit the blank quadrant.
            for (var n = 0; n < 6; n++) {
                if (x >= 32) {
                    if (y >= 32) {
                        // Bottom right quarter is a diagonal reflection
                        var t = x - 32;
                        x = y - 32;
                        y = t;
                    } else {
                        // Bottom left quarter is blank
                        c = ' ';
                        break;
                    }
                } else {
                    if (y >= 32) {
                       // Top right corner is a horizontal reflection
                       y = 63 - y;
                    } else {
                       // Top left corner is a vertical reflection
                       x = 31 - x;
                    }
                }
                x *= 2;
                y *= 2;
            }
            s += c;
        }
        s += '\n';
    }
    return s;
}

```
> 22 votes

# Answer
# LOGO, ~~375~~ ~~341~~ ~~297~~ ~~295~~ 278 + 3 bytes

Add 3 bytes because of `-p` flag, which enable perspective mode by default, thus don't need to run `perspective` command, saves 9 bytes overall.

Use FMSLogo on Windows with Unix (LF) newline format (FMSLogo have problem with parsing CR newline format)

```
to R
rt 90
end
to g :w :l
R fd 2*:l R bk :l up 180
run :w
R run :w
fd 2*:l R bk :l run :w
fd 2*:l up 180
end
to h
pu
ask -1[setxyz 0 0 870]g[g[g[g[g[g[rt 45 fd .7 pd fd 0 pu bk .7 lt 45]1]2]4]8]16]32
repeat 64[sety 64-# repeat 64[setx #-1 type if pixel=[0 0 0]""#["\ ]](pr)]
end

```

Unfortunately, no "Try it online!" link because I can't find any online interpreter support perspective mode.

Idea: Draw a picture of the image, then retrieve the pixels from the picture and print as output.

Picture breakdown to simple repeated parts:

.

Make use of the hint above. However, since LOGO does not support reflection, we can only simulate that by enter 3D (`perspective`) mode and turn the turtle 180 degree around an axis parallel to the computer screen.

This defines a helper function `g`, which given 2 parameters `l` (image side length) and `w` (procedure used to draw the image), draw 3 copies of its reflected image. (see hint in the question) The procedure `h` perform the main procedure.
> 11 votes

# Answer
# 05AB1E, ~~30~~ 26 bytes

```
'#)6F©R®í®'#ð:®ζ)2ä€ø€J˜}»

```

Try it online!
> 10 votes

# Answer
# Python 2, ~~205~~ ~~195 ... 145~~ ~~144~~ ~~142~~ 144 bytes

```
g=lambda n,i,j,*_:g(n/2,*[~i,j,i,~j][2*(j&n>0)-(i&n>0):])if n*(i&n<=j&n)else'# '[i&n>0]
r=range(64)
for j in r:print''.join(g(32,j,i)for i in r)

```

Try it online!

Inspired by Neil's JS answer.
> 8 votes

# Answer
## CJam, 30 bytes

```
"#"]{_W%_32ff&+\_Wf%\z+.+}6*N*

```

Try it online!
> 8 votes

# Answer
## Haskell, ~~126~~ ~~125~~ ~~113~~ ~~106~~ 103 bytes

```
e=[]:e
z=zipWith
r=reverse
m s=z(++)(r s++map(' '<$)s)$map r s++foldr(z(:))e s
unlines$m$m$m$m$m$m["#"]

```

A direct implementation of hint1 in the spoiler.

Function `m` generates the next iteration. The main functions applies `m` 6 times. Details to `m`:

```
m s=                          -- s is the current pattern
     zipWith(++)              -- concatenate pairwise the lines of
                (r s)++       --    the lines of s in reverse order, followed by
                map(' '<$)s   --    each char in s replaced by a space
                              -- and
                map r s++     --    each line of s reversed, followed by
                foldr ... s   --    the transposition of s

e=[]:e;foldr(zipWith(:))e     -- this right fold transposes a matrix

```

Edit: @ngn saved a byte and @Laikoni another 3. Thanks!
> 7 votes

# Answer
# Java 7, ~~259 238 237~~ 200 bytes

```
void f(){char[][]o={{35}},n;for(int s=1,x,y;s<64;s*=2,o=n)for(n=new char[64][64],x=s;x-->0;)for(y=0;y<s;n[s+y++][x]=32)n[s+~y][x]=n[y][2*s+~x]=n[s+x][s+y]=o[y][x];for(char[]b:o)System.out.println(b);}

```

Saved 2 bytes by removing the {} on the x loop, thanks ngn
Saved 19 bytes from various assignment changes, thanks Jonathan
Saved 24 bytes for print vs return (didn't know this was allowed), and
Saved 13 bytes for loop changes, thanks Nevay

Try it online!

My first challenge, and I think respectable for Java. Uses hint 1, (which is wrong btw, but I can't write comments). It can probably be golfed further, this pass was basically as is, without pretty printing.
> 6 votes

# Answer
# , ~~30~~ 27 bytes

```
|:@(|:@|.,|.@|:,.])^:6,.'#'

```

Try it online!

### Original version.

```
((|.,.|."1),' '"0,.|:)^:6,.'#'

```

Try it online!
> 5 votes

# Answer
## Python 2, 586 bytes

```
import zlib,base64 as b
print zlib.decompress(b.b64decode('eJyVVlsOwzAI++8pJuX+d1zXDGLAUKi0pUp52ATcfj7+Wni3dF2/677ZO1dw+z/Zd3+rJU4SdkVHMcYQS9OuJVGio4N61p31+TGoQkco6eqoU6gSWdBJRrQhjhIdvLQ6YhNrqrEtUsu8yEbjmRqUWXlgYbl5EHfLC7cDQl4sxxAhO4wUv7fFPTx22sUWqOeEJ544Z3vn9FPU+ZmdHtCak6Fk3hfCx0FkOC8DF4YvmgoFMnCEwW2cDBkzftoiGy4GZaNhM8VYSl3YMEV7ctxsjLQKRCHZ3IB6+ATZpKSKmEyGrqZvEHY8lEQBWf8zbuAg0eypWG6nRqTLIzM+NPQa2faN89FlxhMY2vcTKDP7579fl0rmIpJ+grTvSyis798ghb4vM0CuVgbM1SFdvukjnFnfR1Gt3vAEngd6lGrIDdfkDU/ARwl+ecMHf5SzIzct8KhsqHANZ0FqFbpXdad5qH2DzOHJIHGM2pz26oug9i2+EBpX+cXQCpBA7/tne01lLb4wviHjtJE='))

```

Try it online.

---

## Python 2, ~~1032~~ 1025 bytes

I like this one more. But it is much longer. It could be golfed down but there is no need for that. officialaimm's approach is much shorter.

-7 thanks to Jonathan Frech

```
print''.join(' '*int(x)if'/'<x<'@'else("#"*(ord(x)-64),"\n")[x<"#"]for x in'99A9A2A4A2A1E2B4A9!99B8D4G2A3A4B8!88D8B6B4A2C1G8!88A2A9A7A4E1C1A2A8!88A2A1C1E3E4A9A2A8!88G1C2A2C2A4B8D8!88B4A3A2C2A2G8B55!98A4B2E3E1A2A9A55!88B4A559A9A2A1E2!98A4B99B8G2A2!98G88D8B4A2C!88C1A2A88A2A9A4E1!992A2A88A2A1C1E4A5!992D88G1C2A4B4!992B99B4A3A2G4!777A559A4B2E1A2A4!4A2A1E2B4A559A777!4G2A3A4B99B992!4B4A2C1G88D992!5A4E1C1A2A88A2A569!1E4A9A2A88A2A1C88!C2A4B8D88G98!2A2G8B99B4A89!2E1A2A9A559A4B88!55A9A2A1E3E2B4A98!55B8G2A2C2A3A4B88!8D8B4A2C2A2C1G88!8A2A9A4E3E1C1A2A88!8A2A1C1E4A7A9A2A88!8G1C2A4B6B8D88!8B4A3A2G4D8B99!9A4B2E1A2A4A2A9A99!99996A777!99996B992!99994D299!99994A2A992!99994A2A1C88!99994G98!99994B4A98!99995A4B88!9996E2B4A89!9995C2A3A4B88!9997A2C1G88!9997E1C1A2A88!9997A9A2A88!9997B8D88!9995D8B99!9995A2A9A99!9997A9A2A4A2A1E2!9997B8D4G2A2!9995D8B6B4A2C!9995A2A9A7A4E1!9995A2A1C1E3E4A5!9995G1C2A2C2A4B4!9995B4A3A2C2A2G4!9996A4B2E3E1A2A4!9995B4A559A5!9996A4B99B4!9996G88D4!9995C1A2A88A2A4!9999A2A88A2A1C!9999D88G1!9999B99B4A1!99991A559A4B')

```

Try it online.
> 3 votes

# Answer
# Mathematica, ~~112~~ 90 bytes

Thanks to Jonathan Frech for help saving 2 bytes!

```
""<>Nest[{{(r=Reverse)@#,r/@#},{" "+0#,#}}~Flatten~{{1,3},{2,4}}&,{{"#"}},6]~Riffle~"
"

```

Try it online! (Mathics)

For some reasons, Mathics prints leading spaces in all lines except the first one when print multiline string. Also Mathics doesn't support operator.

Explanation:

* `{{Reverse@#,Reverse/@#},{" "+0#,#}}` : Represent the reverse-horizontally, reverse-vertically, replace-all-by-`" "`, and transpose ( is transpose operator in Mathematica), corresponding to different ways to reflect or rotate the image.
* `~Flatten~{{1,3},{2,4}}` : Flatten in particular dimensions.
* `Nest[ ... ,{{"#"}},6]` : Apply the function inside to `{{"#"}}` 6 times.
* `~Riffle~"<literal newline character>"` : Riffle a newline character between each line.
* `""<>` : Join all strings together.
> 3 votes

# Answer
# C# (.NET Core), ~~1016~~ ~~1002~~ ~~980~~ 955 bytes

Saved 14 bytes thanks to Kevin Cruijssen!
Saved 47 bytes thanks to Jonathan Frech!

```
o=>{foreach(var l in new[]{35223185965568,52841249260288,0xf00c0c277f00,0x9004043ee900,0x977c7c200900,0xfee4e4300f00,0xc22727f00c00,73934616658944,0xc2000020097c,73667282210788,0x7f0000f00c27,0xe9000090043e,9895614577696,0xf0000fee430,0xc0000c227f0,4398050918032,325982355457<<21,1092065689603<<20,835235872783<<20,291765223433<<20,0x7c20090000970000,-15289957744513<<17,21955973480545<<17,68788263321667<<16,68799053409<<17,206425089091<<16,0xf00c27277f0000,618546478825<<16,650622541833<<16,0xfee430300f0000,208473439235<<18,72203117569<<18,1<<21,3<<20,15<<20,9<<20,9895936,127<<17,97<<17,67<<16,15969<<17,3829596160,662634496,16105<<16,8201<<16,806289408,4027318272,9217L<<18,537463164,806293476,4027321383,2416182334,2541517856,4276413488,3257346032,1128152720,3254779936,1124073520,2130706672,3909091472,150995095,251658494,201326786,67108931})System.Console.WriteLine(System.Convert.ToString(l,2).PadLeft(64,'0').Replace('0',' ').Replace('1','#'));}

```

Try it online!

---

# Explanation

The format of the output is stored inside an array of signed 64-bit numbers, which fits perfectly since each line is 64 characters long. Empty spaces are represented by `0` and `#` is represented by `1`.

The numbers are then converted to their binary string, zeros are padded left until the string is 64 characters wide and then the `0` and `1` characters are replaced with  and `#`.

The code is stored inside a lamba function, more specifically a `System.Func<string>`.

Some constants in the `long[]` are shortened by performing some bit-shifting.
> 2 votes

# Answer
# Charcoal, 42 bytes

```
#↓##ＦＥ⁵Ｘ²ι«‖↑Ｊ⁻×³ι¹±⁰ψ⟲ＯＯ⁴×²ι⟲ＣＪ⁰±φＴ×⁴ι×⁴ι

```

Try it online! Link is to verbose version of code. Would be 25 bytes if this worked:

```
#ＦＥ⁷Ｘ²ι«‖↑⟲Ｃ→⁴⟲ＣＪ⁰±φＴιι

```

Explanation:

```
#↓##

```

Manually generate the first recursion, since it's not possible to rotate around (1, 0.5). (Such a rotation would only make sense if it was 180°.)

```
ＦＥ⁵Ｘ²ι«

```

Loop over the first five powers of 2 (1, 2, 4, 8, 16).

```
‖↑

```

Reflect the canvas vertically. This completes the top left quarter of the result.

```
Ｊ⁻×³ι¹±⁰ψ⟲ＯＯ⁴×²ι

```

Rotate the canvas 180° around a point half-way up the right-hand side. The copy ends up in the correct position for the top right quarter of the result.

```
⟲Ｃ

```

Rotate the canvas 90° around the bottom right corner. The copy of the top right corner ends up in the correct position for the bottom right corner of the result. The copy of the top left corner is extraneous.

```
Ｊ⁰±φＴ×⁴ι×⁴ι

```

Trim the canvas to the size we want. The trim starts at the cursor or the top left of the canvas, whichever is bottom rightmost. The cursor is therefore sent to (0, -1000) to ensure that it doesn't interfere with the trim.
> 2 votes

# Answer
# Dyalog APL, 29 bytes

```
⎕←(((⊖,⌽)⍪⊢∘' '¨,⍉)⍣6)1 1⍴'#'

```

Try it online!
> 2 votes

# Answer
# Python 2, ~~715~~ 711 bytes

* -4 bytes thanks to @Jonathan Frech

```
for k in range(64):print"".join(ord(i)*" #"[j%2]for j,i in enumerate('												<?<<<89:11222	202	4	$" 	!%$%$&%$($%&'))[k<<6:][:64]

```

Try it online!
> 1 votes

# Answer
## Perl 5, 452 bytes

**451 bytes code + 1 for `-p`.**

Packs all the data into the string, rather than stealing @Neil's correct answer.

```
$_=unpack"B*","\x00\x00\x20\x09\x09\x7c\xc2\x33\x00\x30\x0f\x0f\xe4\x43\x33\x00\xf0\x0c\x0c\x27\x7f\x33\x00\x90\x04\x04\x3e\xe9\x33\x00\x97\x7c\x7c\x20\x09\x33\x00\xfe\xe4\xe4\x30\x0f\x33\x00\xc2\x27\x27\xf0\x0c\x33\x00\x43\x3e\x3e\x90\x04\x33\x00\xc2\x00\x00\x20\x09\x7c\x00\x00\x43\x00\x00\x30\x0f\xe4\x00\x00\x7f\x00\x00\xf0\x0c\x27\x00\x00\xe9\x00\x00\x90\x04\x3e\x00\x00\x09\x00\x00\x97\x7c\x20\x00\x00\x0f\x00\x00\xfe\xe4\x30\x00\x00\x0c\x00\x00\xc2\x27\xf0\x00\x00\x04\x00\x00\x43\x3e\x90\x09\x7c\xc2\x00\x00\x20\x00\x00\x0f\xe4\x43\x00\x00\x30\x00\x00\x0c\x27\x7f\x00\x00\xf0\x00\x00\x04\x3e\xe9\x00\x00\x90\x00\x00\x7c\x20\x09\x00\x00\x97\x00\x00\xe4\x30\x0f\x00\x00\xfe\x00\x00\x27\xf0\x0c\x00\x00\xc2\x00\x00\x3e\x90\x04\x00\x00\x43\x33\x00\x20\x09\x7c\x7c\xc2\x33\x00\x30\x0f\xe4\xe4\x43\x33\x00\xf0\x0c\x27\x27\x7f\x33\x00\x90\x04\x3e\x3e\xe9\x33\x00\x97\x7c\x20\x20\x09\x33\x00\xfe\xe4\x30\x30\x0f\x33\x00\xc2\x27\xf0\xf0\x0c\x33\x00\x43\x3e\x90\x90\x04\x37\x00\x20\x37\x00\x30\x37\x00\xf0\x37\x00\x90\x37\x00\x97\x37\x00\xfe\x37\x00\xc2\x37\x00\x43\x36\x00\x7c\xc2\x36\x00\xe4\x43\x36\x00\x27\x7f\x36\x00\x3e\xe9\x36\x00\x20\x09\x36\x00\x30\x0f\x36\x00\xf0\x0c\x36\x00\x90\x04\x36\x00\x20\x09\x09\x7c\x34\x00\x30\x0f\x0f\xe4\x34\x00\xf0\x0c\x0c\x27\x34\x00\x90\x04\x04\x3e\x34\x00\x97\x7c\x7c\x20\x34\x00\xfe\xe4\xe4\x30\x34\x00\xc2\x27\x27\xf0\x34\x00\x43\x3e\x3e\x90\x34\x00\xc2\x00\x00\x20\x34\x00\x43\x00\x00\x30\x34\x00\x7f\x00\x00\xf0\x34\x00\xe9\x00\x00\x90\x34\x00\x09\x00\x00\x97\x34\x00\x0f\x00\x00\xfe\x34\x00\x0c\x00\x00\xc2\x34\x00\x04\x00\x00\x43"=~s/[3-9](.)/$1x$&/ger;y/01/ #/;s/.{64}/$&
/g

```

Reversible output from `xxd` for 451 byte file:

```
00000000: 245f 3d75 6e70 6163 6b22 422a 222c 2200  $_=unpack"B*",".
00000010: 0020 0909 7cc2 3300 300f 0fe4 4333 00f0  . ..|.3.0...C3..
00000020: 0c0c 277f 3300 9004 043e e933 0097 7c7c  ..'.3....>.3..||
00000030: 2009 3300 fee4 e430 0f33 00c2 2727 f00c   .3....0.3..''..
00000040: 3300 433e 3e90 0433 00c2 0000 2009 7c00  3.C>>..3.... .|.
00000050: 0043 0000 300f e400 007f 0000 f00c 2700  .C..0.........'.
00000060: 00e9 0000 9004 3e00 0009 0000 977c 2000  ......>......| .
00000070: 000f 0000 fee4 3000 000c 0000 c227 f000  ......0......'..
00000080: 0004 0000 433e 9009 7cc2 0000 2000 000f  ....C>..|... ...
00000090: e443 0000 3000 000c 277f 0000 f000 0004  .C..0...'.......
000000a0: 3ee9 0000 9000 007c 2009 0000 9700 00e4  >......| .......
000000b0: 300f 0000 fe00 0027 f00c 0000 c200 003e  0......'.......>
000000c0: 9004 0000 4333 0020 097c 7cc2 3300 300f  ....C3. .||.3.0.
000000d0: e4e4 4333 00f0 0c27 277f 3300 9004 3e3e  ..C3...''.3...>>
000000e0: e933 0097 7c20 2009 3300 fee4 3030 0f33  .3..|  .3...00.3
000000f0: 00c2 27f0 f00c 3300 433e 9090 0437 0020  ..'...3.C>...7.
00000100: 3700 3037 00f0 3700 9037 0097 3700 fe37  7.07..7..7..7..7
00000110: 00c2 3700 4336 007c c236 00e4 4336 0027  ..7.C6.|.6..C6.'
00000120: 7f36 003e e936 0020 0936 0030 0f36 00f0  .6.>.6. .6.0.6..
00000130: 0c36 0090 0436 0020 0909 7c34 0030 0f0f  .6...6. ..|4.0..
00000140: e434 00f0 0c0c 2734 0090 0404 3e34 0097  .4....'4....>4..
00000150: 7c7c 2034 00fe e4e4 3034 00c2 2727 f034  || 4....04..''.4
00000160: 0043 3e3e 9034 00c2 0000 2034 0043 0000  .C>>.4.... 4.C..
00000170: 3034 007f 0000 f034 00e9 0000 9034 0009  04.....4.....4..
00000180: 0000 9734 000f 0000 fe34 000c 0000 c234  ...4.....4.....4
00000190: 0004 0000 4322 3d7e 732f 5b33 2d39 5d28  ....C"=~s/[3-9](
000001a0: 2e29 2f24 3178 2426 2f67 6572 3b79 2f30  .)/$1x$&/ger;y/0
000001b0: 312f 2023 2f3b 732f 2e7b 3634 7d2f 2426  1/ #/;s/.{64}/$&
000001c0: 0a2f 67                                  ./g

```

Try it online!
> 1 votes

# Answer
# Jq 1.5, ~~538~~ ~~535~~ ~~488~~ 476 bytes

This is a straightforward representation. ~~I haven't attempted any fancy encodings yet.~~ Replaced 0,0 pairs with Z function.

Thanks again to Jonathan Frech for helping eliminate 3 bytes!

```
def B:recurse(if.>0then./2|floor else empty end)|.%2;def S:256+.|[B]|reverse[2:]|map(if.>0then"#"else" "end)|join("");def Z:0,0;[[Z,3,1,1,4,5,2],[1,4,5,2,2,3,Z],[Z,Z,2,3,Z],[Z,Z,3,1,1,4]]as$m|[[],[9,15,12,4,124,228,39,62],[Z,Z,Z,Z,124,228,39,62,32,48,240,144],[32,48,240,144,151,254,194,67,194,67,127,233,9,15,12,4],[124,228,39,62,32,48,240,144,32,48,240,144,151,254,194,67],[194,67,127,233,9,15,12,4,9,15,12,4,124,228,39,62]]as$c|$m[]|range(16)as$l|map($c[.][$l]|S)|join("")

```

Character count

```
$ wc -c picture.jq
 476 picture.jq

```

Sample run

```
$ jq -Mnr -f picture.jq
                  #         #  #    #  # #####  ##    #
                  ##        ####    #######  #   #    ##
                ####        ##      ##    #  ### #######
                #  #         #       #    ##### ### #  #
                #  # ### #####   #####    #         #  #
                ####### ###  #  ###  #    ##        ####
                ##    #   #  ###  #  #######        ##
                 #    ##  #####   ##### #  #         #
                ##    #                   #         #  # #####
                 #    ##                  ##        #######  #
                 #######                ####        ##    #  ###
                ### #  #                #  #         #    #####
                    #  #                #  # ### #####    #
                    ####                ####### ###  #    ##
                    ##                  ##    #   #  #######
                     #                   #    ##  ##### #  #
    #  # #####  ##    #                   #
    #######  #   #    ##                  ##
    ##    #  ### #######                ####
     #    ##### ### #  #                #  #
 #####    #         #  #                #  # ###
###  #    ##        ####                #######
  #  #######        ##                  ##    #
  ##### #  #         #                   #    ##
          #         #  # #####   #####  ##    #
          ##        #######  #  ###  #   #    ##
        ####        ##    #  ###  #  ### #######
        #  #         #    #####   ##### ### #  #
        #  # ### #####    #       #         #  #
        ####### ###  #    ##      ##        ####
        ##    #   #  #######    ####        ##
         #    ##  ##### #  #    #  #         #
                                          #
                                          ##
                                        ####
                                        #  #
                                        #  # ###
                                        #######
                                        ##    #
                                         #    ##
                                 #####  ##    #
                                ###  #   #    ##
                                  #  ### #######
                                  ##### ### #  #
                                  #         #  #
                                  ##        ####
                                ####        ##
                                #  #         #
                                  #         #  #    #  # #####
                                  ##        ####    #######  #
                                ####        ##      ##    #  ###
                                #  #         #       #    #####
                                #  # ### #####   #####    #
                                ####### ###  #  ###  #    ##
                                ##    #   #  ###  #  #######
                                 #    ##  #####   ##### #  #
                                ##    #                   #
                                 #    ##                  ##
                                 #######                ####
                                ### #  #                #  #
                                    #  #                #  # ###
                                    ####                #######
                                    ##                  ##    #
                                     #                   #    ##

```
> 1 votes

# Answer
# Python 2, ~~174~~ ~~164~~ 154 bytes (based on matrix operations)

* -10 bytes thanks to ngn.
* -10 bytes thanks to Jonathan Frech.

```
from numpy import*
s=[['#']]
exec'b=fliplr(s);s=vstack((hstack((flipud(s),b)),hstack((eye(len(s)),rot90(b)))));'*6
s[s>'#']=' '
for l in s:print''.join(l)

```

Try it online!
> 1 votes

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

```
6{,[|x;""x],'(+|+x),+x}/"#"

```

Try it online!

`6{` `}/` 6 times do

`+x` transpose

`|x` reverse vertically

`+|+x` reverse horizontally

`,` concatenate vertically

`,'` concatenate horizontally

`,[A;B]` is the same as `A,B`. it helps avoid parentheses around `A` and around the whole expression

`""x` use the elements of `x` as indices in the empty string. out-of-bounds indexing produces spaces, so this expression will return an all-spaces matrix, same size as `x`
> 1 votes

# Answer
# Canvas, 10 bytes

```
#６［↔ω⤢∔ω↶×

```

Try it here!
> 1 votes

# Answer
# C# (.NET Core), ~~976~~ 969 bytes

```
o=>{foreach(var l in new[]{35223185965568,52841249260288,0xf00c0c277f00,0x9004043ee900,0x977c7c200900,0xfee4e4300f00,0xc22727f00c00,73934616658944,0xc2000020097c,73667282210788,0x7f0000f00c27,0xe9000090043e,9895614577696,0xf0000fee430,0xc0000c227f0,4398050918032,0x97cc20000200000,0xfe44300003<<20,0xc277f0000f<<20,0x43ee900009<<20,0x7c20090000970000,-0x1bcff0ffff020000,0x27f00c0000c20000,0x3e90040000430000,9017629528424448,0x300fe4e4430000,0xf00c27277f0000,0x90043e3ee90000,0x977c2020090000,0xfee430300f0000,0xc227f0f00c0000,0x433e9090040000,2097152,3145728,15728640,9437184,9895936,16646144,12713984,4390912,2093088768,3829596160,662634496,1055457280,537460736,806289408,4027318272,2416181248,537463164,806293476,4027321383,2416182334,2541517856,4276413488,3257346032,1128152720,3254779936,1124073520,2130706672,3909091472,150995095,251658494,201326786,67108931})System.Console.WriteLine(System.Convert.ToString(l,2).PadLeft(64).Replace('0',' ').Replace('1','#'));}

```

Try it online!
> 0 votes

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

```
_=>{var r="";for(int i=0,j,k=0;i<626;i++)for(j=0;j++<@"4#+#$#&#$##'$$&#=$*&&)$#%#&$:&*$($&#$%#):#$#+#)#&'#%##$#:#$##%#'%'&#+#$#:)#%$#$%$#&$*&:$&#%#$%$#$)*$=#&$$'%'##$#+#<$&#5#+#$##'5#&$4$*)$#5)2&*$&#$%2%##$#2#$#+#&'7#$#2#$##%#'&#;&2)#%$#&$:$4$&#%#$);#5#&$$'##$#*#$##'$$&#5#;)$#%#&$4$:$&#$%#)2&;#&'#%##$#2#$#7'&#+#$#2#$##%2%$#&$*&2)5#$)*$4$&#5'##$#+#5#&$<#+#$##'%'$$&#=$*)$#$%$#%#&$:&*$&#$%$#$%#):#$#+#&'%'#%##$#:#$##%#'&#)#+#$#:)#%$#&$($*&:$&#%#$)&&*$=#&$$'##$#&#$#+#^#a$^&^#$#^#$##%Z)[$&#\#&$S'$$&#S%$#%#&$T#$%#)T'#%##$#T#+#$#T$*&R&*$T#$#+#V#+#$#&#$##'F$*&&)$#D&*$($&#$%B#$#+#)#&'C#$##%#'%'&#G)#%$#$%$#&$F$&#%#$%$#$)G#&$$'%'##$#F$&#5#H#&$4$G)2&F%##$#2#$#J#$#2#$##%F&2)G$4$&#H#5#&$"[i]-34;){r+=i%2<1?' ':'#';if(++k%64<1)r+='\n';}return r;}

```

Try it online!

Uses the same approach is this other answer.
> 0 votes

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

```
_=>` 18# 9# 2# 4# 2# #5 2#2 4#
 18#2 8#4 4#7 2# 3# 4#2
 16#4 8#2 6#2 4# 2#3 #7
 16# 2# 9# 7# 4#5 #3 # 2#
 16# 2# #3 #5 3#5 4# 9# 2#
 16#7 #3 2# 2#3 2# 4#2 8#4
 16#2 4# 3# 2#3 2# 2#7 8#2
 17# 4#2 2#5 3#5 # 2# 9#
 16#2 4# 19# 9# 2# #5
 17# 4#2 18#2 8#7 2#
 17#7 16#4 8#2 4# 2#3
 16#3 # 2# 16# 2# 9# 4#5
 20# 2# 16# 2# #3 #5 4#
 20#4 16#7 #3 2# 4#2
 20#2 18#2 4# 3# 2#7
 21# 19# 4#2 2#5 # 2#
 4# 2# #5 2#2 4# 19#
 4#7 2# 3# 4#2 18#2
 4#2 4# 2#3 #7 16#4
 5# 4#5 #3 # 2# 16# 2#
 #5 4# 9# 2# 16# 2# #3
#3 2# 4#2 8#4 16#7
 2# 2#7 8#2 18#2 4#
 2#5 # 2# 9# 19# 4#2
 10# 9# 2# #5 3#5 2#2 4#
 10#2 8#7 2# 2#3 2# 3# 4#2
 8#4 8#2 4# 2#3 2# 2#3 #7
 8# 2# 9# 4#5 3#5 #3 # 2#
 8# 2# #3 #5 4# 7# 9# 2#
 8#7 #3 2# 4#2 6#2 8#4
 8#2 4# 3# 2#7 4#4 8#2
 9# 4#2 2#5 # 2# 4# 2# 9#
 42#
 42#2
 40#4
 40# 2#
 40# 2# #3
 40#7
 40#2 4#
 41# 4#2
 33#5 2#2 4#
 32#3 2# 3# 4#2
 34# 2#3 #7
 34#5 #3 # 2#
 34# 9# 2#
 34#2 8#4
 32#4 8#2
 32# 2# 9#
 34# 9# 2# 4# 2# #5
 34#2 8#4 4#7 2#
 32#4 8#2 6#2 4# 2#3
 32# 2# 9# 7# 4#5
 32# 2# #3 #5 3#5 4#
 32#7 #3 2# 2#3 2# 4#2
 32#2 4# 3# 2#3 2# 2#7
 33# 4#2 2#5 3#5 # 2#
 32#2 4# 19#
 33# 4#2 18#2
 33#7 16#4
 32#3 # 2# 16# 2#
 36# 2# 16# 2# #3
 36#4 16#7
 36#2 18#2 4#
 37# 19# 4#2`.replace(/(.)(\d+)/g,(_,c,n)=>c.repeat(n))

```

Try it online!
> -1 votes

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


title: Matrix rotation sort

text:
# Question
Title: Matrix rotation sort
Lets define a non-empty, unsorted and finite matrix with unique numbers as follow: $$N = \begin{Bmatrix} 4&5&7\\1&3&6 \end{Bmatrix}$$

Lets define 4 matrix moves as:

* ↑\* (up): Moves a column up
* ↓\* (down): Moves a column down
* →\* (right): Moves a row to the right
* ←\* (left): Moves a row to the left

The asterisk(\*) represents the column/row that is affected by the move (It can be 0-indexed or 1-indexed. Up to you. Please state which one in your answer).

---

**The challenge** is, using above moves, sort the matrix in a ascendant order (being the top left corner the lowest and the bottom right corner the highest).

**Example**

Input: $$N=\begin{Bmatrix}4&2&3\\1&5&6 \end{Bmatrix}$$ Possible Output: `↑0` or `↓0`. (Notice any of those moves can sort the matrix so both answer are correct)

---

Input: $$N=\begin{Bmatrix}2&3&1\\4&5&6 \end{Bmatrix}$$ Possible Output: `→0`

---

Input (Example test case): $$N = \begin{Bmatrix} 4&5&7\\1&3&6 \end{Bmatrix}$$ Possible Output: `↑0↑1←1↑2`

---

Input: $$N = \begin{Bmatrix} 5&9&6\\ 8&2&4\\ 1&7&3 \end{Bmatrix}$$ Possible Output: `↑0↑2→0→2↑0→2↑1↑2←1`

---

Input: $$N = \begin{Bmatrix} 1 & 27 & 28 & 29 & 6 \\10 & 2 & 3 & 4 & 5 \\17 & 7 & 8 & 13 & 9 \\15 & 11 & 12 & 18 & 14 \\26 & 16 & 21 & 19 & 20 \\30 & 22 & 23 & 24 & 25 \end{Bmatrix}$$ Possible Output: `↑2↑1←3→0←3↓0←0←2→3↑3↑4`

---

Input: $$N = \begin{Bmatrix} 1 \end{Bmatrix} $$ Output:  or any move

---

Input: $$N = \begin{Bmatrix} 1&2\\3&4 \end{Bmatrix} $$ Output:

---

**Notes**

* There can be different correct outputs (there don't need to be necessarily the same as the test cases or the shortest one)
* You can assume it will be always a way to order the matrix
* Edges connects (like pacman :v)
* There wont be a matrix with more than 9 columns or/and rows
* Assume matrix contains only positive non-zero unique integers
* You can use any 4 distinct values other than numbers to represent the moves (in case of that, please state that in your answer)
* Column/row can be 0 or 1 indexed
* Winning criteria

---

Extra test cases are always welcome

# Answer
# JavaScript (ES6),  ~~226~~  219 bytes

Brute force search, using *right* (`"R"`) and *down* (`"D"`) moves.

Returns either a string describing the moves, or an empty array if the input matrix is already sorted. Columns and rows in the output are 0-indexed.

```
f=(m,M=2)=>(g=(s,m)=>m[S='some'](p=r=>r[S](x=>p>(p=x)))?!s[M]&&m[0][S]((_,x,a)=>g(s+'D'+x,m.map(([...r],y)=>(r[x]=(m[y+1]||a)[x])&&r)))|m[S]((_,y)=>g(s+'R'+y,m.map(([...r])=>y--?r:[r.pop(),...r]))):o=s)([],m)?o:f(m,M+2)

```

Try it online!

### Commented

```
f =                              // f = main recursive function taking:
(m, M = 2) => (                  //   m[] = input matrix; M = maximum length of the solution
  g =                            // g = recursive solver taking:
  (s, m) =>                      //   s = solution, m[] = current matrix
    m[S = 'some'](p =            // we first test whether m[] is sorted
      r =>                       // by iterating on each row
        r[S](x =>                // and each column
          p > (p = x)            // and comparing each cell x with the previous cell p
        )                        //
    ) ?                          // if the matrix is not sorted:
      !s[M] &&                   //   if we haven't reached the maximum length:
      m[0][S]((_, x, a) =>       //     try all 'down' moves:
        g(                       //       do a recursive call:
          s + 'D' + x,           //         append the move to s
          m.map(([...r], y) =>   //         for each row r[] at position y:
            (r[x] =              //           rotate the column x by replacing r[x] with
              (m[y + 1] || a)[x] //           m[y + 1][x] or a[x] for the last row (a = m[0])
            ) && r               //           yield the updated row
      ))) |                      //
      m[S]((_, y) =>             //     try all 'right' moves:
        g(                       //       do a recursive call:
          s + 'R' + y,           //         append the move to s
          m.map(([...r]) =>      //         for each row:
            y-- ?                //           if this is not the row we're looking for:
              r                  //             leave it unchanged
            :                    //           else:
              [r.pop(), ...r]    //             rotate it to the right
      )))                        //
    :                            // else (the matrix is sorted):
      o = s                      //   store the solution in o
)([], m) ?                       // initial call to g(); if we have a solution:
  o                              //   return it
:                                // else:
  f(m, M + 2)                    //   try again with a larger maximum length

```
> 3 votes

# Answer
# ~~Python 2, 296 277 245~~ Python 3, ~~200~~ 194 bytes

```
from numpy import*
def f(p):
 s='';u=[]
 while any(ediff1d(p)<0):u+=[(copy(p),s+f'v{v}',f':,{v}')for v in r_[:shape(p)[1]]]+[(p,s+'>0',0)];p,s,i=u.pop(0);exec(f'p[{i}]=roll(p[{i}],1)')
 return s

```

Try it online!

-19: unicode arrows weren't required...
-32: slightly reworked, but much slower performance on average.
-45: took some inspiration from @Arnauld's answer. Switched to Python 3 for `f''` (-4 bytes)
-6: `range( )``r_[: ]`, `diff(ravel( ))``ediff1d( )`

---

Exhaustively searches combinations of all possible  moves and `→0`. Times out on the third test case.

Since `→n` is equivalent to

```
↓0↓1...↓*(c-1)* 	*... repeated r-n times*
→0
↓0↓1...↓*(c-1)*	*... repeated n times*

```

where `r` and `c` are the numbers of rows and columns, these moves are sufficient to find every solution.

---

```
from numpy import*
def f(p):
    s=''                                    #s: sequence of moves, as string
    u=[]                                    #u: queue of states to check
    while any(ediff1d(p)<0):                #while p is not sorted
        u+=[(copy(p),s+f'v{v}',f':,{v}')    #add p,↓v to queue
            for v in r_[:shape(p)[1]]]      # for all 0<=v<#columns
        u+=[(p,s+'>0',0)]                   #add p,→0
        p,s,i=u.pop(0)                      #get the first item of queue
        exec(f'p[{i}]=roll(p[{i}],1)')      #transform it
    return s                                #return the moves taken

```

---

`>v` correspond respectively to `→↓`. (others undefined)
> 2 votes

# Answer
# Jelly, 35 bytes

```
ṙ€LXȮƊ¦1
ÇZÇZƊ⁾ULXȮOịØ.¤?F⁻Ṣ$$¿,“”Ṫ

```

Try it online!

Full program. Outputs moves to STDOUT using L for left and R for right. Keeps trying random moves until the matrix is sorted, so not very efficient in terms of speed or algorithmic complexity.
> 0 votes

---
Tags: code-golf, matrix, sorting
---


title: Return Spiral Indexes!

text:
# Question
Title: Return Spiral Indexes!
Spirals are cool , so are numbers, and number spirals are even cooler. But what if I want a specific number, in a specific place using xy coordinates...

**Challenge**

Using an infinite spiral moving down first, curling in a counterclockwise manner

ex:

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

```
1. Take negative and positive inputs(integers) in the form of (x, y)
2. When given those coordinates return the number at that position in the spiral
3. The integer inputs must be the maximum that your language can use

ex:

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

input : (0,0)
output : 0

input : (1,1)
output : 4

input : (-1,-1)
output : 8

input : (5,5)
output : 100

input : (-5, -6)
output : 121

input : (2, -5)
output : 87

input : (-9, 2)
output : 349

input : (-7, 8)
output : 271

input : (-5, -7)
output : 170

```

**Scores**

This is a codegolf, so smallest code wins!!!

# Answer
# JavaScript (ES7), 50 bytes

This is using a slightly modified version of the formula that I've used and explained in this post.

```
x=>y=>(i=4*(x*x>y*y?x:y)**2)-(x<y||-1)*(i**.5-x-y)

```

Try it online!

or Try a version that displays the spiral.
> 8 votes

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

```
·nàDtIO-I`›·<*-

```

Port of *@Arnauld*'s JavaScript (ES7) answer.
And -3 bytes thanks to *@Arnauld* as well.

My answer uses the formula:

$$T=\max((2\*x)^2, (2\*y)^2)$$

$$P=\begin{cases} 1&\text{if }y\>x\\ -1&\text{if }y\le x \end{cases}$$

$$T - (\sqrt{T} - (x+y)) * P$$

Which saves bytes with some of 05AB1E's convenient builtins, in comparison to the similar but slightly different formula *@Arnauld* uses in his answer.

Try it online or verify all test cases.

**Explanation:**

```
·                # Double both values in the (implicit) input-list
 n               # Then square both values
  à              # Take the maximum of the two
   Dt            # Duplicate it, and take its square-root
     IO-         # Subtract the sum of the input-list
        I`›      # Check if y is larger than x (1 if truthy; 0 if falsey)
           ·<    # Double it, and decrease it by 1 (1 if 1; -1 if 0)
             *   # Multiply both
              -  # Subtract them from each other (and output the result implicitly)

```
> 6 votes

# Answer
# Perl 5, 55 bytes

From @Arnauld's formula

```
/ /;$_=($i=2*max abs$`,abs$')**2-($`<$'||-1)*($i-$`-$')

```

TIO
> 3 votes

# Answer
# Jelly, 15 bytes

```
Ḥ²Ṁ©½_S×>/Ḥ’Ɗ®_

```

Try it online!

Port of @KevinCruijssen’s version of@Arnauld’s formula so be sure to upvote them.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 45 bytes

```
(For[i=j=0,ReIm@i!=#,i+=I^⌈2√++j⌉I];j)&

```

Try it online!

Generates the spiral up to the desired point
> 0 votes

---
Tags: code-golf
---