[RESOLVED] Semi-Random file selector.
Weighted Random File Selector.
I am planning out a program with several parts. I have used VB as a hobby for a few years but want to do this in C#. I’m not quit up on what should be a module, a sub-routine or what should be a class. Anyway this is part of what I want to do.
Perhaps from a comma delimited text file, a sub-routine would read in or index a list of files that also have a percentage rating associated with each one.
When called, the program would select one file from the list in a weighted random fashion. In other words the file that had a rating of 10 % should come up approximately ten times as often as the file with a rating of 1 % but not in a predicable way.
Would this be just a little code or a lot?
Re: Semi-Random file selector.
IIRC modules are a VB specific thing. Next, in .NET we have config files to store dynamic data, a perferred method over using a comma delimited file. And to answer your question, that shouldn't take much code.
Re: Semi-Random file selector.
The simplest thing to do would be to create a little struct that ties a string (the filename) to a float (the percentage, expressed as a value between 0 and 1).
Code:
struct FileWeight
{
private string _path = "";
private float _weight = 0.0f;
//put public accessors here...
}
Then all you need to do is create one of those for each file in your list, assign a weight to it.
Then once you've got them all in an array (or a list or whatever), just generate a random float in the range zero to (sum of all weights in list).
Then loop through the list adding each weight to a sum until the random float is less than the sum. Then you know you've selected the file by its weight.
20 lines of code max.
:)
Re: Semi-Random file selector.
How about creating a string array where each filename was in the array x% of the time, and use random to index the array?
Re: Semi-Random file selector.
Quote:
Originally Posted by wild_bill
How about creating a string array where each filename was in the array x% of the time, and use random to index the array?
Because that would be...
a) wasteful of memory
b) fiddly to tune for correct weightedness
c) the resolution would be too low.
Re: [RESOLVED] Semi-Random file selector.
Addendum to post #3...
Actually, the weight inside each struct item doesn't have to be between 0 and 1 really, it can be any number. I suggested 0-1 as it might be simpler to deal with.
Just thought I'd better point that out in case you had any problems restraining the values.