I have to write an algorithm for Assigning Contiguous seats in a seat map.For example: allocating seats in a stadium. The seat map can be viewed as a 2d array of N rows and M columns. The system must assign contiguous seats for bookings that are made together. Since no seat map is presented to the user, the system should automatically assign the available seats corresponding to each purchase. In addition to this, it should do this in such a fashion such that the holes/gaps in the seats are minimized.
Share
Finding a perfect solution is NP-hard. Look at the equivalent language problem:
L={((x1,x2,...,xk),n,m)}where xi are the number of co-booked tickets, and n,m are the stadium sizes.We will show Partition <=(P) L, and thus this problem is NP-Hard, and there is no known polynomial solution for it.
Proof
let
S=(x1,x2,..,xk)be the input for a partition problem, and letsum=x1+...+xkLook at the following reduction:
Correctness:
If S has a partition, let it be
S1=(x_i1,x_i2,...,x_it), then by definition of partition,x_i1+...+x_it=sum/2, and thus we can insertx_i1,..,x_itin the first row, and the rest in the second row, and so((x1,...,xk),sum/2,2)is in LIf
((x1,...,xk),sum/2,2)is in L, then by definition there are t bookings such thatx_i1,x_i2,...,x_itform a perfect first line, and thusx_i1+x_i2+...+x_it=sum/2, and thus it is a valid partition and S is in Partition problemConclusion:
Since L is NP-Hard, and the problem you seek is the optimization problem for this language, there is no known polynomial solution for it. For an exact solution you can use backtracking [check all possibilities, and choose the best], but it will take a lot of time, or you can sattle for a heuristic solution, such as greedy, but it will not be optimized.
EDIT: Backtracking solution [pseudocode]:
Assuming
Solutionis an implemented class, and for an illegal solution [i.e. too many people in one row]numGaps() == infinity