title: Produce a List of Rotonyms 1

text:
# Question
Title: Produce a List of Rotonyms 1
# Rotonyms 1

ROT13 ("rotate by 13 places") is a simple letter substitution cipher that replaces a letter with the 13th letter after it, in the alphabet. So, `A` becomes `N`, `N` becomes `A`, `B` \<-\> `O`, and so on to `M` \<-\> `Z`.

`ROT13('abcdefghijklmnopqrstuvwxyz') == 'nopqrstuvwxyzabcdefghijklm'`

A "Rotonym" is a word (pair) that ROT13s into another word (in the same language).

For example:

`ROT13('Terra') == 'Green'`

# The Challenge

Write a program or function that accepts a dictionary/word list and prints or returns a complete list of rotonyms.

1. Order doesn't matter.
2. Comparisons should be case-insensitive. Since the code can accept a dictionary, you can assume it will be passed a lower-case-only dictionary.
3. Result should be expressed as single words (not the pairs) and contain no duplicates.
4. This is .

# Example

Given

```
ask
green
irk
me
terra
vex
you

```

Return

```
green
irk
terra
vex

```

# A Real Test

Given

```
ab aba abba abe abjurer abo acieral acock adoxy advised adviser aefald affeer agena ah aha ahaunch aho ajowan albe alula alypin amesite amidic amidin amylin an ana anakes analogy anan anil ann anorexy ant apaid aparai ar arba arc areek argyle argyria arn arne aro arsheen arshin asaphic assegai atresic audian aum avar avertin avo avoid awesome ba babiism baler balita balk ban bana bar baraca bare batino bauson bawra baywood be beamage beamed bean becuna bedaub beg begrime bel bell ben ber bes beshlik beyond bhang bickern bimane bin birl bizonia bloat blunter bolero bonded bonnie boozer bor borasca boun boxhaul brava bromoil bronc bu bub bucksaw buggy built bullism bunga bunny bunt burion buttery byerite cabinda cadjan cadrans calas calends callus cameist cant capulet carpent cater caution cayuga censor cha chab chack chal chat chatta che chechen chee cheer cheery cheney chevon chian chirr cho chob cholo chopin city clerk clouted clover coach coder codworm coeval coff colic color conopid consul contra coraise corneum coster coueism cougnar couxia cowbind coz crag craggan crax crea creel crete crex crissal cross crowder cub cuba cuculus cullen cullion cur cuvy cymar czarian dabb dalles damson dand darger decapod decream deeping delible demi deworm dhanush dhoon didym diehard dill dineric disglut diss doghole donnish dorab doubled downy drop droshky dubb ducker dudish duit dungan durance ebony ehlite ejam eleven ella elohism eluder en enation endear endew enrut envy er erava erg erikite erne err ers evasive facient faden falisci fant faro fetish figment filite finless fipenny fitchet fiuman flabby flap flirter flyboat fogon foiler footle forgot fra fracas fraghan frank frater freir fu fub fubby fun fundic funt fur fury fusc gangdom ganglia gaonate garbel gast gaul gear geat gel gen gena genny gent genu gerenuk gers ghan ghat ghee gist gledy glee gnar gnat gnawing godpapa gordian gouda gra graddan granter grat greeny grr grummet grutch guacin guesten gul gun guna gunj gur gurl gurr ha hack haler hallage han haught haver he hein hen henotic her hern hetaery hexine hin hippus hiro hirudin hissing hoer hoghood homo hooklet horned howe hundi huspil hydrula hyppish ideally illeck imbed imburse immi impasse incog ing integer iowan iraq irk isobare isocrat istle ithacan ivan ivin ivoried jaunce jerry jitters juergen juha jun june junior jura kalends keacorn kemple kialee kinch kippeen kittul kohen koli komati koniga kulimit la laine lamb lapel laurate led leeward lexia liman linin linten lipan lisper loave lobcock loom luite maestri magiric mahra maimer mannose mano manuao map marcher marcid married mary maun maundy maxim medal meddler mentum merfold mew mho miamia midwise milchy molary molpe moslem mousse mudden mun muricid mysidae mysore myxa na naa nag nakhod namer nan nana navy ne nea neb neon nep nettler newtake nib nine ninon nizamut no nob nobby nodding nodiak non noon nor nourice nowhere nu nub nucleus numeral nun nunnery obe octose odso oenin off ogam ogor oh oho omasum omitter on ona onan one oner oniscus onyx oppidan or ora ore orf orlo orna orotund orphan ort ory osamine ourie outpay ova overget ovey palama paludic panical panisic pavia penk pent perjury perk pern perry phil pho phon phonics pickee picture pien pimpled piously pirl pit platty pledger pollack pomato ponerid poria postic poteye poulter pounce powdry prefer privy profile pross pruner psaltes psylla pub pun punatoo pung punicin puno puny pur purpura purr purre purrel pusscat pyrex pyropen pyropus quader qubba ra rabi rabitic rail rappage rarity re reaal rear rebend redcoat redweed ree rees ref regrasp reluct renin replate reseize residua ret retour retral rheic rhymer rife rifling ripping robing rohuna romanly romic rookish rumor rupial sairve saltant saltery salvo samekh scissel scraw scrubby seafolk seaware seldor sen serer serve setness seton setsman setting settlor sex sexto sh sha shag shave she shedded shel sher sho shool showish shrinal shrip shrove sievy sinus sinusal sirrah sis skither slait sley slicken slinker sloven smoker snag snap snath sneb sniping snithe soiling sort sourer spalax spent spex spidger spirt spiry spryly spyship squalor stilt strive strue styrian sucuriu suevi summary sumpter sundry swahili sylphy sync taccada talao tane tang tanghin tanglad tankert tarazed tarve taxon tealery teaser tecuna tee telical ten teng tercio terral terrify testily tha than thaw the thecate thee theft they thistle thob thole thone thorny thy thymoma timawa tiphead titrate toadess tomnoup tomosis toplike toryess tra trag trah train tran tref tremble triarch trilobe try tubbie tueiron tumored tuna tung tuning turfdom turr tweil tyrr ulcery un una unaloud unfrank unionid unkeyed unlit unmount unoften unpiety unscent unspike unurban unwhig unwon upperch uprid ur ura ure urea urocyon urva usurp uta utopian uva vacancy vacuist valkyr valois vapored vari vat vejoces vend verd vesbite vesicae vex victim vina vitals viva walloon warori warp waucht wearily weblike wedded weftage wha whample whar when whence whites whorish whun wilhelm wincey wog woodlet wouch wuzzer yakona yamp yaru yerava yezdi ym yn za zimme

```

