2010-02-20 104 views
0

我期待隨機隨機使用密鑰洗牌列表/數組。我希望能夠使用密鑰重複相同的隨機順序。需要使用密鑰的可重複的隨機數組隨機洗牌

所以我會隨機生成一個數字鍵從說1到20,然後使用該鍵嘗試隨機洗牌列表。

我第一次嘗試只是使用該鍵來繼續遍歷我的列表,遞減鍵直到= 0,然後抓住我所在的任何元素,將其刪除並將其添加到我的混洗數組中。結果是隨機的,但是當數組很小時(我的大部分時間都是這樣)和/或關鍵是小的,它不會結束混洗......似乎更像是一個轉變。

我必須能夠確定什麼樣的順序

這裏是在csharp的一些示例代碼:

public static TList<VoteSetupAnswer> ShuffleListWithKey(TList<VoteSetupAnswer> UnsortedList, int ShuffleKey) 
    { 
     TList<VoteSetupAnswer> SortedList = new TList<VoteSetupAnswer>(); 
     int UnsortedListCount = UnsortedList.Count; 
     for (int i = 0; i < UnsortedListCount; i++) 
     { 
      int Location; 
      SortedList.Add(OneArrayCycle(UnsortedList, ShuffleKey, out Location)); 
      UnsortedList.RemoveAt(Location); 
     } 
     return SortedList; 
    } 

    public static VoteSetupAnswer OneArrayCycle(TList<VoteSetupAnswer> array, int ShuffleKey, out int Location) 
    { 
     Location = 0; 
     if (ShuffleKey == 1) 
     { 
      Location = 0; 
      return array[0]; 
     } 
     else 
     { 
      for (int x = 0; x <= ShuffleKey; x++) 
      { 
       if (x == ShuffleKey) 
        return array[Location]; 
       Location++; 
       if (Location == array.Count) 
        Location = 0; 
      } 
      return array[Location]; 
     } 
    } 

回答

1

做一個隨機排列,種子與你的鑰匙RNG。

/** 
    * Randomly permutes the array of this permutation. All permutations occur with approximately equal 
    * likelihood. This implementation traverses the permutation array forward, from the first element up to 
    * the second last, repeatedly swapping a randomly selected element into the "current position". Elements 
    * are randomly selected from the portion of the permutation array that runs from the current position to 
    * the last element, inclusive. 
    * <p> 
    * This method runs in linear time. 
    */ 
    public static void shuffle(Random random, int[] a) { 
     for (int i = 0; i < a.length - 1; i++) { 
      swap(a, i, i + random.nextInt(a.length - i)); 
     } 
    } 
+0

謝謝你的回覆。如果我想重複我的數組的相同順序,那麼隨機random.nextInt將不會每次調用返回不同的數字。我需要一種方法來重現相同的洗牌順序 – user277488 2010-03-08 17:14:56

+0

用固定種子對隨機類進行種子處理。 – bmargulies 2010-03-08 19:45:24

0

實施類似Fisher-Yates的東西。不要推出自己的。這很可能是錯誤的。具有指定值的Seed the Random constructor。洗牌將是可重複的。

或者,這可以很好地使用LINQ做:

var key=0; 
var r=new Random(key); 
myList.OrderBy(x=>r.Next()); 

變化key值改變洗牌。

+0

我沒有使用Linq。但這很有趣。 .OrderBy可以採用索引而不是字段。所以它隨機排序上漲呢? – user277488 2010-03-08 17:18:57

+0

那麼,它並不是真正按照「字段」排序,而是評估字段的價值。這不一定是lambda參數(在上面的例子中是x)的一個屬性,而是範圍內的任何東西。 – spender 2010-03-08 18:53:25