Real DHCP servers lend addresses for a limited time. Expired leases return to the pool, and a returning client is given its old address back if it is still free.
What to build
A program that runs a DHCP server with leases over a list of requests.
Requirements
- A lease granted or renewed at time t is active until time t + L: it is expired when the current time is at least t + L.
- A client with an active lease renews it and gets the same address.
- Any other client gets its previous address if that address is not actively leased, otherwise the lowest address in the pool that is not actively leased, otherwise
none. - Print
time client addressfor every request.
Input
Line 1: the first three numbers of the address (like 192.168.1), the first and last host number of the pool, and the lease time L. Line 2: the number of requests n. Then n lines time client, in non-decreasing time order.
Output
n lines like 0 phone 192.168.1.10.
Constraints
1 ≤ n ≤ 100; the pool has 1 to 20 addresses.
Example
Input:
192.168.1 10 11 60
4
0 a
10 b
20 c
70 c
Output:
0 a 192.168.1.10
10 b 192.168.1.11
20 c none
70 c 192.168.1.10
Why it works
A lease table with expiry times lets the server decide, at each request, which addresses are free. Preferring the client's last address is what makes a returning device keep its address when nothing else has taken it.
Examples
192.168.1 10 11 60 4 0 a 10 b 20 c 70 c
0 a 192.168.1.10 10 b 192.168.1.11 20 c none 70 c 192.168.1.10
10.0.0 1 2 100 3 0 a 50 a 200 b
0 a 10.0.0.1 50 a 10.0.0.1 200 b 10.0.0.1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Store for each address its client and expiry time. A lease is active at time t when expiry is greater than t.
Hint 2
A client with an active lease renews it (expiry = t + lease) and keeps its address. Otherwise prefer the client's last address if nobody holds it, else the lowest free address.
Hint 3
Remember every client's last address in a second dict, even after the lease expires.
Solution
Show one correct solution (try it yourself first)
prefix, low, high, lease = input().split()
low, high, lease = int(low), int(high), int(lease)
n = int(input())
holder = {}
last = {}
for _ in range(n):
t, client = input().split()
t = int(t)
active = {}
for host in range(low, high + 1):
if host in holder and holder[host][1] > t:
active[host] = holder[host][0]
chosen = None
for host in active:
if active[host] == client:
chosen = host
if chosen is None and client in last and last[client] not in active:
chosen = last[client]
if chosen is None:
for host in range(low, high + 1):
if host not in active:
chosen = host
break
if chosen is None:
print(t, client, "none")
else:
holder[chosen] = (client, t + lease)
last[client] = chosen
print(t, client, prefix + "." + str(chosen))
▶ Open this solution in the compiler, then press Visualize to watch it run step by step