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

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

问题描述

什么是在使用C一个文本文件中返回一个随机行的最佳方法是什么?它使用标准I / O库(<&stdio.h中GT; ),因为它是任天堂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);
}

我没有验证,这有一个正确的随机性质,但它似乎是正确的第一眼。



据指出,整数溢出会很快成为比较为codeD的方式有问题,我已经独立得出同样的结论我自己。可能有许多方法来解决这个问题,但是这是我想到的第一:

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天全站免登陆