Return

```
ab aba abba abe abjurer abo ah aha aho an ana anan anil ann ant ar arba arc arn aro avar avo ba balk ban bana bar bare be bean becuna beg bel ben ber bes bin birl bor brava bu bub cha chab chal chat che chechen chee cheer cheery cho clerk crag crax crea creel crex cub cuba cuvy dhoon en envy er erava erg erne err ers fant faro flap fra freir fu fub fubby fun funt fur fury gel gen gena gent genu gers ghan ghat ghee glee gnar gnat gra grat greeny grr gul gun guna gunj gur gurl gurr ha han he hein hen her hern hin ing iraq irk ivan ivin juha jun june jura la na naa nag nan nana navy ne nea neb neon nep nib nine no nob non noon nor nowhere nu nub nun obe oenin oh oho on ona onan one oner onyx or ora ore orf orna orphan ort ory ova ovey penk pent perk pern perry phil pho phon pub pun pung puno puny pur purpura purr purre purrel pyrex qubba ra rail re rear ree ref renin ret sen serve sh sha shag she shel sho shool snag sneb sync tane tang tee ten teng terral tha than thaw the thee they thy tra trag trah tran tref try tuna tung turr tyrr un una ur ura ure urea urva uva vat vend vex vina viva wha whar when whun yn

```

# Answer
> 7 votes
# Jelly, 7 bytes

*Two bytes were saved by turning this into a function, as suggested by @EriktheOutgolfer.*

