3

txt ファイルから行を読み取ります。それらは約100 000です。キューを埋めてその要素をシャッフルする方法は? 次のようにキューを埋めます。

    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

4 に答える 4

1

これは私の配列で動作しています:

Queue<string> arrProvincies = new Queue<string>(File.ReadAllLines(@"provincies.txt").OrderBy(o => new Guid()));
于 2016-09-12T13:52:51.690 に答える
0

キューにファイルのランダムな部分からの行を含める場合は、リストにファイルの行を入力してシャッフルし、値を挿入した後、リストをキューに挿入して、記述した結果を作成する必要があります。

于 2013-07-29T19:40:07.543 に答える
-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 ) ;

}
于 2013-07-29T19:18:58.710 に答える