Creating random numbers with no duplicates

后端 未结 18 1672
忘了有多久
忘了有多久 2020-11-21 12:00

In this case, the MAX is only 5, so I could check the duplicates one by one, but how could I do this in a simpler way? For example, what if the MAX has a value of 20? Thanks

18条回答
  •  有刺的猬
    2020-11-21 12:20

    There is a more efficient and less cumbersome solution for integers than a Collections.shuffle.

    The problem is the same as successively picking items from only the un-picked items in a set and setting them in order somewhere else. This is exactly like randomly dealing cards or drawing winning raffle tickets from a hat or bin.

    This algorithm works for loading any array and achieving a random order at the end of the load. It also works for adding into a List collection (or any other indexed collection) and achieving a random sequence in the collection at the end of the adds.

    It can be done with a single array, created once, or a numerically ordered collectio, such as a List, in place. For an array, the initial array size needs to be the exact size to contain all the intended values. If you don't know how many values might occur in advance, using a numerically orderred collection, such as an ArrayList or List, where the size is not immutable, will also work. It will work universally for an array of any size up to Integer.MAX_VALUE which is just over 2,000,000,000. List objects will have the same index limits. Your machine may run out of memory before you get to an array of that size. It may be more efficient to load an array typed to the object types and convert it to some collection, after loading the array. This is especially true if the target collection is not numerically indexed.

    This algorithm, exactly as written, will create a very even distribution where there are no duplicates. One aspect that is VERY IMPORTANT is that it has to be possible for the insertion of the next item to occur up to the current size + 1. Thus, for the second item, it could be possible to store it in location 0 or location 1. For the 20th item, it could be possible to store it in any location, 0 through 19. It is just as possible the first item to stay in location 0 as it is for it to end up in any other location. It is just as possible for the next new item to go anywhere, including the next new location.

    The randomness of the sequence will be as random as the randomness of the random number generator.

    This algorithm can also be used to load reference types into random locations in an array. Since this works with an array, it can also work with collections. That means you don't have to create the collection and then shuffle it or have it ordered on whatever orders the objects being inserted. The collection need only have the ability to insert an item anywhere in the collection or append it.

    // RandomSequence.java
    import java.util.Random;
    public class RandomSequence {
    
        public static void main(String[] args) {
            // create an array of the size and type for which
            // you want a random sequence
            int[] randomSequence = new int[20];
            Random randomNumbers = new Random();
    
            for (int i = 0; i < randomSequence.length; i++ ) {
                if (i == 0) { // seed first entry in array with item 0
                    randomSequence[i] = 0; 
                } else { // for all other items...
                    // choose a random pointer to the segment of the
                    // array already containing items
                    int pointer = randomNumbers.nextInt(i + 1);
                    randomSequence[i] = randomSequence[pointer]; 
                    randomSequence[pointer] = i;
                    // note that if pointer & i are equal
                    // the new value will just go into location i and possibly stay there
                    // this is VERY IMPORTANT to ensure the sequence is really random
                    // and not biased
                } // end if...else
            } // end for
            for (int number: randomSequence) {
                    System.out.printf("%2d ", number);
            } // end for
        } // end main
    } // end class RandomSequence
    

提交回复
热议问题