2

Quick question, something in my logic here isn't adding up. Basically I want to shuffle or randomize an array, but keep specific elements in place. Anything over 900 should stay in the same position. This looks like it should work, but apparently I'm 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.

3
  • Please tag the language!!! Commented May 2, 2015 at 6:36
  • Not knowing the language or libraries in use, can't verify that RandomBetween returns a value greater-than-or-equal to the first parameter and strictly less than the second, but you need it to. Commented May 2, 2015 at 6:43
  • Sorry about not tagging the C#.. apparently I'm more tired than I realized. Commented May 2, 2015 at 6:47

1 Answer 1

2

Your logic is incorrect because you are using r as an index.


Change this:

while (r > 900)

To this:

while (data[r] > 900)

Please note that your algorithm by itself is extremely inefficient.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh good gravy... I must be more tired than I thought.. thank you for pointing out the obvious.. Sorry about not tagging the language, didn't think it made much difference in this case.. C# for the record though.. I'm sure there's a lot that inefficient, this was mostly a first pass just to make it work.. I would love to see a more optimized version though if you have time! thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.