JavaScript(ES6),172个字节
@JonathanAllan建议的速度较慢但版本较短的建议(在原始答案中还节省了4个字节):
f=(n,A,S=(n,c)=>n>=0?c(n)||S(n-1,c):0)=>S(A,w=>(F=(l,n)=>n?S(w-n,x=>S(A/w-n,y=>l.some(([X,Y,W])=>X<x+n&X+W>x&Y<y+n&Y+W>y)?0:F([...l,[x,y,n]],n-1))):A%w<1)([],n))?A:f(n,-~A)
在线尝试!
原来的答案, 209个183 178 174字节
返回序列的第N个项,以1为索引。
f=(n,A,S=(n,c)=>n>=0?c(n)||S(n-1,c):0)=>S(A,w=>A%w?0:(F=(l,n)=>n?S(w-n,x=>S(A/w-n,y=>l.some(([X,Y,W])=>X<x+n&X+W>x&Y<y+n&Y+W>y)?0:F([...l,[x,y,n]],n-1))):1)([],n))?A:f(n,-~A)
在线尝试!
已评论
辅助功能
我们首先定义一个辅助函数S,该函数调用n到0(包括两者)的回调函数c,并在调用返回真实值时立即停止。n0
S = (n, c) => // n = integer, c = callback function
n >= 0 ? // if n is greater than or equal to 0:
c(n) || // invoke c with n; stop if it's truthy
S(n - 1, c) // or go on with n - 1 if it's falsy
: // else:
0 // stop recursion and return 0
主功能
我们从A=1开始。
(w ,h )w × h = A1 × 1n × n
我们通过其位置跟踪正方形列表(X,Y)w ^l [ ]
一种A + 1。
f = ( n, // n = input
A ) => // A = candidate area (initially undefined)
S(A, w => // for w = A to w = 0:
A % w ? // if w is not a divisor of A:
0 // do nothing
: ( // else:
F = (l, n) => // F = recursive function taking a list l[] and a size n
n ? // if n is not equal to 0:
S(w - n, x => // for x = w - n to x = 0
S(A / w - n, y => // for y = A / w - n to y = 0:
l.some( // for each square in l[]
([X, Y, W]) => // located at (X, Y) and of width W:
X < x + n & // test whether this square is overlapping
X + W > x & // with the new square of width n that we're
Y < y + n & // trying to insert at (x, y)
Y + W > y //
) ? // if some existing square does overlap:
0 // abort
: // else:
F([ ...l, // recursive call to F:
[x, y, n] // append the new square to l[]
], //
n - 1 // and decrement n
) // end of recursive call
) // end of iteration over y
) // end of iteration over x
: // else (n = 0):
1 // success: stop recursion and return 1
)([], n) // initial call to F with an empty list of squares
) ? // end of iteration over w; if it was successful:
A // return A
: // else:
f(n, -~A) // try again with A + 1
h
测试并将其移动a%w<1
到递归TIO的尾部来节省6 * 。当然,它要慢得多。(*至少-我不是JavaScript专家!)