A function expecting a list of strings in lowercase and returning a list of Jelly strings.

```
O_5ịØaf

```

Try it online!

### How?

```
O_5ịØaf    - link taking a list of strings such as ['irk','me','vex']
O          - convert to ASCII codes         --> [[105,114,107], [109,101], [118,101,120]]
 _5        - subtract 5 ((-96 + 13) mod 26) --> [[100,109,102], [104, 96], [113, 96,115]]
    Øa     - yield the lowercase alphabet   --> 'abcdefghijklmnopqrstuvwxyz'
   ị       - pick new letters from there
             (modulo 26)                    --> ['vex','zr','irk']
      f    - filter out elements that are
             not in the original list       --> ['vex','irk']

```

# Answer
> 6 votes
# Attache, 12 bytes

```
{Rot=>_∩_}

```

Try it online! (10 chars)

I thought I'd never see the day where `Rot` came in handy... :D

On Attache's showcase entry, I said that `Rot` is a residual command from its days of being a joke language. It's default behaviour is Rot13.

## Explanation

```
{Rot=>_∩_}
{        }    anonymous lambda. argument: _
 Rot=>_       calculate all rot-13 shifts of each item in _
       ∩_     and keep only those that were in _ (by using an intersection)

```

## Extended test case

Try it online!

## Alternatives

**14 bytes:** `{_&Has\Rot=>_}`

**14 bytes:** `{`in&_\Rot=>_}`

(Both of these work by filtering using functions.)

# Answer
> 5 votes
# Python 2, ~~70~~ 63 bytes

```
lambda l:l&{''.join(chr((ord(c)-6)%26+97)for c in w)for w in l}

```

Try it online!

# Answer
> 4 votes
# MATL, 16 bytes

```
tot2Y2t13YSXEXm)

```

Try it online!

### Explanation

The stack is shown upside down, that is, the most recent element is below.

```
t        % Implicit input: cell array of strings. Duplicate
         % STACK: {'ask' 'green' 'irk' 'me' 'terra' 'vex' 'you'}
         %        {'ask' 'green' 'irk' 'me' 'terra' 'vex' 'you'}
o        % Convert to double. Gives a matrix, right-padding with 0
         % STACK: {'ask' 'green' 'irk' 'me' 'terra' 'vex' 'you'}
         %        [97 115 107   0   0; ...; 121 111 117   0   0]
t        % Duplicate
         % STACK: {'ask' 'green' 'irk' 'me' 'terra' 'vex' 'you'}
         %        [97 115 107   0   0; ...; 121 111 117   0   0]
         %        [97 115 107   0   0; ...; 121 111 117   0   0]
2Y2      % Push predefined literal 'abc...xyz'
         % STACK: {'ask' 'green' 'irk' 'me' 'terra' 'vex' 'you'}
         %        [97 115 107   0   0; ...; 121 111 117   0   0]
         %        [97 115 107   0   0; ...; 121 111 117   0   0]
         %        'abc...xyz'
t13YS    % Duplicate. Circularly shift by 13 positions
         % STACK: {'ask' 'green' 'irk' 'me' 'terra' 'vex' 'you'}
         %        [97 115 107   0   0; ...; 121 111 117   0   0]
         %        [97 115 107   0   0; ...; 121 111 117   0   0]
         %        'abc...xyz'
         %        'nop...klm'
XE       % Replace entries in the 1st input that are in the 2nd input by
         % those of the 3rd input
         % STACK: {'ask' 'green' 'irk' 'me' 'terra' 'vex' 'you'}
         %        [97 115 107   0   0; ...; 121 111 117   0   0]
         %        [110 102 120   0   0; ...; 108  98 104   0   0]
Xm       % Ismember-rows: true for rows of 1st input that are in the 2nd
         % STACK: {'ask' 'green' 'irk' 'me' 'terra' 'vex' 'you'}
         %        [false; true; true; false; true; true; false]
)        % Index. Implicit display
         % STACK: {'green' 'irk' 'terra' 'vex'}

