2017-08-27 50 views
-1

我目前正在嘗試創建一個程序,生成1到45之間的隨機數字,沒有重複。我的程序在我沒有else語句的情況下運行時,只要出現重複,它會輸入數字0,當我使用else語句時,函數就會中斷。我想要顯示1到45之間的隨機數字,但變量大小必須指定數組的大小。對於具有35c#隨機數發生器陣列中沒有重複

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace RandomArray 
{ 
public class RandomArrayNoDuplicates 
{ 
    static void Main(string[] args) 
    { 
     int size = 45; 
     int[] noDuplicateArray = new int[size]; 
     noDuplicateArray = InitializeArrayWithNoDuplicates(size); 
     DisplayArray(noDuplicateArray); 
     ExitProgram(); 

    } //end Main 
    static Random rng = new Random(); 

    /// <summary> 
    /// Creates an array with each element a unique integer 
    /// between 1 and 45 inclusively. 
    /// </summary> 
    /// <param name="size"> length of the returned array < 45 
    /// </param> 
    /// <returns>an array of length "size" and each element is 
    /// a unique integer between 1 and 45 inclusive </returns> 
    /// 
    static void ExitProgram() 
    { 
     Console.Write("\n\nPress any key to exit program: "); 
     Console.ReadKey(); 
    }//end ExitProgram 

    public static int[] InitializeArrayWithNoDuplicates(int size) 
    { 
    int number; 
    int[] noDuplicates = new int[size]; 

     for (int i = 0; i < size; i++) 
     { 
      number = rng.Next(1, size); 
      if (!noDuplicates.Contains(number)) 
       noDuplicates[i] = number; 
      // else 
      //  i--; 
     } 
     return noDuplicates; 

    } 
    static void DisplayArray(int[] noDuplicates) 
    { 
    foreach (int element in noDuplicates) 
     { 
      Console.Write("\t" + element + "\n"); 
     } 
    } 
} 
} 

數組大小爲1和45之間例如隨機整數的問題就在於此位代碼:

public static int[] InitializeArrayWithNoDuplicates(int size) 
    { 
    int number; 
    int[] noDuplicates = new int[size]; 

     for (int i = 0; i < size; i++) 
     { 
      number = rng.Next(1, size); 
      if (!noDuplicates.Contains(number)) 
       noDuplicates[i] = number; 
      // else 
      //  i--; 
     } 
     return noDuplicates; 

,但我不能確定如何解決它。我寧願使用random.next函數,而不是使用enumberable方法。感謝

+0

到底是什麼問題? – Blacktempel

回答

1

嘗試以下:

 public static int[] InitializeArrayWithNoDuplicates(int size) 
     { 
      Random rand = new Random(); 
      return Enumerable.Repeat<int>(0, size).Select((x, i) => new { i = i, rand = rand.Next() }).OrderBy(x => x.rand).Select(x => x.i).ToArray(); 
     } 

的代碼創建填充零值等於大小整數(Enumerable.Repeat(0,大小))的數組只是爲了得到等於陣列尺寸。所以select創建了一個二維數組,其中i是數字0的大小,rand是一個隨機數。我不重複。該代碼然後簡單地通過隨機數命令二維數組,然後僅提取i值。

+0

很好的答案。你可以分解什麼'返回Enumerable.Repeat (0,size).Select((x,i)=> new {i = i,rand = rand.Next()})。OrderBy(x => x.rand ).Select(x => xi).ToArray();'請做? –

+1

在答案中添加說明。 – jdweng

+0

這工作,如果我想要1到45之間的任何數字。但我希望它始終是隨機整數之間1和45與數組的大小不同。 –

0

如果你去下一個方法的定義,你會看到

// Exceptions: 
// T:System.ArgumentOutOfRangeException: 
//  minValue is greater than maxValue. 

rng.Next(1, 0); 

提高ArgumentOutOfRangeException異常