You are building the request-routing layer of a load balancer. Given a list of backend server IP addresses, you need to pick one for each incoming request according to a specified probability.
Implement a load balancer that can distribute incoming requests to a set of backend servers based on given probabilities. Each server is represented by its IP address and an associated weight which indicates the probability of receiving a request. The sum of all weights should equal 1.
Input: IPs = ["192.168.1.1", "192.168.1.2", "192.168.1.3"], weights = [0.2, 0.5, 0.3]
Input: IPs = ["10.0.0.1", "10.0.0.2"], weights = [0.1, 0.9]
`python import random
class LoadBalancer: def init(self, IPs, weights): self.IPs = IPs self.weights = weights self.cumulative_weights = [] current_sum = 0 for weight in weights: current_sum += weight self.cumulative_weights.append(current_sum)
def get_random_IP(self):
rand_num = random.random()
for i, cum_weight in enumerate(self.cumulative_weights):
if rand_num < cum_weight:
return self.IPs[i]
return self.IPs[-1] # Fallback in case of floating-point arithmetic issues
IPs = ["192.168.1.1", "192.168.1.2", "192.168.1.3"] weights = [0.2, 0.5, 0.3] load_balancer = LoadBalancer(IPs, weights) print(load_balancer.get_random_IP()) `
This solution initializes a LoadBalancer with a list of IPs and their corresponding weights. It then uses a cumulative distribution function to select an IP based on the specified probabilities. The get_random_IP method simulates an incoming request and returns an IP address according to the weights.