PIXELBANKv9.1.0
Menu

Random Pick with Weight

Given an array w of positive integers where w[i] describes the weight of index i, implement pickIndex() which randomly picks an index proportional to its weight.

For testing: given weights and a large number of picks, output the percentage each index was picked (rounded to nearest integer). The output should be close to the weight distribution.

Instead of random testing, output the cumulative weights used for selection as space-separated integers.

Example:

Input:
1,3
Output:
1 4
Reasoning:
  • The input array w is given as [1, 3], representing the weights of the two indices.
  • To calculate the cumulative weights, we start with the first weight 1 and add the second weight 3 to get the cumulative weight at index 1: 1+3=41 + 3 = 4.
  • The cumulative weights are then [1, 4], where 1 is the cumulative weight up to index 0 and 4 is the cumulative weight up to index 1.
  • The final output is the cumulative weights as space-separated integers: 1 4.

Constraints:

  • 1 <= len(w) <= 10^4
  • 1 <= w[i] <= 10^5
solution.py

Test Results

0/0
Run code to see test results.