随机化队列

时间:2013-07-29 19:00:54

标签: c#

我从文本文件中读取行。它们大约是10万。如何填充队列并洗牌其元素? 像这样填充队列:

    Queue<string> accs = new Queue<string>();
    private void loadLikeAccountsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.RestoreDirectory = true;
        openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            accs.Clear();

            foreach (string s in File.ReadAllLines(openFileDialog1.FileName))
            {
                accs.Enqueue(s);
            }
            label4.Text = accs.Count.ToString();
        }
    }

4 个答案:

答案 0 :(得分:6)

队列用于FIFO。你要的是其他而不是FIFO。所以,你正在使用错误的工具。

一个简单的方法是而不是填充队列,填写列表,然后shuffle the elements of the list

答案 1 :(得分:1)

这适用于我的数组:

Queue<string> arrProvincies = new Queue<string>(File.ReadAllLines(@"provincies.txt").OrderBy(o => new Guid()));

答案 2 :(得分:0)

如果你想让一个队列拥有来自文件随机部分的行,那么你应该用文件的行填充一个列表,然后将其洗牌,然后将列表的值插入到队列中,创建你所描述的最终结果。

答案 3 :(得分:-1)

尝试这样的事情:

class Program
{
  static void Main( string[] args )
  {
    string myFileName = @"c:\foo\bar\baz.txt" ;
    Queue<string> queue = new Queue<string>( File.ReadAllLines(myFileName).Shuffle() ) ;
  }
}
/// <summary>
/// A few helper methods
/// </summary>
static class ExtensionMethods
{
  /// <summary>
  /// Performs an in-place shuffle of an array
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="instance"></param>
  /// <returns></returns>
  public static T[] Shuffle<T>( this T[] instance )
  {
    for ( int i = 0 ; i < instance.Length ; ++i )
    {
      int j = rng.Next(i,instance.Length ) ; // select a random j such that i <= j < instance.Length

      // swap instance[i] and instance[j]
      T x = instance[j] ;
      instance[j] = instance[i] ;
      instance[i] = x ;

    }

    return instance ;
  }
  private static readonly Random rng = new Random() ;

}

但为什么要使用Queue<T>?什么?这样的事情更简单,更直接:

List<string> shuffledLines = new List<string>( File.ReadAllLines(fn).Shuffle() ) ;
.
.
.
// we iterate over the shuffled list in reverse order so as to 
// shrink the list in place rather than remove the leftmost item
// and moving the remainder wholesale on each iteration.
for ( int i = --shuffledLines.Length ; i >= 0 ; --i )
{
  string s = shuffledLines(i) ;
  shuffledLines.RemoveAt(i) ;

  DoSomethingUseful( s ) ;

}