vendredi 1 mai 2015

Randomize an array while leaving specific elements in place?

Quick question, something in my logic here isnt adding up. Basically I want to shuffle or randomize an array, but keeping specific elements in place. Basically anything over 900 should stay at its same position.. This looks like it should work, but apparently im missing something..

    public static int[] ShuffleArray(int[] data)
{
    for (int t = 0; t < data.Length; t++)
    {
        int tmp = data[t];
        if (tmp < 900)
        {
            int r;
            do
            {
                r = (int)RandomBetween(t, data.Length);
            } while (r > 900);

            data[t] = data[r];
            data[r] = tmp;
        }
    }

    return data;
}

Inputting this:

0,0,1,1,2,2,3, 3,999,4,5,1,999,6, 0,0,1,999,2,2,3, 3,4,4,5,5,6,6, 0,999,1,1,999,999,3, 3,4,4,5,5,6,6, 0,0,1,1,2,2,3,

Getting this:

3,5,6,2,6,1,0, 999,999,3,3,5,999,6, 2,4,999,1,999,2,4, 5,2,0,999,2,1,3, 0,1,5,6,2,0,4, 0,0,4,3,6,0,3, 1,1,5,4,3,1,1,

I thought i caught it with the <900 and the do while.. what am i missing here? the 999's need to stay in place..




Aucun commentaire:

Enregistrer un commentaire