| Bytes | Lang | Time | Link |
|---|---|---|---|
| 008 | Japt | 250513T161611Z | Shaggy |
| 049 | Janet | 250513T093309Z | Adam |
| 048 | Red | 250513T070142Z | Galen Iv |
| 100 | Nim | 250513T055954Z | janAkali |
| 028 | Juby | 250513T030349Z | Jordan |
| 004 | Uiua | 230928T233121Z | chunes |
| 003 | Thunno 2 | 230620T181739Z | The Thon |
| 020 | Arturo | 230221T131658Z | chunes |
| 009 | K ngn/k | 221215T200714Z | naffetS |
| 004 | BQN | 221215T185010Z | DLosc |
| nan | 221215T163424Z | bigyihsu | |
| 008 | MATL | 170228T171930Z | Suever |
| 002 | Vyxal | 220415T014240Z | naffetS |
| 076 | tinylisp | 220414T024405Z | des54321 |
| 033 | Pari/GP | 211102T115254Z | alephalp |
| 021 | Julia 0.6 | 180630T171409Z | Sundar R |
| 003 | Jelly | 210829T162411Z | Unrelate |
| 074 | Zsh | 210828T231845Z | roblogic |
| 021 | Raku | 210829T014003Z | theangry |
| 039 | Factor + arrays.shaped | 210827T101457Z | chunes |
| 002 | 05AB1E | 210827T090026Z | Kevin Cr |
| 004 | MathGolf | 181120T130812Z | maxb |
| 014 | Japt | 190221T212554Z | Kamil Dr |
| 005 | 05AB1E legacy | 170228T170331Z | Riley |
| 012 | Pip p | 190221T084349Z | DLosc |
| 004 | Jelly | 180605T202446Z | dylnan |
| 051 | Haskell | 180630T212548Z | ბიმო |
| 085 | Lua | 180624T083929Z | IDid |
| 053 | C GCC | 180624T053023Z | Jakob |
| 034 | Perl 5 | 180622T201419Z | Dom Hast |
| 014 | V | 180605T194138Z | JoshM |
| 059 | SNOBOL4 CSNOBOL4 | 180605T200235Z | Giuseppe |
| 042 | 12basic | 180605T183401Z | 12Me21 |
| 034 | WendyScript | 170821T194402Z | Felix Gu |
| 079 | Common Lisp | 170316T234700Z | ceilingc |
| 056 | Hoon | 170317T005956Z | RenderSe |
| 082 | Lithp | 170308T235538Z | Andrakis |
| 007 | I | 170306T201659Z | Adá |
| 117 | Bash + GNU utilities | 170304T033415Z | Mitchell |
| 089 | Python 3 | 170303T075447Z | AvahW |
| 027 | Ruby | 170302T084427Z | G B |
| 026 | Ruby | 170301T072555Z | adrianmp |
| 049 | Clojure | 170301T233044Z | MattPutn |
| 141 | Batch | 170301T200910Z | Neil |
| 038 | JavaScript ES6 | 170301T134127Z | Neil |
| 045 | Rebol | 170301T110414Z | draegtun |
| 095 | Java | 170301T092206Z | anacron |
| 036 | Clojure | 170301T094251Z | cliffroo |
| 062 | PHP | 170228T181401Z | Ismael M |
| 063 | Clojure | 170301T065122Z | clismiqu |
| 052 | Haskell | 170301T062031Z | Ørj |
| 020 | Mathematica | 170228T173817Z | JungHwan |
| 025 | Perl 6 | 170228T215348Z | smls |
| 026 | R | 170228T214041Z | Flounder |
| 005 | Jelly | 170228T185319Z | Jonathan |
| 038 | Python 3 | 170228T171532Z | ovs |
| 062 | Haskell | 170228T183750Z | nimi |
| 032 | Python | 170228T175916Z | xnor |
| 036 | Python 2 | 170228T171409Z | Trelzevi |
| 061 | Perl 6 | 170228T174136Z | Håv |
| 004 | APL Dyalog APL | 170228T173109Z | Dennis |
| 020 | Octave | 170228T170500Z | rahnema1 |
| 012 | CJam | 170228T172304Z | Business |
| 005 | Jelly | 170228T171056Z | lynn |
| 040 | JavaScript ES6 | 170228T170210Z | Arnauld |
| 004 | J | 170228T170231Z | miles |
Japt, 8 bytes
N´?UÆß:U
N´?UÆß:U :Implicit input of integer U
N :Array of all inputs (initially [U])
´ :Postfix decrement, coercing to an integer
? :If truthy (not 0)
UÆ : Map the range [0,U)
ß : Recursive call
:U :Else return U
Janet, 49 bytes
|(do(var a $)(repeat $(set a(seq[:repeat $]a)))a)
Nim, 100 bytes
include xmltree
macro f(n):auto=(var
N=n.intval
a=n;for i in 1..N:a=nnkBracket.newTree a.repeat N
a)
Ungolfed:
include xmltree
macro f(node): auto =
var
N = node.intval
a = node
for i in 1..N:
a = newTree(nnkBracket, repeat(a, N)
a
xmltreeinternally importsmacrosandsequtilslibraries. Because they're not exported - we can access them only if we include the library.sequtils.repeatworks similar to Python'ssomething * n- UFCS allows us to rewrite
a(b,c)asb.a cto save 1 byte - In Nim - the last expression in parenthesis is a value of that expression e.g.
(foo();a) == a - The last expression in procedure/macro is implicitly returned e.g.
proc b():int=0is same asproc b():int=return 0
If the task would allow tuples, we could shave off another 12 bytes:
Nim, 88 bytes
include xmltree
macro f(n):auto=(var
N=n.intval
a=n;for i in 1..N:a=newPar a.repeat N
a)
This will generate:
(1)
((2,2),(2,2))
and so on ...
Thunno 2, 3 bytes
{Wọ
Explanation
{Wọ # Implicit input
{ # Repeat input number of times:
W # Wrap top of stack into a list
ọ # Repeat input number of times
# Implicit output
Arturo, 20 bytes
$=>[@.of:@.of:<=<=&]
Huh?
In Arturo, you can initialize a block of values like this:
array.of: 5 2 ; [2 2 2 2 2]
You can also give it a shape:
array.of: [5 3] 2 ; [[2 2 2] [2 2 2] [2 2 2] [2 2 2] [2 2 2]]
@ is syntax sugar for array.
$=> is syntax sugar for function [n].
<=<=& Means push the input to the stack and duplicate it twice.
So putting it all together, $=>[@.of:@.of:<=<=&] is the same as:
function [n][
array.of: array.of: n n n
]
Or perhaps more clearly:
function [n][
shape: array.of: n n
return array.of: shape n
]
BQN, 4 bytes
⥊˜⥊⊢
Anonymous tacit function; takes an integer and returns an N-dimensional array. Try it at BQN online!
Explanation
Exactly the same as Dennis's APL answer, though independently derived.
The Reshape builtin ⥊ takes a shape (list of integer dimensions) on the left and an array of values on the right. It creates an array of the given shape, filled with values taken from the original array. If either argument is a bare integer, it is promoted to a list containing that integer.
With example argument 3:
⥊˜ reshapes the argument with itself as the shape. The result is a 3-element 1-dimensional array of 3's: ⟨ 3 3 3 ⟩.
⊢ returns the argument unchanged: 3.
So ⥊˜ ⥊ ⊢ is equivalent to ⟨ 3 3 3 ⟩ ⥊ 3: reshape 3 into a 3 by 3 by 3 array.
Go, 150 bytes
func f(n int)[]any{return g(n,n)}
func g(n,d int)(L[]any){if d<1{return}
for i:=0;i<n;i++{var e any
if d<2{e=n}else{e=g(n,d-1)}
L=append(L,e)}
return}
Call with f(n). Returns an []any, that can be casted to a f(n).([]int),f(n).([][]int),f(n).([][][]int),f(n).([][][][]int), etc.
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
l$1 % Create a matrix of ones that is this size
* % Multiply this matrix of ones by N
% Implicitly display the result
tinylisp, 76 bytes
Since tinylisp was our most recent LYAL, I figured I had to at least post one answer in the lang. Embarrassingly, this answer (in a golfing dialect of lisp) is just as long as the Common Lisp solution
(load library
(d _(q((N D $)(i D(_ N(s D 1)(repeat-val $ N))$
(q((N)(_ N N N
This defines a helper function _ that takes three arguments, the number of times to repeat each layer N, the current depth of the iteration D (counting down, so deepest depth is zero), and an accumulator $. Depending on depth, this function either returns the accumulator (at depth zero), or uses the library builtin repeat-val to repeat the current accumulator N times, and passes that on to the next depth of the recursion. Then the actual function, A, is defined, which takes a single argument N in, and calls _ with that as all three arguments.
Non-library solution, 86 bytes
This was my first attempt to do this, without using the builtin library (which has rather ungolfy names), but it unfortunately turned out rather longer.
(d _(q((X N D I $)(i D(i I(_ X N D(s I 1)(c X $))(_ $ N(s D 1)N()))X
(q((N)(_ N N N N(
This works much the same as the library solution, but manually defines the behavior of repeat-val, which requires taking two extra arguments in the helper function, which takes the value X the current depth is repeating, the number of repetitions on each depth N, the current depth D (counting down to zero), the number of repetitions remaining in this depth I, and an accumulator $. The proper function A works much the same, taking N calling _ with the proper arguments. (in this case N for the first four, and nil () for the accumulator)
Julia 0.6, 23 21 bytes
n->n>(n>n)...
> =fill
(Thanks to @MarcMush for -2 bytes.)
In Julia, binary operators are parsed as function calls, so a>b is >(a, b), which here is fill(a, b). So the above is really saying:
n->fill(n,fill(n,n)...)
The first argument to fill is the value to fill the new array with. The following arguments to that are the dimensions of the new array. Here we create those dimensions themselves using another fill call: we create an array of n ns, then splat that with ... so that the first fill call gets n number of dimension arguments, each with value n - so it creates an n-dimensional array where each dimension length is n, and filled with the value n.
Jelly, 3 bytes
ḷⱮ¡
Like Lynn's solution which heavily inspired this, a full program only.
¡ Repeat [input] times, starting with the input on the left and right:
Ɱ Produce an array containing, for every element of the right argument,
ḷ the left argument.
Although dyadic ¡, rather than reusing its right argument, uses the previous left argument for each successive iteration, in this case either behavior would do the same thing--since each intermediate result has the same length as the (implicitly rangified) initial input.
Zsh, 74 bytes
f(){for i ({1..$1})z+=($2);<<<($z)}
for j ({1..$1})k=`f $1 ${k:-$1}`;<<<$k
Zsh doesn't have multi dimensional arrays but it can do arrays of strings. Here we build up string $k by plugging it into f, then taking that result as the new $k, iterating N times ($1).
Factor + arrays.shaped, 39 bytes
[ 3 dupn <array> swap repeated-shaped ]
repeated-shaped Takes a sequence of dimensions (i.e. a shape) and an element and creates an array from them. The rest of the code turns 4 into { 4 4 4 4 } 4, for example.
05AB1E, 2 bytes
Fи
Try it online or verify the first \$[1,5]\$ test cases†.
†: Uses a Bash script to execute the 05AB1E code, so it'll use the (implicit) input within the test suite. If the number would be on the stack instead of as input, it won't work for \$n=2\$ (no idea why..): see this traditional test suite, where every output is correct except for \$n=2\$.
Explanation:
F # Loop the (implicit) input amount of times:
и # Repeat the (implicit) input the current values amount of times (as list)
# (after which the resulting nested list is output implicitly)
MathGolf, 5 4 bytes
_{a*
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]]])
Japt, 14 bytes
_òU}g[UpU ÆUÃ]
Output is wrapped in an extra singleton array.
Explanation:
Æ Ã #Create an array
U #Where every element is U
UpU #And the length is U^U
_ }g[ ] #Repeat this function U times:
òU # Cut into slices of length U
05AB1E (legacy), 6 5 bytes
-1 thanks to Kevin Cruijssen
F¹.D)
F # For 0 .. input
¹.D) # Push <input> copies of the result of the last step as an array
Pip -p, 12 bytes
YaLaY[y]RLay
Explanation
YaLaY[y]RLay
Y Yank into the y variable
a the first command-line argument, a
La Fixed-iterations loop, do the following a times:
[y] y wrapped in a list
RLa repeated a times (results in a list containing a copies of y)
Y Yank that list back into y
y After the loop, print y
Jelly, 4 bytes
R»µ¡
R»µ¡
R Range. 2 -> [1, 2]
» Max between left arg and right arg. Vectorizes. -> [2, 2]
µ Separates into a new chain.
¡ Repeat 2 times. After another iteration this yields [[2, 2], [2, 2]].
Same thing but with a single monad and no need for the chain separator:
»€`¡
Haskell, 51 bytes
Other than the existing Haskell solutions this constructs a usable data type not just a string representation thereof (and is shorter):
data L=N[L]|E Int
f n=iterate(N.(<$[1..n]))(E n)!!n
Explanation / Ungolfed
The reason why this is an interesting challenge in Haskell is that a solution to this challenge needs to return different deeply nested lists and Haskell (without importing external modules) does not support this. One workaround which turned out to be the golfiest, is to define our own data type:
data NestedList = Nest [NestedList] | Entry Int
Now we can just define a function f :: Int -> NestedList which is able to represent all the required data types:
pow n = iterate (Nest . replicate n) (Entry n) !! n
Lua, 85 bytes
function f(n,d,x)d=d or 2 x={}for i=1,n do x[i]=d>n and n or f(n,d+1)end return x end
(The TIO link contains a bit of extra code to print the table as Lua has no built-in way of printing a table's contents)
Explanation
function f(n, d, x)
d = d or 2
x = {}
for i = 1, n do
x[i] = d > n and n or f(n, d + 1)
end
return x
end
As you can probably see, f is a recursive function which takes the number N as n, and two other arguments, d and x. d is the depth, and is not used in the initial call, in which case it defaults to 2. x is not actually used as a parameter, but is there because the function requires a temporary local variable, and it is shorter to declare it as a parameter than to use the local keyword.
C (GCC), 53 bytes
Since C "has" multidimensional arrays (i.e. chunks of memory plus automatic offset calculation), this is almost a reasonable solution. Still, it's mostly a joke and borders on non-competing.
f(n){int s=pow(n,n),*p=malloc(s*8);wmemset(p,n,s);}
In the TIO I go through the ceremony of casting the result (which is an int) to the appropriate array type despite the fact that my array print function (appropriately) takes a generic pointer.
While I can't demonstrate that the structure of the array is determined by f (it's not), I do include a flat printout of the elements of the output for an input of 3 using the multidimensional array element access syntax, to show that the layout of the returned memory matches that of the corresponding array type.
Byte count
- function: 51 bytes
- compiler flags (
-lm): 2 bytes
Unportability
- The result pointer is returned through an
int, so this may not work for all heap addresses. - By using
wmemsetI require that the sizes ofintandwchar_tare equal, and the scaling in the argument tomallocrequires the sizes to be at most 8 bytes. - Implicit declaration madness. I don't even know why passing
ints to an unprototypedpowthat actually takesdoubles seems to work correctly. - The function "returns" by (I think) just leaving the return value of
wmemsetin the proper register. This behavior may be particular to the x86 architecture.
V, 14 bytes
é,"aPÀñDÀpys0]
input
é, # write comma
"aP # paste register A (input)
Àñ # loop À (number in register A) times
D # cut to end of line
Àp # paste À times
ysB] # surround everything before comma in square brackets
SNOBOL4 (CSNOBOL4), 59 bytes
DEFINE('F(N)')
F F =ARRAY(DUPL(N ',',N - 1) N,N) :(RETURN)
Defines a function that returns an ARRAY with the appropriate dimensions and filled with value N.
12-basic, 42 bytes
A=[N=INPUT()]*N
FOR I=2TO N
A=[A]*N
NEXT?A
WendyScript, 34 bytes
#:(x){<<j=[x]*x#i:1->x j=[j]*x/>j}
#:(x){<<j=[x]*x#i:1->x j=[j]*x/>j}(2) // [[2, 2], [2, 2]]
Common Lisp, 128 102 95 79 bytes
(defun f(x &optional y)(if(if y(< y 2))x(fill(make-list x)(f x(if y(1- y)x)))))
Hoon, 56 bytes
|=
n/@
=+
i=1
|-
?:
=(n i)
(reap n n)
(reap n $(i +(i)))
Create a new function that takes an atom n. Make a variable i starting at 1, and start a loop: if i==n return a list with n elements of n, else return a list with n elements of the value returned by recursing to the start of the loop with i = i + 1.
I'm a little bit upset that there's not really anything you can do to golf this in Hoon :/ The standard trick of using unnamed variables doesn't apply because it's longer to use lark syntax for once, due to the loop shifting the location of i.
> =f |=
n/@
=+
i=1
|-
?:
=(n i)
(reap n n)
(reap n $(i +(i)))
> (f 1)
~[1]
> (f 2)
~[~[2 2] ~[2 2]]
> (f 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]]]
> (f 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]]
]
]
Lithp, 82 bytes
(def f #N::((def i #N,I,K::((if(> I 0)((i N(- I 1)(list-fill N K)))K)))(i N N N)))
I tried implementing this as a list comprehension, but couldn't comprehend how to do it correctly. Instead I went for an implementation based on the JavaScript answer. Unfortunately, my language is fairly long-winded, and this is complicated by the fact that I lack shorthand and other useful features.
A more readable version is available at the Try it Online link.
I, 7 bytes
I got this from my colleague, the creator of I.
#Bbhph~
#Bb the copy # function Bound to binding
hp hook the argument to (the right of) the power function (repeat)
h~ hook the argument to the left ~ (of the entire resulting function)
Bash + GNU utilities, 117 bytes
n=$[$1**$1]
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] \ []
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:
- If k ends with at least one digit 0, print a '[' for each digit 0 at the end of k.
- Print n.
- 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]]]
Python 3, 89 Bytes
def f(x):
r=[x for _ in range(x)]
for _ in range(x-1):r=[r for _ in range(x)]
print(r)
Ruby, 27 bytes
->a{(z=a).times{z=[z]*a};z}
Only 1 byte more but using a different approach instead of the 'eval' trick from xnor's wonderful Python answer.
Ruby, 28 26 bytes
Thanks to Cyoce for saving 2 bytes!
->n{eval'['*n+'n'+']*n'*n}
Stolen shamelessly from xnor's excellent answer.
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.
Batch, 141 bytes
@set t=.
@for /l %%i in (2,1,%1)do @call set t=%%t%%,.
@set s=%1
@for /l %%i in (1,1,%1)do @call call set s=[%%%%t:.=%%s%%%%%%]
@echo %s%
Batch doesn't actually have arrays so this just prints the string representation of an array. Explanation: The first two lines build up a repeated pattern of N .s separated by N-1 ,s in the variable t. The fourth line then uses this as a substitution pattern N times to create the N-dimensional array. The double call is necessary because of how the for and set statements work. First, the for command substitutes variables. As it happens, all of my % signs are doubled, so this does nothing except to unquote them all, resulting in call call set s=[%%t:.=%s%%%]. It then repeats the resulting statement N times. Each time, the call command substitutes variables. At this point, the s variable only has a single set of %s, so it gets substituted, resulting in (e.g.) call set s=[%t:.=[2,2]%]. The inner call then substitutes the t variable, resulting in (e.g.) set s=[[2,2],[2,2]], performing the desired assignment. The final value of s is then printed.
JavaScript (ES6), 38 bytes
f=(n,m=n)=>m?Array(n).fill(f(n,m-1)):n
The memory-hungry version of this is 45 bytes:
f=(n,m=n)=>m?[...Array(n)].map(_=>f(n,m-1)):n
Rebol, 45 bytes
func[n][array/initial append/dup copy[]n n n]
Java 97 96 95 bytes
Object c(int n,int i){Object[]a=new Object[n];for(int j=0;j<n;)a[j++]=i<2?n:c(n,i-1);return a;}
Ungolfed:
public class N_Dim {
public static Object create(int n) {
return create(n, n);
}
public static Object create(int n, int i) {
Object[] array = new Object[n];
for(int j=0;j<n;j++) {
array[j] = i<2?n:create(n, i - 1);
}
return array;
}
public static void main(String[] args) {
System.out.println(Arrays.deepToString((Object[]) create(3)));
}
}
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.
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!
Clojure, 63 bytes
#(loop[a(repeat % %)d 1](if(= d %)a(recur(repeat % a)(inc d))))
This is a lambda function, usage is like so:
(#(...) {input_no})
...where {input_no} is replaced with the number.
Output for 3 is like this:
(((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)))
This uses Clojure's definition of lists, which are denoted as ().
Ungolfed code and explanation:
; Defines the function
(defn layered [n]
; Begins a loop with a variable depth of 1,
; and a list of n elements which are all n
(loop [depth 1
array (repeat n n)]
; If "depth" is equal to n, return the list
(if (= depth n) array
; Else, continue on with the loop, with
; an incremented "depth"...
(recur (inc depth)
; ...and a list which contains the
; list repeated n times
(repeat n array)))))
Haskell, 52 bytes
f n=iterate(filter(>'"').show.(<$[1..n]))(show n)!!n
Inspired by @nimi's answer, but using more predefined functions.
- Uses
iterateand!!instead of a recursive help function. - Instead of constructing list delimiters "by hand", uses
filter(>'"').showto format a list of strings, then stripping away the extra"characters.
Mathematica, 22 20 bytes
(t=Table)@@t[#,#+1]&
(* or *)
Table@@Table[#,#+1]&
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.
R, 26
This is the obvious answer but perhaps there is something cleverer?
n=scan();array(n,rep(n,n))
Jelly, 5 bytes
⁾Wẋẋv
How?
⁾Wẋẋv - Main link: n e.g. 3
⁾Wẋ - character pair literal ['W','ẋ'] "Wẋ"
ẋ - repeat list n times "WẋWẋWẋ"
v - evaluate as Jelly code with input n eval("WẋWẋWẋ", 3)
- ...
WẋWẋ... - toEval: n e.g. 3
W - wrap [3]
ẋ - repeat list n times [3,3,3]
Wẋ - wrap and repeat [[3,3,3],[3,3,3],[3,3,3]]
... - n times total [[[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]]]
Python 3, 57 53 50 38 bytes
f=lambda n,c=0:n-c and[f(n,c+1)*n]or 1
-4 bytes thanks to @CalculatorFeline
34 bytes:
f=lambda c,n:c and[f(c-1,n)*n]or 1
Needs to be called as f(4,4)
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
Python, 32 bytes
lambda n:eval('['*n+'n'+']*n'*n)
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.
Perl 6, 61 bytes
my $x=prompt(0);my @a=$x xx$x;"@a=[@a] xx $x;".EVAL xx$x-1;
Big rippof from the Python 2 answer, but converted :P
Octave, 35 33 25 23 20 bytes
@(N)ones(N+!(1:N))*N
@(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
Previous answer:
@(N)repmat(N,num2cell(!(1:N)+N){:})
CJam, 12 bytes
ri:X{aX*}X*p
Explanation
ri:X Read an integer from input, store it in X (leaves it on the stack)
{ }X* Execute this block X times:
a Wrap the top of stack in an array
X* Repeat the array X times
p Print nicely
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)))
J, 4 bytes
$~#~
Explanation
$~#~ Input: integer n
#~ Create n copies of n
$~ Shape n into an array with dimensions n copies of n