0

I'm attempting to create an array of random integers that do not repeat. Instead, my array is full of zeroes. We aren't allowed to use things from the outside of our learning such as ArrayList or Arrays class and such. (Pisses me off but I make do).

I haven't tried any other method different as I am still VERY novice, but i've used little iterators and output checkpoints to see what is happening much easier. The random values are initialized but are just not stored.

private Card[] returnShuffled(Card[] cards) {
    Card[] shuffled = cards;                        //Card array
    int[] randomIndexes = new int[cards.length];    //Random ?>NONREPEATING integer array.
    int randomValue;                                //Value entered into Random Indexes.
    for(int x = 0; x < randomIndexes.length; x++) {
        do {
        randomValue = (int) (Math.random()*52);
            System.out.println(randomValue);
        } while(!(search(randomIndexes, randomValue)>-1));
        randomIndexes[x] = randomValue;             //Point of problem: Printing out the Array after loop gives a list of 0s
    }
    for(int x = 0; x < shuffled.length; x++) {
        shuffled[x] = cards[randomIndexes[x]];
    }
    return shuffled;
}

private int search(int[] random, int value) {
int token = -1;
    for(int i = 0; i < random.length; i++) {
        if(random[i]==value) {
            token = i;
            break;
        }
    }
    return token;
}
dpapadopoulos
  • 1,834
  • 5
  • 23
  • 34
  • The usual way to do this is to initialize the array with `[0,1,2,3,.....]` and then randomly shuffle it. You could also just shuffle the original card array. https://stackoverflow.com/questions/1519736/random-shuffling-of-an-array – Thilo Feb 14 '19 at 07:21
  • Your two variables `shuffled`and `cards` actually point to the same physical array. This causes all kinds of unwanted effects when you do `shuffled[x] = cards[randomIndexes[x]]`. But rethink the problem, there is a much simpler approach to do shuffling. – Henry Feb 14 '19 at 07:21
  • Yes, `Math.random` can easily give repeated values. The correct (easy) way to do this is just to shuffle the `Card[]` array. – markspace Feb 14 '19 at 07:22
  • `randomIndexes` is initialized with `0`s so you should add `1` to the generated number and also ignore `0` in your search for repeated numbers. Then when populating `shuffled`, you should deduct 1 from the `cards[]` array element. Also, like what other people mentioned, there are much more straightforward approaches to this. – Jai Feb 14 '19 at 07:27
  • Thanks for all the help. I just redid the entire code after looking up dozens of other people's examples. I think i boxed myself in by attempting to not make use of temporary arrays/objects. – KodenameYT Feb 14 '19 at 07:40

0 Answers0