[英]C: Get a random string starting with a specific character from file
我厌倦了学习,因此决定尝试使用C知识并编写一个小程序来获取我保存在文件中的随机推文,然后将其显示给我。
文本文件的组织方式如下:
@username
§
tweet1
§
tweet2
§
@username2
我的想法是,当我运行程序时,它会捕获一个随机用户,然后捕获一个随机推文。
我认为随机化用户的唯一方法是:
但是随后出现了同样的问题,如何随机化一条tweet,我知道它的开始和结束时间,但是选择一个随机的tweet,我唯一想到的方法就是上面提到的第一个。
你们建议任何更聪明的方法吗?
万分感谢!
这是我编写的一些最近代码的评论,其中包含对您有用的信息:
/*
** From Wikipedia on Reservoir Sampling
** https://en.wikipedia.org/wiki/Reservoir_sampling
**
** Algorithm R
** The most common example was labelled Algorithm R by Jeffrey Vitter in
** his paper on the subject. This simple O(n) algorithm as described in
** the Dictionary of Algorithms and Data Structures consists of the
** following steps (assuming k < n and using one-based array indexing):
**
** // S has items to sample, R will contain the result
** ReservoirSample(S[1..n], R[1..k])
** // fill the reservoir array
** for i = 1 to k
** R[i] := S[i]
**
** // replace elements with gradually decreasing probability
** for i = k+1 to n
** j := random(1, i) // important: inclusive range
** if j <= k
** R[j] := S[i]
**
** Alternatively: https://stackoverflow.com/questions/232237
** What's the best way to return one random line in a text file
**
** count = 0;
** while (fgets(line, length, stream) != NULL)
** {
** count++;
** // if ((rand() * count) / RAND_MAX == 0)
** if ((rand() / (float)RAND_MAX) <= (1.0 / count))
** strcpy(keptline, line);
** }
**
** From Perl perlfaq5:
** Here's a reservoir-sampling algorithm from the Camel Book:
**
** srand;
** rand($.) < 1 && ($line = $_) while <>;
**
** This has a significant advantage in space over reading the whole file
** in. You can find a proof of this method in The Art of Computer
** Programming, Volume 2, Section 3.4.2, by Donald E. Knuth.
*/
您需要对在您的情况下构成随机选择的内容做出一些决定。
如果您的文件中有12个高音扬声器,(出于讨论目的)每个高音扬声器之间有1至12条高音,那么您是否要选择概率为1/12的每个高音扬声器,然后每个高音扬声器在以下位置选择其高音扬声器之一:随机(从属于该高音扬声器的集合中),或者您有其他想法吗?例如,如果有66条高音,则将有1/66的概率会选择给定的高音,但发过高音的高音比只发过一次Twitter的人更有可能出现。
一旦确定了要遵循的规则,基于上述信息的编码就很简单了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.