Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get random element from hashset?

Tags:

c#

hashset

Im using the following piece of code to load my text file into a hashset.

HashSet<string> hashs = new HashSet<string>(File.ReadLines("textFile.txt"));

Am wondering if there is any easy way to get a random line from it?

Lets asume the textFile.txt contains 10 lines, i would like to randomize and grab one of those existing lines.

like image 235
user1213488 Avatar asked May 18 '12 14:05

user1213488


2 Answers

If you are planning on drawing multiple random values, the efficient way would be to use a Dictionary with integer keys to store the information.

HashSet<string> hashs = new HashSet<string>();
Dictionary<int, string> lookup = new Dictionary<int, string>();
foreach (string line in File.ReadLines("textFile.txt")) {
    if (hashs.Add(line)) {
        lookup.Add(lookup.Count, line);
    }
}
        
int randomInt = new Random().Next(lookup.Count);
string randomLine = lookup[randomInt];

(In this example, you could use a List instead, but with a dictionary you can also remove individual elements without affecting the order).

like image 139
Emil Forslund Avatar answered Oct 02 '22 23:10

Emil Forslund


Random randomizer = new Random();
string[] asArray = hashs.ToArray()
string randomLine = asArray[randomizer.Next(asArray.length)];
like image 28
Greg Bahm Avatar answered Oct 03 '22 01:10

Greg Bahm