Reputation: 59
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.
Upvotes: 2
Views: 74
Reputation: 30136
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.
Upvotes: 2