```

# Answer
> 4 votes
# APL (Dyalog Unicode), ~~19~~ 17 bytesSBCS

Anonymous tacit prefix function, taking a list of uppercase words. Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems.

```
⊢∩{⎕A[⍵⍳⍨13⌽⎕A]}¨

```

Try it online! (edit: now with big word list!)

the argument's

intersection with

`{` the result of the following function applied to each word ( is the word):

`⎕A[``]` index the uppercase **A**lphabet with:

`⍵⍳⍨` the indices of the word into

`13⌽` the rot-13 of

`⎕A` the uppercase **A**lphabet

# Answer
> 4 votes
# Python 2, 40 bytes

```
lambda l:l&{w.encode('rot13')for w in l}

```

Try it online!

# Answer
> 3 votes
# JavaScript (Node.js), 59 bytes

*Saved 1 byte thanks to @ovs*

Takes input as an array of strings in lowercase. Returns an array of strings.

```
a=>a.filter(s=>a.some(S=>Buffer(S).map(c=>(c-6)%26+97)==s))

```

Try it online!

### Commented

```
a =>                  // given the input array a[]
  a.filter(s =>       // for each string s in a[]:
    a.some(S =>       //   for each string S in a[]:
      Buffer(S)       //     create a buffer from S (deprecated method)
      .map(c =>       //     for each byte c in the buffer:
        (c - 6) % 26  //       apply rot13 transformation ((-97 + 13) mod 26 = -6)
        + 97          //       and convert it back to [a-z]
      ) == s          //     implicit coercion to string; compare with s
    )                 //   end of some()
  )                   // end of filter()

```

# Answer
> 3 votes
# Retina 0.8.2, 42 bytes

```
.+
$&¶$&!
T`l`n-zl`.+!
O`
!`\b(.+)(?=¶\1!)

```

Try it online! Explanation:

```
.+
$&¶$&!

```

Duplicate all of the words, suffixing a `!` to the duplicate.

```
T`l`n-zl`.+!

```

ROT13 all of the duplicates.

```
O`

```

Sort the words.

```
!`\b(.+)(?=¶\1!)

```

Find the duplicates.

# Answer
> 2 votes
# Perl 6,  ~~57~~  35 bytes

```
.say for ($/=lines.Set).keys.grep:{$/{TR/a..z/n..za..m/}}

```

Try it

```
{@^a.grep:{@a∋TR/a..z/n..za..m/}}

```

Try it

## Expanded:

```
{  # bare block lambda with placeholder parameter @a

  @^a                # declare and use placeholder parameter
  .grep:             # find all the values in it that match the following
  {
    @a
    ∋                 # Set contains operator
    TR/a..z/n..za..m/ # do the rotation on the grepped value
  }
}

```

# Answer
> 2 votes
# Ruby, ~~45~~ 35 bytes

-10(!) thanks to G B

```
->a{a&a.map{|x|x.tr"a-z","n-za-m"}}

```

Try it online!

# Answer
> 1 votes
# Python 2, ~~101~~ 94 bytes

```
lambda d:[w for w in d if{''.join(chr((ord(c)+i)%26+97)for c in w)for i in range(26)}&(d-{w})]

```

Try it online!

Takes a set of words (lowercase), and returns a list of rotonyms.

# Answer
> 1 votes
# Perl 5 `-a`, 40 bytes

```
y/a-z/n-za-m/;for$i(@F){/\b$i\b/&&say$i}

```

Try it online!

Input is as a space separated list of words.

# Answer
> 1 votes
# Python 3, ~~68~~ 60 bytes

```
lambda d:d&{encode(w,"rot13")for w in d};from codecs import*

```

Although we could put the `import` on the previous line without penalty, it just seems more amusing this way. The function now only accepts the dictionary as a `set`, which makes a huge performance improvement for very large dictionaries.

# Answer
> 1 votes
# C (gcc), 137 bytes

```
char*a,*b,x[99];f(_)char*_;{strcpy(x,_);for(a=strtok(x," ");a=strtok(0," ");strstr(_,a)&&printf("%s ",a))for(b=a;*b;++b)*b=(*b-6)%26+97;}

```

Try it online!

Description:

```
char*a,*b,x[99];                        // Variables
f(_)char*_;{                            // f(space separated string)
    strcpy(x,_);                        // copy input to x
    for(a=strtok(x," ");                // loop from first word
        a=strtok(0," ");                // to last word
        strstr(_,a)&&printf("%s ",a))   // at each step printing if found in original string
                                        // this occurs after the next loop which
                                        // rot13's the loop argument 'a'
        for(b=a;*b;++b)                 // for each character in a
            *b=(*b-6)%26+97;}           // set it to its rot13 variant (x-6)%26+97 for ascii

```

# Answer
> 1 votes
# 05AB1E, ~~13~~ ~~12~~ 10 bytes

```
εAA2äRJ‡}Ã

