I have a weighted selection algorithm that works, but I would like to improve it in two aspects (in order of importance):
- Ensure that the minimum quantity is selected from each possible choice.
- Reduce computational complexity from O (nm) to O (n) or O (m), where n is the requested number of randomly selected elements, and m are the types of available elements.
Edit: The number of requested numbers is usually small (less than 100) for my purposes. Thus, algorithms with complexity O (t) or O (t + n), where t is the total number of elements, is usually worse than O (nm) due to O (t)> O (m).
Simplified code:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; public class Program { static void Main(string[] args) {
The PickRandom() function uses yield return and IEnumerable , but is not required. I was just trying to be smart when I first wrote this function so that it could scroll through something (even say, an enum from the LINQ to SQL query). Subsequently, I found that, despite the flexibility, I never needed it.
My first thought about resolving point number 1 (I guarantee that the minimum number from each possible choice is selected) would be to select the required minimum from each type in a completely nonrandom way, use my existing algorithm to select the remaining unststrined part, then shuffle the results together. It seemed the most natural and imitative, as I will do something similar in real life, but I think that this is not the most effective way.
My second idea was to first create an array of results, randomly select indexes to fill in the required minima first, and then fill in the rest using my existing algorithm, but in all my attempts this led to an increase in the complexity of "big O" or how a big mess of indexes being written all over. I still think that such an approach is possible, I just could not solve it yet.
Then I decided to come here, since this problem seems that it can be abstracted to a fairly general algorithm, but all the keywords that I use for searching usually indicate me the generation of a weighted random number (as opposed to choosing individual elements grouped by type with specific availability). And not a single one was found that holds back the problem with a minimum choice for each type of element, but still remains randomized. Therefore, I hope that someone bright can see a simple effective solution, or someone who has heard this problem before they recognize some better keywords than I can and point me in the right direction.