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];
        }
    }
4

2 回答 2

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));
        }
    }
于 2010-02-20T03:02:21.717 回答
0

实现类似Fisher-Yates 的东西。不要自己滚。这很可能是错误的。使用指定值播种 Random 构造函数。然后随机播放将是可重复的。

或者,这可以用 linq 很好地完成:

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

更改 的值key以更改随机播放。

于 2010-02-20T03:07:24.903 回答