```

-2 bytes thanks to *@Emigna*.

Try it online.

**Explanation:**

```
            # example input: ["ask","green","irk","terra"]
ε       }   # For-each over the input-list:
 A          #  Take the lowercase alphabet twice
  A2äRJ     #  Split the alphabet in halve, reverse both parts, and joined it back together
            #   → nopqrstuvwxyzabcdefghijklm
       ‡    #  Transliteral; changing the characters in the input-words, from
            #  the letters in the alphabet, to the letters in the ROT-13 alphabet
            #   → ['nfx','terra','vex','green']
         Ã  # Remove all items from the input-list, that are not in the list above
            #  → ['green','terra']

```

---

**Old 12-byte version:**

```
Ç6-₂%εAsèJ}Ã

```

-1 byte thanks to *@Emigna* changing `мм` to `Ã` (couldn't find this builtin myself in the available commands).

Try it online.

**Explanation:**

```
               # example input: ["ask","green","irk","terra"]
Ç              # Convert all input-characters to their unicode values
               #  → [[97,115,107],[103,114,101,101,110],[105,114,107],[116,101,114,114,97]]
  6-₂%         # Subtract 6, and take modulo-26
               #  → [[13,5,23],[19,4,17,17,0],[21,4,23],[6,17,4,4,13]]
      ε    }   # For-each:
       Asè     #  Take the letters from the lowercase alphabet at the calculated indices
               #   → [['n','f','x'],['t','e','r','r','a'],['v','e','x'],['g','r','e','e','n']]
          J    #  Join all letters together again
               #   → ['nfx','terra','vex','green']
            Ã  # Remove all items from the input-list, that are not in the list above
               #  → ['green','terra']

```

# Answer
> 1 votes
# Java (JDK 10), 97 bytes

```
l->l.stream().filter(s->l.contains(new String(s.chars().map(m->m%26+65).toArray(),0,s.length())))

```

Try it online!

# Answer
> 1 votes
# Pyth, 11 bytes

```
@ms@LGm-Ck6

```

Try it online

Expects input as an array of lowercase words. Explanation:

```
@ms@LGm-Ck6dQQ   Q=input(), final 3 tokens are implicit

 m          Q    For each word d in input, map over...
      m    d       For each letter k in d, map over...
        Ck           Convert to ASCII code point
       -  6          Subtract 6
   @LG             Modular index each over the lowercase alphabet (G)
  s                Join each array of chars into a string
@            Q   Filter the input on presence in the resulting set

```

# Answer
> 1 votes
# Julia 0.6, 49 bytes

```
W->filter(w->String(([w...].-'S')%26.+'`')∈W,W)

```

Try it online!

Takes a `Set` of words and returns a `Set` of rotonyms.

`[w...]` takes a string `w` and "explodes" it into an array of `Char`s, which enables us to do arithmetic on it. The `String` call does the reverse, making a string from an array of `Char`s after the arithmetic operations are done. We have to subtract `'S'` and not 83, because `Char`-`Char` is an `Int` on which `%` works, whereas `Char`-`Int` is a `Char` which would lead to an error. Similarly, adding `'`'` changes the result of the mod from `Int` back to a `Char`, which is necessary for the `String` call to work.

# Answer
> 0 votes
# JavaScript, 93 bytes

Takes input as an array of lowercase words, filters the array by the result of a lookup for the rot13 result.

```
d=>d.filter(t=>d.indexOf(t.replace(/[a-z]/ig,c=>((parseInt(c,36)+3)%26+10).toString(36)))>-1)

