Ita*_*aro 15
string[] lines = File.ReadAllLines(...); //i hope that the file is not too big
Random rand = new Random();
return lines[rand.Next(lines.Length)];
Run Code Online (Sandbox Code Playgroud)
另一个(也许更好)选项是让文件的第一行包含其中的记录数,然后您不必读取所有文件.
tva*_*son 11
读取每行,保持您目前所看到的行数N.选择每条线的概率为1/N,即始终选择第一条线,第二条线将被选择1/2次以替换第一条线,第三条线为1/3次,...这样每条线都有一条线作为所选行的1/N概率,您只需要读取一次文件,并且您不需要在任何给定时间将所有文件存储在内存中.
这是一个可以根据您的需求进行调整的实现.
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;
}
Run Code Online (Sandbox Code Playgroud)
基于用于从任意长链表中选择节点的C实现.
| 归档时间: |
|
| 查看次数: |
7480 次 |
| 最近记录: |