Distributed Cluster Count
OpenAIPhone screenMedium
A cluster is a tree of machines. Each machine knows only its own id, its parent (the root has none) and its children, and it can talk only to those machines, by sending text messages. A machine cannot look at the rest of the tree, and sending to a machine that is not its parent or child raises an error. You write what a machine does when a message arrives.
A Node is one machine. It is given send(node_id, message), which queues a text message for its parent or one of its children, and output(text), which prints one line. When a queued message is delivered, the cluster calls the receiving machine's receive_message(from_node_id, message). You write Node.receive_message, and you choose what the messages say.
Cluster is provided. Cluster(children, root) builds a machine for every key of children, a map from each machine id to the list of its children's ids (a leaf's list is empty). start(command) delivers command to the root with no sender (from_node_id is null), then delivers queued messages in the order they were sent until none are left, and returns the lines printed during that run. A cluster can be started any number of times; each start is a separate run on the same machines.
Part 1: Count the machines
When the root receives the command "count", the cluster must print the number of machines in the whole tree. Only the root prints, and it prints exactly one line: the count as a string, such as "6".
Implement Node.receive_message so that start("count") returns that one line. A cluster of a single machine prints "1".
- Example 1
- init
[{"1":["2","3"],"2":["4","5"],"3":["6"],"4":[],"5":[],"6":[]},"1"]- operations
[["start",["count"]]]- Output
[["6"]]
Why: The tree has 6 machines: the root 1, its children 2 and 3, and their children 4, 5 and 6.
Constraints
1 <= len(children) <= 1000- Machine ids are non-empty strings of letters and digits
- Every machine id is a key of
children, and the structure is a tree rooted atroot