I’m trying to randomly shuffle integers in an array. That seems simple enough, but I have to shuffle them so that they still remain in a particular order (odd, even, odd, even, etc). For example, if the original array contained [1, 2, 3, 4, 5, 6, 7, 8] then the shuffled array might look like [5, 8, 7, 4, 1, 6, 3, 2], but always retaining the same alternating order, starting with odd.
Thanks for the help. By the way, this isn’t my exact homework problem. I just want to figure out how to do this so that I can do my homework. I don’t know where to start.
I would probably:
You can let the desired elements of the array appear as a List<Integer>
, by implementing AbstractList
accordingly, as a view on the relevant array elements. Then, a simple Collections#shuffle
on the lists will do the trick.
This may seem "unconventional" at the first glance, but has some advantages:
int
arrays (although you can change it to Integer
if you want to)Implemented here as an MCVE:
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class ConstrainedShuffle
{
public static void main(String[] args)
{
int array[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
System.out.println("Before: " + Arrays.toString(array));
constrainedShuffle(array, new Random(0));
System.out.println("After : " + Arrays.toString(array));
}
private static void constrainedShuffle(int array[], Random random)
{
Collections.shuffle(asList(array, 0, 2), random);
Collections.shuffle(asList(array, 1, 2), random);
}
private static List<Integer> asList(int array[], int offset, int stride)
{
int size = (array.length - offset + stride - 1) / stride;
return new AbstractList<Integer>()
{
@Override
public Integer get(int index)
{
return array[offset + index * stride];
}
@Override
public Integer set(int index, Integer element)
{
int i = offset + index * stride;
Integer old = array[i];
array[i] = element;
return old;
}
@Override
public int size()
{
return size;
}
};
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With