```

# Answer
> 0 votes
# PHP, 60 bytes

Given an array of words, echos only those having a rotonym match

`foreach($l as$w)if(in_array($j=str_rot13($w),$l))echo"$w\n";`

Try it online!

---
Tags: code-golf, alphabet
---


title: Self-Identifying Coordinates

text:
# Question
Title: Self-Identifying Coordinates
Write a program or function that, given an integer `n`, construct an array with `n` dimensions of `n` length, where each element is an identifier of its own coordinates. That is, starting with one array, populate it with `n` arrays, where each of those contain `n` more arrays, up to a depth of `n-1`. The elements of the deepest arrays are the coordinates describing where they are in the full array.

Some examples in case my explanation was confusing.

### n = 1

```
["1"]

```

### n = 2

```
[
 ["11", "12"],
 ["21", "22"]
]

```

### n = 3

```
[
  [
    ["111","112","113"],
    ["121","122","123"],
    ["131","132","133"]
  ],
  [
    ["211","212","213"],
    ["221","222","223"],
    ["231","232","233"]
  ],
  [
    ["311","312","313"],
    ["321","322","323"],
    ["331","332","333"]
  ]
]

```

Here, "321" means it is the 1st element of the 2nd element of the 3rd array.

### Rules:

* Coordinates and dimension (`n`) can be either 0 or 1 indexed
* You may assume `n` is single digit, below 10 for both indexing options to prevent ambiguous outputs
* IO is flexible.
    + In particular, coordinates can be arrays, strings etc. as long as they are clear. "321" =\> \[3,2,1\]
    + Output can be integers in base 10 with or without leading zeroes.
    + Coordinates can be in reverse order if you wish, as long as it is consistent. "321" =\> "123"
    + Output doesn't necessarily have to be an array structure in your language. As long as there's clear distinct markers for the start of an array, end of an array and for separating elements.
    + The output for `n=1` can just be 1
    + If your output is atypical, make sure to explain the format.
* This is so the shortest solution in each language wins!

# Answer
> 19 votes
# Dyalog APL, ~~5~~ 3 bytes

```
⍳⍴⍨

```

-2 bytes thanks to FrownyFrog

Try it online!

gives all the indices given the shape of an array. e.g. 2 3.
reshapes the right arg to be the size of the left arg.  makes both be the right arg.

# Answer
> 10 votes
# Python 3, 56 bytes

```
f=lambda n,*l:len(l)//n*l or[f(n,*l,k)for k in range(n)]

