Skip to content
Advertisement

Algorithm to position diners at a table with social distancing guidelines

Trying to solve this task:

A cafeteria table consists of a row of N seats, numbered from 1 to N from left to right. Social distancing guidelines require that every diner be seated such that K seats to their left and K seats to their right (or all the remaining seats to that side if there are fewer than K) remain empty. There are currently M diners seated at the table, the ith of whom is in seat S(i).

No two diners are sitting in the same seat, and the social distancing guidelines are satisfied. Determine the maximum number of additional diners who can potentially sit at the table without social distancing guidelines being violated for any new or existing diners, assuming that the existing diners cannot move and that the additional diners will cooperate to maximize how many of them can sit down. Please take care to write a solution which runs within the time limit.

JavaScript

Sample Explanation

In the first case, the cafeteria table has N=10 seats, with two diners currently at seats 2 and 6 respectively. The table initially looks as follows, with brackets covering the K=1 seat to the left and right of each existing diner that may not be taken.

JavaScript

Three additional diners may sit at seats 4, 8, and 10 without violating the social distancing guidelines. In the second case, only 1 additional diner is able to join the table, by sitting in any of the first 3 seats.

My solution works for both test cases (1 and 2):

JavaScript

Yet for a test case:

JavaScript

It returns the wrong answer 2 instead of 3, not taking into account free position 1. What would be the correct algorithm?

Advertisement

Answer

The issue is within the if condition that checks the first position:

JavaScript

The problem is that you have to treat it differently when there is a remainder in the division. You need to modify the new_pos_cnt calculation so that it doesn’t subtract a position if there is a remainder:

JavaScript

This produces the same results for your first two test cases and the correct result for the third case as well.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement