Skip to content

Instantly share code, notes, and snippets.

@rongpenl
Created November 9, 2023 06:05
Show Gist options
  • Save rongpenl/4130ad01805c885fb2741776d4a5fea2 to your computer and use it in GitHub Desktop.
Save rongpenl/4130ad01805c885fb2741776d4a5fea2 to your computer and use it in GitHub Desktop.
The function to calculate A(n,i) for the video https://www.youtube.com/watch?v=sjcle2vIueU
def A(n,i):
# calculate using a simulation approach.
i = i-1 # convert to 0-based index.
urinals = np.zeros(n)
urinals[i] = 1 # the ith is occupied.
while True:
# find the furtherest urinal that is away from any occupied urinal.
candidates = {} # key: the index of the urinal, value: the distance to the nearest occupied urinal.
for j in range(n):
if urinals[j] == 1:
continue
else:
left_distance = 0 if j != 0 else np.inf
right_distance = 0 if j != n-1 else np.inf
for k in range(j-1,-1,-1):
if urinals[k] == 1:
break
elif k == 0:
left_distance = np.inf
else:
left_distance += 1
for k in range(j+1,n):
if urinals[k] == 1:
break
elif k == n-1:
right_distance = np.inf
else:
right_distance += 1
candidates[j] = min(left_distance,right_distance)
# keep only non-zero distance urinals
candidates = {key:value for key,value in candidates.items() if value != 0}
if len(candidates) == 0:
break
else:
max_distance = max(candidates.values())
# randomize the choice if there are multiple urinals with the same distance.
max_keys = [key for key,value in candidates.items() if value == max_distance]
# print(max_keys)
idx = np.random.choice(max_keys)
urinals[idx] = 1
return urinals.sum()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment