# N-dimensional N^N array filled with N

In: Enough memory and a positive integer N

Out: N-dimensional N^N array filled with N, where N^N means N terms of N-by-N-by-N-by...

Examples:

1: [1] which is a 1D array (a list) of length 1, containing a single 1

2: [[2,2],[2,2]] which is a 2D array (a table) with 2 rows and 2 columns, filled with 2s

3: [[[3,3,3],[3,3,3],[3,3,3]],[[3,3,3],[3,3,3],[3,3,3]],[[3,3,3],[3,3,3],[3,3,3]]] which is a 3D array (a cube) with 3 layers, 3 rows, and 3 columns, filled with 3s

4: [[[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]],[[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]],[[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]],[[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]]] 

5 and 6: Please see one of the answers.

• If our language does not support arrays, what would be an acceptable output format?
– Okx
Feb 28 '17 at 16:54
• Since "Enough memory" is part of the input, I want to see an answer that controls a robot to actually take the memory as input and plug it in before using it. Feb 28 '17 at 19:05
• Do all the arrays need to be distinct objects?
– Neil
Mar 1 '17 at 0:25
• @user2357112 I think that's more of a precondition type issue. I doubt the op actually expects the function to accept memory as input. Mar 1 '17 at 4:31
• @TheGreatDuck Correct, but I'm pretty sure user2357112 meant it as a joke.
Mar 1 '17 at 5:47

# Python, 32 bytes

lambda n:eval('['*n+'n'+']*n'*n)


Try it online!

Makes a string like "[[[n]*n]*n]*n" with n multiplcations, and evaluates it as Python code. Since the evaluation happens within the function scope, the variable name n evaluates to the function input.

• the scope trick is genius Feb 28 '17 at 19:09
• +1, that eval trick really golfs down a lot of bytes Mar 26 '19 at 1:28

# J, 4 bytes

$~#~  Try it online! ## Explanation $~#~  Input: integer n
#~  Create n copies of n
$~ Shape n into an array with dimensions n copies of n  • When I saw the challenge title, I thought of J immediately. Pretty cool that J even beats Jelly (the golfing language inspired by J). – Dane Feb 28 '17 at 18:56 • There's also $~$~ which is equivalent while also repeating itself Mar 1 '17 at 23:53 • $~$~ translated to English... MONEY, get more of, MONEY, get more of... Mar 2 '17 at 21:38 # APL (Dyalog APL), 4 bytes ⍴⍨⍴⊢  Try it online! # Mathematica, 22 20 bytes (t=Table)@@t[#,#+1]& (* or *) Table@@Table[#,#+1]&  ## JavaScript (ES6), 44 40 bytes f=(n,k=i=n)=>i--?f(n,Array(n).fill(k)):k  ### Demo f=(n,k=i=n)=>i--?f(n,Array(n).fill(k)):k console.log(JSON.stringify(f(1))) console.log(JSON.stringify(f(2))) console.log(JSON.stringify(f(3))) console.log(JSON.stringify(f(4))) # Octave, 35332523 20 bytes @(N)ones(N+!(1:N))*N  Try it online! @(N)ones(N*ones(1,N))*N @(N)repmat(N,N*ones(1,N))  Thanks to @LuisMendo saved 8 bytes @(N)ones(num2cell(!(1:N)+N){:})*N  Try it online! Previous answer: @(N)repmat(N,num2cell(!(1:N)+N){:})  Try it online! • @LuisMendo Rats, I was just going to post that one ;) Feb 28 '17 at 17:29 • @beaker Whoops :-) Feb 28 '17 at 17:31 # R, 26 This is the obvious answer but perhaps there is something cleverer? n=scan();array(n,rep(n,n))  • is scan() necessary? – Adám Feb 28 '17 at 21:42 • Looking at the other answers, it seems like it either has to be a function or accept input somehow? Feb 28 '17 at 21:43 • Right, I don't know R at all. I just thought that you could specify a function somehow instead. – Adám Feb 28 '17 at 21:58 • Yes, you can replace n=scan(); by function(n) but it makes it longer. Mar 1 '17 at 1:19 • You can save one byte by putting the n assignment inside of array: array(n<-scan(),rep(n,n)). Mar 2 '17 at 8:49 # Haskell, 52 bytes f n=iterate(filter(>'"').show.(<$[1..n]))(show n)!!n


Try it online!

Inspired by @nimi's answer, but using more predefined functions.

• Uses iterate and !! instead of a recursive help function.
• Instead of constructing list delimiters "by hand", uses filter(>'"').show to format a list of strings, then stripping away the extra " characters.

# 05AB1E (legacy), 6 5 bytes

-1 thanks to Kevin Cruijssen

F¹.D)


Try it online!

F     # For 0 .. input
¹.D) # Push <input> copies of the result of the last step as an array

• The leading D can be removed because the input is used implicitly again (not sure if this was a thing when you posted the answer, but you don't need the explicit D anymore now). Feb 21 '19 at 13:05
• @KevinCruijssen I think this is one of the answers that gave us the idea to take implicitly input multiple times :) Feb 21 '19 at 14:23
• Ah ok. I was indeed expecting it to not be implicitly yet at the time of posting, but realized that after posting my comment (which I edited). ;) Sometimes it's funny how much explicit things are being done by old answer (usually pre-2017), and how much shorter it can be done now. Feb 21 '19 at 14:25

## Haskell, 62 bytes

n#0=show n
n#l='[':tail((',':)=<<n#(l-1)<$[1..n])++"]" f n=n#n  Usage example: f 2 -> "[[2,2],[2,2]]". Try it online!. Haskell's strict type system prevents a function that returns nested lists of different depths, so I construct the result as a string. How it works: n#l= n with the current level l is '[': a literal [ followed by n#(l-1)<$[1..n]   n copies of   n # (l-1)
(',':)=<<            each prepended by a , and flattened into a single list
tail                   and the first , removed
++"]"      followed by a literal ]

n#0=show n                   the base case is n as a string

f n=n#n                      main function, start with level n

• We can do the same idea shorter with more builtin functions: f n=iterate(filter(>'#').show.(<$[1..n]))(show n)!!n. Mar 1 '17 at 0:44 • @ØrjanJohansen: that's a great idea. Please post it as a separate answer. – nimi Mar 1 '17 at 6:04 • Could you shave a byte with (#0)=show? Not too familiar with Haskell Mar 1 '17 at 23:56 • @Cyoce: No, that's a syntax error. For a correct syntax I could flip the arguments and use (#)0=show, but all definitions of a function must have the same number of arguments. The second line (n#l='['...) needs two arguments, so the first line must also have two arguments. – nimi Mar 2 '17 at 6:06 # MATL, 8 bytes ttY"l$l*


Try it at MATL Online (I have added some code showing the actual size of the output since all n-dimensional outputs in MATL are shown as 2D matrices where all dimensions > 2 are flattened into the second dimension).

Explanation

        % Implicitly grab the input (N)
tt      % Make two copies of N
Y"      % Perform run-length decoding to create N copies of N
seq -f$1o%.fd$n+1-p $n|dc|rev|sed -r "s/(0+|$[$1-1]*).*$/\1/;s/^(0*)/\1$1/;s/^1/[1]/"|tr \\n0$[$1-1] \ []  Try it online! The program essentially counts from 0 to (n^n)-1 in base n, where n is the input. For each base-n number k in the count, it does the following: 1. If k ends with at least one digit 0, print a '[' for each digit 0 at the end of k. 2. Print n. 3. If k ends with at least one digit n-1, print a ']' for each digit n-1 at the end of k. (The value n=1 needs to have brackets added as a special case. This input value also generates some output to stderr, which can be ignored under standard PPCG rules.) Maybe there's a shorter way to implement this idea. Sample run: ./array 3 [[[3 3 3] [3 3 3] [3 3 3]] [[3 3 3] [3 3 3] [3 3 3]] [[3 3 3] [3 3 3] [3 3 3]]]  • My Zsh solution could probably translate to Bash Aug 29 at 1:21 # MathGolf, 5 4 bytes _{a*  Try it online! ## Explanation using n = 2 (note that the outermost [] are not arrays, but are just there to show the stack) _ duplicate TOS (stack is [2, 2]) { loop 2 times (stack is [2]) a wrap in array ([2] => [[2]], [[2, 2]] => [[[2, 2]]]) * pop a, b : push(a*b) ([[2]] => [[2, 2]], [[[2, 2]]] => [[[2, 2], [2, 2]]])  # Raku, 21 bytes try it online! {[[xx] [xx]$_ xx 3]}

• Welcome to Code Golf! Nice first answer. Aug 29 at 1:52

# Perl 6, 25 bytes

{($^n,{$_ xx$n}...*)[$n]}


Starts with n, and iteratively applies the "repeat n times" transformation n times, each time creating an additional level of List nesting.

Try it online!

• Use $_ instead to save a byte – Jo King Jun 23 '18 at 0:28 • @JoKing: I already use $_ as the inner block's parameter, so I can't use it as the outer block's parameter as well.
– smls
Aug 23 '18 at 21:46
• Yes, but $n and $_ always have the same value. Try it online!
– Jo King
Aug 23 '18 at 22:59

# PHP, 70 62 bytes

This is the simplest I can come up with.

for(;$i++<$n=$argv[1];)$F=array_fill(0,$n,$F?:$n);print_r($F);


Takes the input as the first argument and prints the resulting array on the screen.

Thanks to @user59178 for saving me 8 bytes!

• Pre-assigning variables like that is unnecessary, as is $l. Dropping the $i=0, & replacing $lwith $n saves 7 bytes. An additional byte can be saved by not assigning $F, assigning $n in the conditional and using a ternary $F?:$n in the array_fill() Mar 1 '17 at 9:28
• @user59178 I don't know if this is what you had in mind or not, but, thank you for the tips. You've saved me 8 bytes! Mar 1 '17 at 9:38

# Clojure, 36 bytes

#(nth(iterate(fn[a](repeat % a))%)%)


Iterates function which repeats its argument n times, it produces infinite sequence of such elements and then takes its nth element.

# Rebol, 45 bytes

func[n][array/initial append/dup copy[]n n n]


# Clojure, 49 bytes

(defmacro r[n](->> ~n ~@(repeat n(repeat ~n))))


Not the shortest Clojure example, but I amused myself with the quoting and unquoting.