Route packet to rule
Your task
A router matches packets against a table of rules. A rule reads address/length, where the address is four numbers from 0 to 255 joined by dots and length runs from 0 to 32. Read an address as a 32 bit number with the first of the four numbers highest. A rule covers a packet when the top length bits of the two addresses agree, and the bits below that are ignored, so 10.0.0.7/24 and 10.0.0.0/24 cover exactly the same packets. Each packet takes the covering rule with the largest length, and the earliest such rule when two lengths tie. Given the rules in table order and the packet addresses, return the chosen rule index for each packet, or -1 when nothing covers it. Aim for a cost per packet that does not grow with the size of the table.
Examples
selected_routes(rules: list[str], packets: list[str]) -> list[int]Example 1
Input
selected_routes(["0.0.0.0/0", "10.0.0.0/8", "10.1.0.0/16"], ["10.1.2.3", "10.2.0.1", "8.8.8.8"])Output
[2, 1, 0]Example 2
Input
selected_routes(["10.0.0.7/24"], ["10.0.0.0", "10.0.1.0"])Output
[0, -1]Example 3
Input
selected_routes(["192.168.1.0/24", "192.168.1.0/24"], ["192.168.1.9"])Output
[0]