How should you arrange your chairs?
Jelly, 16 15 14 bytes
÷RĊ,Rµạ/+PỤḢịZ
Try it online! or verify all test cases.
How it works
÷RĊ,Rµạ/+PỤḢịZ Main link. Argument: n
R Range; yield [1, ..., n].
÷ Divide n by each k in [1, ..., n].
Ċ Ceil; round the quotients up to the nearest integer.
R Range; yield [1, ..., n].
, Pair; yield A := [[ ⌈n ÷ 1⌉, ..., ⌈n ÷ n⌉ ], [ 1, ..., n ]].
µ Begin a new, monadic chain. Argument: A
ạ/ Reduce A by absolute difference.
This yields [ |⌈n ÷ 1⌉ - 1|, ..., |⌈n ÷ n⌉ - n| ].
P Product; reduce A by multiplication.
This yields [ ⌈n ÷ 1⌉ × 1, ..., ⌈n ÷ n⌉ × n].
+ Add the results to left and right, element by element. This yields
[ |⌈n ÷ 1⌉ - 1| + ⌈n ÷ 1⌉ × 1, ..., |⌈n ÷ n⌉ - n| + ⌈n ÷ n⌉ × n ].
Ụ Grade up; sort the indices of the list of sums by their values.
Ḣ Head; extract the first value, which corresponds to the smallest
sum. Grading up is stable, so this selects the first index of all
with the smallest sum in case of a tie. In this event, the first
index will have the highest absolute difference of all indices
with the smallest sum, meaning that it has the lowest product and,
therefore, the lowest number of empty chairs.
Z Zip; transpose A's rows and columns.
This yields [[ ⌈n ÷ 1⌉, 1 ], ..., [ ⌈n ÷ n⌉, n ]].
ị Retrieve the pair at that index.
Python 2, 68 bytes
lambda n:min((abs(~i-n/~i)+n/~i*~i,i+1,0-n/~i)for i in range(n))[1:]
Equivalent to the more “obvious”:
lambda n:min([(i+1,0-n/~i)for i in range(n)],key=lambda(p,q):abs(p-q)+p*q)
Haskell, 65 bytes
f x=snd$minimum[((a*b+a-b,a*b),(b,a))|a<-[1..x],b<-[1..a],a*b>=x]
Usage example: map f [1..5]
-> [(1,1),(1,2),(2,2),(2,2),(2,3)]
.
Goes through an outer loop a
from 1
to x
(x -> number of students) and an inner loop b
from 1
to a
. Keeps all (b,a)
where a*b>=x
and builds pairs of ((arrangement points,seats left), (b,a))
which follow the lexicographical order we need to find the minimum. Note: a
is always greater than b
, so we don't need abs
for squareyness. No need to subtract x
from the "seats left" score, because only the relative order matters. Finally we remove the score pair with snd
.