```

Try it online!

Mr. Xcoder saved 2 bytes switching to Python 3 for starred unpacking.

# Answer
> 9 votes
# Wolfram Language (Mathematica), ~~32~~ 22 bytes

<sup>-10 bytes thanks to @alephalpha</sup>

```
Array[List,#~Table~#]&

```

Try it online!

# Answer
> 6 votes
# Jelly, ~~8~~ 7 bytes

```
ṗ³s³$³¡

```

Try it online!

**Explanation**

Use argument 2 as an example.

```
ṗ³s³$³¡
ṗ        Cartesian power with power
 ³       2 (the argument). Autoranges the left arg.
         Yields [[1,1],[1,2],[2,1],[2,2]]
    $³¡  Do 2 times:
  s³     Split into segments of length 2.
         This last step molds the array of indices into the proper shape.

```

---

If `¡` didn't vary it's right argument over iterations for dyads then this would be 4 bytes: `ṗs³¡`

# Answer
> 6 votes
# , 18 bytes

```
,"1/^:(]{:)~@,.@i.

```

Try it online!

Iterative solution, no built-in cartesian product. This is what peak J looks like.

```
                       input                                    2
                i.     range                                 0, 1
             ,.@       reshape each element
                       into a one-dimensional array        [0],[1]   (A)
    ^:(]{:)            (input−1) times...             (1 iteration)
,"1/       ~@             prepend the contents of each 1d array in A    |
                          to every 1d array from the previous iteration,|
                          assembling the results for each A[n] into     |!CANTEXPLAINTHIS!
                          a larger array                                |
                                                         [ [0,0],       |
                                                           [0,1] ],     |
                                                         [ [1,0],       |
                                                           [1,1] ]      |

```

# Answer
> 5 votes
# J, 13 bytes

```
[:{[;/@$,:@i.

```

Try it online!

Interesting this is so much longer than the APL answer (though that may be my inability to see a better translation)

## explanation

```
[: { [ ;/@$ ,:@i.

     [                NB. the argument
            ,:@i.     NB. range 0..arg, considered as one item: ,: is "itemize"
          $           NB. repeat the right range the left number of times
       ;/@            NB. and then put boxes around them. so, eg, if we had
                      NB. an arg of 3, now we have the list of boxes
                      NB. [0 1 2][0 1 2][0 1 2]
[: {                  NB. { is "Catalog", it creates the cartesian product
                      NB. in exactly the format we desire.

```

# Answer
> 5 votes
## MATLAB, 92 89 55 bytes

I have a different answer having re-read the rules of the challenge, but I'll leave the previous attempt below as it's different and still fun to look at.

```
reshape(string(dec2base(0:n^n-1,n+(n<2))),[~(1:n)+n 1])

```

**Explanation**

```
                        0:n^n-1                        % [0,1,...,n^n-1]
               dec2base(       ,n+(n<2))               % Put into base n (base 2 if n=1)
        string(                         )              % Convert to strings
                                          [~(1:n)+n 1] % Dimension array [n,n,...,n] (length n)
reshape(                                 ,            )% Use dim array to reshape

```

This outputs an n-dimensional array of strings which are 0 indexed.

**Previous Answer (89 bytes)**

My first golf! This can likely be reduced more but I thought I'd post what I've got.

```
x=(1:n)';for d=2:n;y=((1:n)*10^(d-1));o=[];for p=1:nnz(y);o=cat(d,o,(x+y(p)));end;x=o end

```

**Explanation**

```
x=(1:n)';                       % Create array x=[1,2,...n]'
for d=2:n                       % d for dimension
    y=((1:n)*10^(d-1));         % Creates an array for each d where
                                %   y=[10,20,30,...] for n=2
                                %   y=[100,200,...] for n=3 etc.
    o=[];                       % o for output
    for p=1:nnz(y)              % For each value of y
        o=cat(d,...             % Concatenate in the dth dimension:
            o,...               % - The current output
            x+y(p));            % - The sum of
                                %   - The array from the last dimension
                                %   - The current value in y (e.g. 100)
    end
    x=o                         % Send the output to x for the next loop
end

```

Outputs x at the end to give solution

Similar to the other MATLAB post, the output is an n-dimensional array, except it uses numbers to display the coordinates. It works for any value, although because loops are bad in MATLAB it begins to slow down significantly around n = 8.

Edit: -2 bytes thanks to Luis Mendo. Also removed final semicolon to print the output.

# Answer
> 5 votes
# Rust, ~~201~~ ~~176~~ ~~167~~ ~~166~~ 154 bytes

```
enum L{S(String),L(Vec<L>)}fn
h(n:u8,d:u8,s:&str)->L{if
d<1{L::S(s.into())}else{L::L((0..n).map(|i|h(n,d-1,&format!("{}{}",s,i))).collect())}}|n|h(n,n,"")

```

Try it online!

The output type is a sum type with two variants as the language is strictly typed. It can be either `L`, which is a list type containing this sum type or `S` which is a result type (a string). The result can look like this.

```
L::L([
 L::L([ L::S("00"), L::S("01") ]),
 L::L([ L::S("10"), L::S("11") ]),
])

```

Also, reformatted using `rustfmt`:

```
enum L {
    S(String),
    L(Vec<L>),
}
fn h(n: u8, d: u8, s: &str) -> L {
    if d < 1 {
        L::S(s.into())
    } else {
        L::L(
            (0..n)
                .map(|i| h(n, d - 1, &format!("{}{}", s, i)))
                .collect(),
        )
    }
}
|n| h(n, n, "")

```

# Answer
> 4 votes
# , 102 bytes

```
function(n,m=array(T,rep(n,n)))`if`(n<2,'1',{m[]=apply(which(m,T)[,`[<-`(1:n,1:2,2:1)],1,toString);m})

```

Try it online!

* 1-indexed, reversed
* unfortunately R stores matrix by column, otherwise we could go down to 73 bytes
* -9 bytes saved thanks to @Giuseppe suggestion to use `which` array indexing

# Answer
> 4 votes
# Java 10, 144 bytes

The solution is method `f`. It produces a string representation of the array.

```
String h(int n,int d,String s){if(d<1)return s;var r="[";for(int i=0;i++<n;)r+=h(n,d-1,s+i)+",";return r+"]";}String f(int n){return h(n,n,"");}

```

Try It Online

## Ungolfed

```
String h(int n, int d, String s) {
    if (d < 1)
        return s;
    var r = "[";
    for (int i = 0; i++ < n;)
        r += h(n, d - 1, s + i) + ",";
    return r + "]";
}
String f(int n) {
    return h(n, n, "");
}

```

## Acknowledgments

# Answer
> 3 votes
# JavaScript (Node.js), ~~62~~ ~~60~~ 58 bytes

```
f=(n,i=n,s='')=>i?[...Array(n)].map((_,j)=>f(n,i-1,s+j)):s

```

Try it online! Output is 0-indexed. Edit: Saved 2 bytes thanks to @JoKing and a further 2 bytes thanks to @Arnauld.

# Answer
> 3 votes
# 05AB1E, 7 bytes

```
LsãsGsô

```

Try it online!

**Explanation**

```
L          # push range [1 ... input]
 sã        # input repeated cartesian products of the list
   sG      # input - 1 times do:
     sô    # split into input parts

```

# Answer
> 3 votes
## MATLAB, 116 108 104 bytes

I feel like there must be a shorter way to do this, given MATLAB's affinity toward multi-dimensional matrices... Thanks to Luis for the 4 bytes from some short-handing

```
a=~(1:n)+n;c=cell(1,n);[c{:}]=ind2sub(a,1:n^n);reshape(arrayfun(@(varargin)[varargin{:}],c{:},'un',0),a)

```

**Explanation**

```
% For using twice, define the array of dimension sizes [n, n, .., n]
a=~(1:n)+n;
% To group variable number of outputs from ind2sub into a cell array
c=cell(1,n);
% Convert linear indices to self-describing coordinates
[c{:}]=ind2sub(a,1:n^n);
% reshape to make it the n-dimensional array
% arrayfun to loop over the numerous ind2sub outputs simultaneously
% varargin and {:} usage to account for various numbers of inputs
reshape(arrayfun(@(varargin)[varargin{:}],c{:},'uni',0),a)

```

The output is an n-dimensional cell array, where each element is an array of the coordinate values. Works for any `n` without ambiguity because of the numeric array output, so long as an `n^(n+1)` element array can be stored in RAM!

# Answer
> 3 votes
# Charcoal, 26 bytes

```
Ｎθ≔ＥＸθθ⪫⪪◧⍘ιθθ ¦0υＦθ≔⪪υθυυ

```

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

```
Ｎθ

```

Input `n`.

```
≔ＥＸθθ⪫⪪◧⍘ιθθ ¦0υ

```

Generate all `nⁿ` `n`-digit numbers in base `n`.

```
Ｆθ≔⪪υθυ

```

Split them `n` times into an `n`-dimensional array where each dimension is of size `n`.

```
υ

```

Print the array. The default output format is each element on its own line, then each block of `n` lines is terminated by a blank line, then each block of `n` blocks of `n` lines is terminated by a second blank line, and so on up to `n-1` blank lines at the top level.

# Answer
> 2 votes
# Jelly, 7 bytes

```
ṗṁẋ`ŒṬ$

```

Try it online!

---
Tags: code-golf
---