0

I want to randomly select a single item out of three lists, where each list represents a different probability of selection.

I have three lists (can be also 3 arrays): high, mid, and low "priority".

I want to choose one item from those three lists by priority chance

E.g. From High 70% chance from mid 20% and from low rest 10%

However, some of the list could be empty (not all of them)

At least there is one item inside one of the lists

I'm looking for algorithm (any language, but prefer C# Java Python) that does it

I tried the following code (Python) but it doesn't do the job due the empty condition sometimes no item is selected even there is one.

        x =  random.randint(1,100)
        if x  < 71 and highChance != []:     
             return random.choice(highChance)
        elif x >=71 and x < 91 and midChance != []:
            return random.choice(midChance)
        elif lowChance != []:
            return random.choice(lowChance)
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
yzahavi
  • 45
  • 2
  • 2
    If `Mid` array is empty, `High` is not and `Low` is not, what should be chances to take an item from `High` array? – AlexD Aug 09 '14 at 23:13
  • doesn't matter - lets say all unused chance goes to high and if high empty mid take unused chance (means low will be always 10% if exist) – yzahavi Aug 09 '14 at 23:21
  • 1
    From the description so far, it sounds like the answer could be a pragmatic `elif return anyElementFromAnyNonEmptyArray()`, because the percentages will be meaningless anyhow. When, for example, the "High" array is empty, how should the percentages be distributed among "Mid" and "Low"? – Marco13 Aug 10 '14 at 00:06

1 Answers1

0
int[] high = new int[] { 0, 1, 2, 3 };
int[] mid = new int[] { 0, 1 };
int[] low = new int[] { };

int[][] arr = new int[3][];
arr[0] = high.Length != 0? high: mid.Length != 0? mid: low;
arr[1] = mid.Length != 0 ? mid : arr[0];
arr[2] = low.Length != 0 ? low : arr[0];

Random rnd = new Random(0);
int n = rnd.Next(10);
int k = (n < 7) ? 0 : (n < 9) ? 1 : 2;
int result = arr[k][rnd.Next(arr[k].Length)];
AlexD
  • 32,156
  • 3
  • 71
  • 65