使用 C 在文本文件中返回随机行的最佳方法是什么? [英] What's the best way to return a random line in a text file using C?

查看:21
本文介绍了使用 C 在文本文件中返回随机行的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 C 在文本文件中返回随机行的最佳方法是什么?它必须使用标准的 I/O 库(),因为它用于 Nintendo DS 自制软件.

What's the best way to return a random line in a text file using C? It has to use the standard I/O library (<stdio.h>) because it's for Nintendo DS homebrew.

说明:

  • 在文件中使用标题来存储行数对我想要做的事情不起作用.
  • 我希望它尽可能随机(最好是每行与其他行被选中的概率相等.)
  • 在程序运行时文件永远不会改变.(这是 DS,所以没有多任务处理.)

推荐答案

读取每一行,并使用随机数选择是保留该行还是忽略该行.对于第一行,您希望保持 1:1 的赔率;对于第二个,你想要 1:2 的赔率,等等.

Read each line, and use a random number to choose whether to keep that line or ignore it. For the first line, you want odds of 1:1 to keep; for the second, you want odds of 1:2, etc.

count = 0;
while (fgets(line, length, stream) != NULL)
{
    count++;
    if ((rand() * count) / RAND_MAX == 0)
        strcpy(keptline, line);
}

我还没有验证这是否具有适当的随机特性,但乍一看似乎是正确的.<小时>有人指出整数溢出很快就会成为比较编码方式的问题,我自己也独立得出了相同的结论.可能有很多方法可以修复它,但这是第一个想到的:

I haven't verified that this has the proper random qualities, but it seems right at first glance.


It has been pointed out that integer overflow would quickly become a problem with the way the comparison is coded, and I had independently reached the same conclusion myself. There are probably many ways to fix it, but this is the first that comes to mind:

if ((rand() / (float)RAND_MAX) <= (1.0 / count)) 

这篇关于使用 C 在文本文件中返回随机行的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