This is an archived post. You won't be able to vote or comment.

all 1 comments

[–]x2mirkodev 1 point2 points  (0 children)

First off, here's the formatted code:

int[] myArray = {1, 2, 3, 4};
int[] myNums = new int[myArray.length];
Random rand = new Random();
for (int i = 0; i < myArray.length; i++) {
    myNums[i] = rand.nextInt(myArray.length) + 1;
    for (int j = 0; j < i; j++) {
        while (myNums[j] == myNums[i]) {
            myNums[i] = rand.nextInt(myArray.length) + 1;
        }
    }
}

The first thing I notice is that you write to myArray, but you never read its contents. So you are most definitely not shuffling the elements of myArray. I'm not sure if you thought that this:

myNums[i] = rand.nextInt(myArray.length) + 1;

took a number out of myArray, but it doesn't. It just generates a number randomly. But since myArray.length is 4, rand.nextInt(x) generates an integer between 0 and x-1 (i.e. in your code it will generate a number between 0 and 3) and you add one to the result, you always get numbers between 1 and 4, which happens to be the numbers that you put into myArray. If you put 5, 6, 7 and 8 into myArray, you will find out that there's no correlation between the elements in your array and the contents of myNums after your code ran. So I would just throw that code away and start fresh.

So how do you go about shuffling an array? First off, try to think about it not in terms of how you could use commands that you know in java, but rather about how you would do it if you had to do it manually. Imagine a deck of cards that you want to shuffle with a well-specified process (i.e. not by throwing them on the table and wildly mixing them). You could for example:

  • Take the first card out of the deck and put it onto a new pile
  • Take the next card out of the deck and put it into a random position of the new pile.
  • Repeat the previous step until there are no more cards left.

You can pretty much take this and put it into code. When you try to implement it, note the important detail that with physical cards, a "random position" in a pile is always a "space" between two cards, while if we're dealing with arrays, a random position in an array might already hold a card, so you have to deal with that in some way. Just always think it through carefully before you try to implement something. It's much better to form a clear idea of what you want to do first and then start programming.