随机化队列

本文关键字:队列 随机化 | 更新日期: 2023-09-27 18:25:28

我从txt文件中读取了行。他们大约有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();
        }
    }

随机化队列

队列用于FIFO。你要求的是先进先出之外的其他东西。所以,你在工作中使用了错误的工具。

一个简单的方法是而不是填充队列、填充列表,然后打乱列表中的元素。

这正在使用我的数组:

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

如果您希望队列包含文件随机部分的行,那么您应该用文件的行填充一个列表,然后对其进行混洗,然后在插入值后,将列表插入一个队列中,以创建您所描述的最终结果。

试试这样的东西:

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 ) ;
}