Can we get randomness in linked lists?. I’m implementing space shooter game in which enemies should shoot bullets randomly. I’m storing enemies in linked lists, I want to select some enemies randomly and shoot from them. How can I do this with linked lists?
Can we get randomness in linked lists?. I’m implementing space shooter game in which
Share
If you know precisely how many items are in your list, and how many you want to have shooting every frame, there’s actually a relatively straightforward way of doing this: for each item, if there are k things left out of a list of N, and p items left to shoot out of a total of Q, then the current item should shoot with probability p/k – and then the values of k and p should be updated. The pseudocode for this looks like:
Note that I’m assuming that random(N) returns a number between 0 and N-1 inclusive; i.e., one of N things. While this algorithm seems like it should choose different items with different probabilities (after all, the check of a random number is changing for each item!), it can be shown mathematically that this not only chooses each individual shooter with the right probability, each set of shooters is actually equally likely.