Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read random line from a file? c#

Tags:

c#

.net

file

I have a text file with few hundred lines, the structure is pretty simple.

firstname lastname

I need to pick out a random firstname & listname from the file.

like image 990
crap Avatar asked Sep 19 '10 13:09

crap


2 Answers

string[] lines = File.ReadAllLines(...); //i hope that the file is not too big
Random rand = new Random();
return lines[rand.Next(lines.Length)];

Another (and maybe better) option is to have the first line of the file contain the number of records in it and then you don't have to read all the file.

like image 120
Itay Karo Avatar answered Nov 05 '22 09:11

Itay Karo


Read each line keeping a count, N, of the lines you have seen so far. Select each line with probability 1/N, i.e., the first line will always be chosen, the second line will be chosen 1/2 times to replace the first, the third 1/3 times, ... This way each line has a 1/N probability of being the selected line, you only have to read the file once, and you don't need to store all of the file in memory at any given time.

Here's an implementation that can be adapted for your needs.

public string RandomLine( StreamReader reader )
{
    string chosen = null;
    int numberSeen = 0;
    var rng = new Random();
    while ((string line = reader.ReadLine()) != null)
    {
        if (rng.NextInt(++numberSeen) == 0)
        {
            chosen = line;
        }
    }
    return chosen;
}

Based on a C implementation for selecting a node from an arbitrarily long linked list.

like image 13
tvanfosson Avatar answered Nov 05 '22 09:11

tvanfosson