Segments can arrive out of order. The receiver answers each one with the next byte it still needs, so a missing segment causes repeated ACKs. Three duplicates make the sender resend at once.
What to build
A program that prints the receiver's ACK for each arriving segment and reports fast retransmits.
Requirements
- The receiver expects the first byte to be
start. When a segment arrives, it is kept; then the receiver moves its expected number past every consecutive segment it holds. (A segment whose sequence number is below the expected number is an old copy: ignore it, but still answer.) - After each arrival print
ack A, where A is the expected number, followed bydup Kwhen it is the K-th repeat in a row of the same ACK number. - When K reaches 3, print
fast retransmit Aon the next line.
Input
Line 1: the starting sequence number and the number of segments n. Then n lines seq len, in the order the segments arrive.
Output
The lines described above.
Constraints
1 ≤ n ≤ 50. Segments never overlap partly: each is a whole segment of the stream.
Example
Input:
1 5
1 100
201 100
301 100
401 100
101 100
Output:
ack 101
ack 101 dup 1
ack 101 dup 2
ack 101 dup 3
fast retransmit 101
ack 501
Why it works
A missing segment keeps the expected number stuck, so every later arrival produces the same ACK. Three duplicates are strong evidence that one segment was lost while later ones got through, so TCP resends it without waiting for a timeout.
Examples
1 5 1 100 201 100 301 100 401 100 101 100
ack 101 ack 101 dup 1 ack 101 dup 2 ack 101 dup 3 fast retransmit 101 ack 501
1 2 1 100 101 100
ack 101 ack 201
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep expected (the next byte wanted) and a dict of segments that arrived early. After each arrival, advance expected while the next segment is in the dict.
Hint 2
The ACK is always expected. If it equals the previous ACK it is a duplicate: count them; a new value resets the count.
Hint 3
When the count reaches 3, print the fast retransmit line once for that ACK value.
Solution
Show one correct solution (try it yourself first)
start, n = map(int, input().split())
expected = start
early = {}
last = None
dups = 0
for _ in range(n):
seq, length = map(int, input().split())
if seq >= expected:
early[seq] = length
while expected in early:
expected += early.pop(expected)
if expected == last:
dups += 1
print("ack", expected, "dup", dups)
if dups == 3:
print("fast retransmit", expected)
else:
dups = 0
last = expected
print("ack", expected)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step