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 に答える