【问题标题】:C: Get a random string starting with a specific character from fileC:从文件中获取以特定字符开头的随机字符串
【发布时间】:2018-06-02 19:43:00
【问题描述】:

我厌倦了学习,我决定尝试使用我的 C 知识并编写一个小程序来抓取我保存在文件中的随机推文并显示给我。

文本文件的组织方式如下:

@username
§
tweet1
§
tweet2
§
@username2

我的想法是,当我运行程序时,它会抓取一个随机用户,然后是一条随机推文。

我认为随机化用户的唯一方法是:

  • 遍历所有文本文件,每次看到用户名时都会保存该行并增加一个计数器。然后我随机化选择器并获取用户名。
  • 避免浏览所有文本文件。并且只需将每个用户分成一个单独的文本文件。只需获取某个文件夹中的文件名并从那里随机化(如果可能的话)。

但是同样的问题出现了,如何随机化一条推文,我知道它什么时候开始和结束,但是要随机选择一条,我能想到的唯一方法是上面提到的第一个。

你们有什么更聪明的方法吗?

非常感谢!

【问题讨论】:

  • 一种方法是随机决定停止寻找用户,然后再随机决定停止寻找用户的推文。然后你可能会得到最新的推文。当您阅读时,您可以使随机决定变得越来越严格。那么你就不会使用 3 个月前的推文了。

标签: c file parsing


【解决方案1】:

这是我最近编写的一些代码的评论,其中包含对您有用的信息:

/*
** 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,但推文发推文最多的人比只发一次推文的人更有可能出现。

一旦您决定要遵循哪些规则,基于上述信息的编码就相当简单了。

【讨论】:

    猜你喜欢
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多