【问题标题】:Randomize the lines of a RichTextBox随机化 RichTextBox 的行
【发布时间】:2013-02-27 01:59:19
【问题描述】:

好吧,我一直在尝试随机化我的 Richtextbox 的行,现在它开始困扰我,因为我正在使用随机但它不起作用......当我使用它时,它会多次重复一些行次,根本不包括一些......

我看过:RichTextBox - sorting lines randomly

但这对我一点帮助都没有。

RichtextBox rtb = new RichTextBox();    
Random R = new Random();
int y;
rtb.Text = "";
for (int i = 0; i < richTextBox1.Lines.Length; i++)
{
   y = R.Next(0, richTextBox1.Lines.Length);
   rtb.Text = rtb.Text + richTextBox1.Lines[y].ToString() + "\r\n";
}
richTextBox2.Text = rtb.Text;

例如如果我输入,

Lorem ipsum dolor sit amet,consectetur adipiscing elit。南仁 aliquam enim。 Proin 在 lacus magna。 Nam bibendum, augue non semper fringilla, ante est interdum ipsum, a egestas urna dolor vel risus。 Phasellus eget dui non augue pretium ullamcorper at ac Tellus。赛德 mattis risus 坐 amet metus dictum egestas。菜豆 enim, ac congue urna bibendum sed。 Sed iaculis pulvinar dui vel 三俗。 Etiam justo metus, consequat in pellentesque eu, eleifend id nunc。

它给了我,

Sed m​​attis risus sat amet metus dictum egestas。菜豆 blandit enim,ac congue urna bibendum sed。 Nam bibendum, augue non semper fringilla, ante est interdum ipsum, a egestas urna dolor vel 风险。 Sed m​​attis risus 坐 amet metus dictum egestas。菜豆 tempus blandit enim,ac congue urna bibendum sed。茯苓 pulvinar dui vel tristique。 Etiam justo metus,结果 pellentesque eu, eleifend id nunc。 Lorem ipsum dolor sit amet, consectetur adipiscing 精英。 Nam in aliquam enim。 Proin at lacus 麦格纳。

其中一行重复,而遗漏了一行……文本越长,它出现的频率越高。

我做 C# 的时间不长,如果这很简单,很抱歉。 :/

【问题讨论】:

  • 您链接的问题的答案似乎完全符合您的要求 - 为什么它对您没有帮助?
  • 那么,您希望这些行以随机顺序排列,而不是重复,并且最终必须提供所有行吗?就像处理一副纸牌......???
  • 您要查找的是shuffle algorithm
  • @Blorgbeard 那里的代码实际上对我不起作用...我对其进行了测试并多次修改...
  • @Robl 我会检查一下,谢谢。

标签: c#


【解决方案1】:

这是你的伪代码逻辑:

Foreach line in original
Choose a random line
Add it to the output

你从不考虑你已经输出了哪些行,因此不知道下次不选择它们。

请注意,在您提供的链接中,他们建议首先将行提取到一个结构中,然后对该结构进行变异以提供新的排序。这样可以确保您每行结束一次。

就地洗牌有几种算法,最简单的是:

Select the first item
Select a random line, after or including the previous selection
Swap the two selections
Repeat moving the first selection to the left

【讨论】:

    【解决方案2】:

    随机意味着“只是”——它会返回一个介于 0 和(富文本框中的行数 - 1)之间的数字。没有唯一性的保证(事实上这不太可能)。

    如果您想以独特的顺序获取它们,则必须跟踪使用过的那些,并且不要再次使用它们。

    一个简单的例子(不一定有效)

       List<int> usedLineIndexes = new List<int>();
    
       while (usedLineIndexes.Count < richTextBox1.Lines.Length)
       {
            int y = R.Next(0, richTextBox1.Lines.Length);
            if (usedLineIndexes.Contains(y))
                continue;   // Try again
    
    
            usedLineIndexes.Add(y);
    
            rtb.Text = rtb.Text + richTextBox1.Lines[y].ToString() + "\r\n";
       }
    

    同样,这是未经测试、效率低下的代码,但它会给你灵感。

    【讨论】:

      猜你喜欢
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多