How to generate an array of random numbers without any duplicates (in Java)?












-1















Below is my attempt to populate an array with randomly generated numbers without producing any duplicates. Yet, I am still getting duplicates. Where am I going wrong?



Random rnd = new Random();
int x = 6;
int selectionsIndex = new int[x];
String pool = {"Tom", "Ralph", "Sam", "Craig", "Fred", "Bob", "Tess", "Kayla", "Nina"}; // = 9

for(int i = 0; i < selectionsIndex.length; i++){
// Initial random
selectionsIndex[i] = rnd.nextInt(pool.length);

// Check whether generated number matches any previously generated numbers
for(int j = 0; j < i; j++){
// Match, so generate a new number and restart check
if(selectionsIndex[i] == selectionsIndex[j]){
selectionsIndex[i] = rnd.nextInt(pool.length);
j = 0;
}
}
}









share|improve this question























  • For what I am guessing you want this array, a more common strategy is to populate your array of length N with the numbers from 0 to N-1 in order, then compute a permutation of that array to scramble the numbers in it. Pick a number of iterations (M), then for that many times, pick two elements of the array at random and swap them. Faster than generating random numbers until you get all N of them...

    – moilejter
    Nov 26 '18 at 3:54











  • @moilejter AFAIK, this kind of shuffle (like Hindu shuffle) is very slow for a well-distributed shuffle, generating a random number from a barrel (like picking random card in the pile of card) is kindly better.

    – Geno Chen
    Nov 26 '18 at 4:02











  • Hey @R.Overbeck do mark the answer as correct by clicking on V type tick mark looking button next to the answer, this helps future readers of this question and I'd appreciate that too. Cheers! :)

    – PradyumanDixit
    Dec 26 '18 at 4:17
















-1















Below is my attempt to populate an array with randomly generated numbers without producing any duplicates. Yet, I am still getting duplicates. Where am I going wrong?



Random rnd = new Random();
int x = 6;
int selectionsIndex = new int[x];
String pool = {"Tom", "Ralph", "Sam", "Craig", "Fred", "Bob", "Tess", "Kayla", "Nina"}; // = 9

for(int i = 0; i < selectionsIndex.length; i++){
// Initial random
selectionsIndex[i] = rnd.nextInt(pool.length);

// Check whether generated number matches any previously generated numbers
for(int j = 0; j < i; j++){
// Match, so generate a new number and restart check
if(selectionsIndex[i] == selectionsIndex[j]){
selectionsIndex[i] = rnd.nextInt(pool.length);
j = 0;
}
}
}









share|improve this question























  • For what I am guessing you want this array, a more common strategy is to populate your array of length N with the numbers from 0 to N-1 in order, then compute a permutation of that array to scramble the numbers in it. Pick a number of iterations (M), then for that many times, pick two elements of the array at random and swap them. Faster than generating random numbers until you get all N of them...

    – moilejter
    Nov 26 '18 at 3:54











  • @moilejter AFAIK, this kind of shuffle (like Hindu shuffle) is very slow for a well-distributed shuffle, generating a random number from a barrel (like picking random card in the pile of card) is kindly better.

    – Geno Chen
    Nov 26 '18 at 4:02











  • Hey @R.Overbeck do mark the answer as correct by clicking on V type tick mark looking button next to the answer, this helps future readers of this question and I'd appreciate that too. Cheers! :)

    – PradyumanDixit
    Dec 26 '18 at 4:17














-1












-1








-1








Below is my attempt to populate an array with randomly generated numbers without producing any duplicates. Yet, I am still getting duplicates. Where am I going wrong?



Random rnd = new Random();
int x = 6;
int selectionsIndex = new int[x];
String pool = {"Tom", "Ralph", "Sam", "Craig", "Fred", "Bob", "Tess", "Kayla", "Nina"}; // = 9

for(int i = 0; i < selectionsIndex.length; i++){
// Initial random
selectionsIndex[i] = rnd.nextInt(pool.length);

// Check whether generated number matches any previously generated numbers
for(int j = 0; j < i; j++){
// Match, so generate a new number and restart check
if(selectionsIndex[i] == selectionsIndex[j]){
selectionsIndex[i] = rnd.nextInt(pool.length);
j = 0;
}
}
}









share|improve this question














Below is my attempt to populate an array with randomly generated numbers without producing any duplicates. Yet, I am still getting duplicates. Where am I going wrong?



Random rnd = new Random();
int x = 6;
int selectionsIndex = new int[x];
String pool = {"Tom", "Ralph", "Sam", "Craig", "Fred", "Bob", "Tess", "Kayla", "Nina"}; // = 9

for(int i = 0; i < selectionsIndex.length; i++){
// Initial random
selectionsIndex[i] = rnd.nextInt(pool.length);

// Check whether generated number matches any previously generated numbers
for(int j = 0; j < i; j++){
// Match, so generate a new number and restart check
if(selectionsIndex[i] == selectionsIndex[j]){
selectionsIndex[i] = rnd.nextInt(pool.length);
j = 0;
}
}
}






java






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 26 '18 at 3:28









R. OverbeckR. Overbeck

1




1













  • For what I am guessing you want this array, a more common strategy is to populate your array of length N with the numbers from 0 to N-1 in order, then compute a permutation of that array to scramble the numbers in it. Pick a number of iterations (M), then for that many times, pick two elements of the array at random and swap them. Faster than generating random numbers until you get all N of them...

    – moilejter
    Nov 26 '18 at 3:54











  • @moilejter AFAIK, this kind of shuffle (like Hindu shuffle) is very slow for a well-distributed shuffle, generating a random number from a barrel (like picking random card in the pile of card) is kindly better.

    – Geno Chen
    Nov 26 '18 at 4:02











  • Hey @R.Overbeck do mark the answer as correct by clicking on V type tick mark looking button next to the answer, this helps future readers of this question and I'd appreciate that too. Cheers! :)

    – PradyumanDixit
    Dec 26 '18 at 4:17



















  • For what I am guessing you want this array, a more common strategy is to populate your array of length N with the numbers from 0 to N-1 in order, then compute a permutation of that array to scramble the numbers in it. Pick a number of iterations (M), then for that many times, pick two elements of the array at random and swap them. Faster than generating random numbers until you get all N of them...

    – moilejter
    Nov 26 '18 at 3:54











  • @moilejter AFAIK, this kind of shuffle (like Hindu shuffle) is very slow for a well-distributed shuffle, generating a random number from a barrel (like picking random card in the pile of card) is kindly better.

    – Geno Chen
    Nov 26 '18 at 4:02











  • Hey @R.Overbeck do mark the answer as correct by clicking on V type tick mark looking button next to the answer, this helps future readers of this question and I'd appreciate that too. Cheers! :)

    – PradyumanDixit
    Dec 26 '18 at 4:17

















For what I am guessing you want this array, a more common strategy is to populate your array of length N with the numbers from 0 to N-1 in order, then compute a permutation of that array to scramble the numbers in it. Pick a number of iterations (M), then for that many times, pick two elements of the array at random and swap them. Faster than generating random numbers until you get all N of them...

– moilejter
Nov 26 '18 at 3:54





For what I am guessing you want this array, a more common strategy is to populate your array of length N with the numbers from 0 to N-1 in order, then compute a permutation of that array to scramble the numbers in it. Pick a number of iterations (M), then for that many times, pick two elements of the array at random and swap them. Faster than generating random numbers until you get all N of them...

– moilejter
Nov 26 '18 at 3:54













@moilejter AFAIK, this kind of shuffle (like Hindu shuffle) is very slow for a well-distributed shuffle, generating a random number from a barrel (like picking random card in the pile of card) is kindly better.

– Geno Chen
Nov 26 '18 at 4:02





@moilejter AFAIK, this kind of shuffle (like Hindu shuffle) is very slow for a well-distributed shuffle, generating a random number from a barrel (like picking random card in the pile of card) is kindly better.

– Geno Chen
Nov 26 '18 at 4:02













Hey @R.Overbeck do mark the answer as correct by clicking on V type tick mark looking button next to the answer, this helps future readers of this question and I'd appreciate that too. Cheers! :)

– PradyumanDixit
Dec 26 '18 at 4:17





Hey @R.Overbeck do mark the answer as correct by clicking on V type tick mark looking button next to the answer, this helps future readers of this question and I'd appreciate that too. Cheers! :)

– PradyumanDixit
Dec 26 '18 at 4:17












3 Answers
3






active

oldest

votes


















2














You can use a Set in Java to add the random numbers you have generated, this would get you the numbers and no numbers would be duplicates.



In code it may look something like this:



Random rand = new Random();
Set<Integer> uniques = new HashSet<>();
while (uniques.size()<10){
uniques.add(rand.nextInt(11));
}
for (Integer i : uniques){
System.out.print(i+" ");
}


Some more information about Sets:




  • Set is an interface which extends Collection. It is an unordered collection of objects in which duplicate values cannot be stored.


  • Basically, Set is implemented by HashSet, LinkedHashSet or TreeSet (sorted representation).


  • Set has various methods to add, remove clear, size, etc to enhance the usage of this interface



Know and read more about Sets here.






share|improve this answer

































    0














    Here is an alternate solution as well if you are not familiar with sets.



    I just made a method to check if the number is already existing in the array. if it is it will get a new number until it is unique.



            Random rnd = new Random();
    int x = 6;
    int selectionsIndex = new int[x];
    String pool = { "Tom", "Ralph", "Sam", "Craig", "Fred", "Bob", "Tess", "Kayla", "Nina" }; // = 9
    int counter = 0;
    while(counter!=6) {
    int n = rnd.nextInt(pool.length);
    if(!isDuplicate(n,selectionsIndex)) {
    selectionsIndex[counter] = n;
    counter++;
    }
    }

    // testing outputs
    // for(int i = 0; i < selectionsIndex.length ; i++) {
    // System.out.println(selectionsIndex[i]);
    // }

    }
    public static Boolean isDuplicate(int n, int a) {
    if(a.length == 0 || a == null) {
    return false;
    }
    for(int i = 0; i < a.length ; i++) {
    if(a[i] == n) {
    return true;
    }
    }
    return false;
    }





    share|improve this answer































      0














      The problem is in this part of the code



      if(selectionsIndex[i] == selectionsIndex[j]){
      selectionsIndex[i] = rnd.nextInt(pool.length);
      j = 0;
      }


      At first glimpse your code looks absolutely fine but the devil is in the details, here's the short answer, just do this



      j =-1 instead of j=0



      and it'll work fine



      The Devil



      You see, the for loop increments first and then proceeds except at the initialization step, hence when you do j=0 you expect the checking to start from 0 but instead it starts from 1 because j gets incremented and hence the 0th index is not checked at all.



      That's why you see repetition with the 0th index and some other index only and not with any other pairs of indices.






      share|improve this answer

























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53474428%2fhow-to-generate-an-array-of-random-numbers-without-any-duplicates-in-java%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        2














        You can use a Set in Java to add the random numbers you have generated, this would get you the numbers and no numbers would be duplicates.



        In code it may look something like this:



        Random rand = new Random();
        Set<Integer> uniques = new HashSet<>();
        while (uniques.size()<10){
        uniques.add(rand.nextInt(11));
        }
        for (Integer i : uniques){
        System.out.print(i+" ");
        }


        Some more information about Sets:




        • Set is an interface which extends Collection. It is an unordered collection of objects in which duplicate values cannot be stored.


        • Basically, Set is implemented by HashSet, LinkedHashSet or TreeSet (sorted representation).


        • Set has various methods to add, remove clear, size, etc to enhance the usage of this interface



        Know and read more about Sets here.






        share|improve this answer






























          2














          You can use a Set in Java to add the random numbers you have generated, this would get you the numbers and no numbers would be duplicates.



          In code it may look something like this:



          Random rand = new Random();
          Set<Integer> uniques = new HashSet<>();
          while (uniques.size()<10){
          uniques.add(rand.nextInt(11));
          }
          for (Integer i : uniques){
          System.out.print(i+" ");
          }


          Some more information about Sets:




          • Set is an interface which extends Collection. It is an unordered collection of objects in which duplicate values cannot be stored.


          • Basically, Set is implemented by HashSet, LinkedHashSet or TreeSet (sorted representation).


          • Set has various methods to add, remove clear, size, etc to enhance the usage of this interface



          Know and read more about Sets here.






          share|improve this answer




























            2












            2








            2







            You can use a Set in Java to add the random numbers you have generated, this would get you the numbers and no numbers would be duplicates.



            In code it may look something like this:



            Random rand = new Random();
            Set<Integer> uniques = new HashSet<>();
            while (uniques.size()<10){
            uniques.add(rand.nextInt(11));
            }
            for (Integer i : uniques){
            System.out.print(i+" ");
            }


            Some more information about Sets:




            • Set is an interface which extends Collection. It is an unordered collection of objects in which duplicate values cannot be stored.


            • Basically, Set is implemented by HashSet, LinkedHashSet or TreeSet (sorted representation).


            • Set has various methods to add, remove clear, size, etc to enhance the usage of this interface



            Know and read more about Sets here.






            share|improve this answer















            You can use a Set in Java to add the random numbers you have generated, this would get you the numbers and no numbers would be duplicates.



            In code it may look something like this:



            Random rand = new Random();
            Set<Integer> uniques = new HashSet<>();
            while (uniques.size()<10){
            uniques.add(rand.nextInt(11));
            }
            for (Integer i : uniques){
            System.out.print(i+" ");
            }


            Some more information about Sets:




            • Set is an interface which extends Collection. It is an unordered collection of objects in which duplicate values cannot be stored.


            • Basically, Set is implemented by HashSet, LinkedHashSet or TreeSet (sorted representation).


            • Set has various methods to add, remove clear, size, etc to enhance the usage of this interface



            Know and read more about Sets here.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 26 '18 at 4:51

























            answered Nov 26 '18 at 3:34









            PradyumanDixitPradyumanDixit

            2,1812819




            2,1812819

























                0














                Here is an alternate solution as well if you are not familiar with sets.



                I just made a method to check if the number is already existing in the array. if it is it will get a new number until it is unique.



                        Random rnd = new Random();
                int x = 6;
                int selectionsIndex = new int[x];
                String pool = { "Tom", "Ralph", "Sam", "Craig", "Fred", "Bob", "Tess", "Kayla", "Nina" }; // = 9
                int counter = 0;
                while(counter!=6) {
                int n = rnd.nextInt(pool.length);
                if(!isDuplicate(n,selectionsIndex)) {
                selectionsIndex[counter] = n;
                counter++;
                }
                }

                // testing outputs
                // for(int i = 0; i < selectionsIndex.length ; i++) {
                // System.out.println(selectionsIndex[i]);
                // }

                }
                public static Boolean isDuplicate(int n, int a) {
                if(a.length == 0 || a == null) {
                return false;
                }
                for(int i = 0; i < a.length ; i++) {
                if(a[i] == n) {
                return true;
                }
                }
                return false;
                }





                share|improve this answer




























                  0














                  Here is an alternate solution as well if you are not familiar with sets.



                  I just made a method to check if the number is already existing in the array. if it is it will get a new number until it is unique.



                          Random rnd = new Random();
                  int x = 6;
                  int selectionsIndex = new int[x];
                  String pool = { "Tom", "Ralph", "Sam", "Craig", "Fred", "Bob", "Tess", "Kayla", "Nina" }; // = 9
                  int counter = 0;
                  while(counter!=6) {
                  int n = rnd.nextInt(pool.length);
                  if(!isDuplicate(n,selectionsIndex)) {
                  selectionsIndex[counter] = n;
                  counter++;
                  }
                  }

                  // testing outputs
                  // for(int i = 0; i < selectionsIndex.length ; i++) {
                  // System.out.println(selectionsIndex[i]);
                  // }

                  }
                  public static Boolean isDuplicate(int n, int a) {
                  if(a.length == 0 || a == null) {
                  return false;
                  }
                  for(int i = 0; i < a.length ; i++) {
                  if(a[i] == n) {
                  return true;
                  }
                  }
                  return false;
                  }





                  share|improve this answer


























                    0












                    0








                    0







                    Here is an alternate solution as well if you are not familiar with sets.



                    I just made a method to check if the number is already existing in the array. if it is it will get a new number until it is unique.



                            Random rnd = new Random();
                    int x = 6;
                    int selectionsIndex = new int[x];
                    String pool = { "Tom", "Ralph", "Sam", "Craig", "Fred", "Bob", "Tess", "Kayla", "Nina" }; // = 9
                    int counter = 0;
                    while(counter!=6) {
                    int n = rnd.nextInt(pool.length);
                    if(!isDuplicate(n,selectionsIndex)) {
                    selectionsIndex[counter] = n;
                    counter++;
                    }
                    }

                    // testing outputs
                    // for(int i = 0; i < selectionsIndex.length ; i++) {
                    // System.out.println(selectionsIndex[i]);
                    // }

                    }
                    public static Boolean isDuplicate(int n, int a) {
                    if(a.length == 0 || a == null) {
                    return false;
                    }
                    for(int i = 0; i < a.length ; i++) {
                    if(a[i] == n) {
                    return true;
                    }
                    }
                    return false;
                    }





                    share|improve this answer













                    Here is an alternate solution as well if you are not familiar with sets.



                    I just made a method to check if the number is already existing in the array. if it is it will get a new number until it is unique.



                            Random rnd = new Random();
                    int x = 6;
                    int selectionsIndex = new int[x];
                    String pool = { "Tom", "Ralph", "Sam", "Craig", "Fred", "Bob", "Tess", "Kayla", "Nina" }; // = 9
                    int counter = 0;
                    while(counter!=6) {
                    int n = rnd.nextInt(pool.length);
                    if(!isDuplicate(n,selectionsIndex)) {
                    selectionsIndex[counter] = n;
                    counter++;
                    }
                    }

                    // testing outputs
                    // for(int i = 0; i < selectionsIndex.length ; i++) {
                    // System.out.println(selectionsIndex[i]);
                    // }

                    }
                    public static Boolean isDuplicate(int n, int a) {
                    if(a.length == 0 || a == null) {
                    return false;
                    }
                    for(int i = 0; i < a.length ; i++) {
                    if(a[i] == n) {
                    return true;
                    }
                    }
                    return false;
                    }






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 26 '18 at 3:48









                    peter-cspeter-cs

                    287




                    287























                        0














                        The problem is in this part of the code



                        if(selectionsIndex[i] == selectionsIndex[j]){
                        selectionsIndex[i] = rnd.nextInt(pool.length);
                        j = 0;
                        }


                        At first glimpse your code looks absolutely fine but the devil is in the details, here's the short answer, just do this



                        j =-1 instead of j=0



                        and it'll work fine



                        The Devil



                        You see, the for loop increments first and then proceeds except at the initialization step, hence when you do j=0 you expect the checking to start from 0 but instead it starts from 1 because j gets incremented and hence the 0th index is not checked at all.



                        That's why you see repetition with the 0th index and some other index only and not with any other pairs of indices.






                        share|improve this answer






























                          0














                          The problem is in this part of the code



                          if(selectionsIndex[i] == selectionsIndex[j]){
                          selectionsIndex[i] = rnd.nextInt(pool.length);
                          j = 0;
                          }


                          At first glimpse your code looks absolutely fine but the devil is in the details, here's the short answer, just do this



                          j =-1 instead of j=0



                          and it'll work fine



                          The Devil



                          You see, the for loop increments first and then proceeds except at the initialization step, hence when you do j=0 you expect the checking to start from 0 but instead it starts from 1 because j gets incremented and hence the 0th index is not checked at all.



                          That's why you see repetition with the 0th index and some other index only and not with any other pairs of indices.






                          share|improve this answer




























                            0












                            0








                            0







                            The problem is in this part of the code



                            if(selectionsIndex[i] == selectionsIndex[j]){
                            selectionsIndex[i] = rnd.nextInt(pool.length);
                            j = 0;
                            }


                            At first glimpse your code looks absolutely fine but the devil is in the details, here's the short answer, just do this



                            j =-1 instead of j=0



                            and it'll work fine



                            The Devil



                            You see, the for loop increments first and then proceeds except at the initialization step, hence when you do j=0 you expect the checking to start from 0 but instead it starts from 1 because j gets incremented and hence the 0th index is not checked at all.



                            That's why you see repetition with the 0th index and some other index only and not with any other pairs of indices.






                            share|improve this answer















                            The problem is in this part of the code



                            if(selectionsIndex[i] == selectionsIndex[j]){
                            selectionsIndex[i] = rnd.nextInt(pool.length);
                            j = 0;
                            }


                            At first glimpse your code looks absolutely fine but the devil is in the details, here's the short answer, just do this



                            j =-1 instead of j=0



                            and it'll work fine



                            The Devil



                            You see, the for loop increments first and then proceeds except at the initialization step, hence when you do j=0 you expect the checking to start from 0 but instead it starts from 1 because j gets incremented and hence the 0th index is not checked at all.



                            That's why you see repetition with the 0th index and some other index only and not with any other pairs of indices.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 26 '18 at 10:21

























                            answered Nov 26 '18 at 6:42









                            RyotsuRyotsu

                            565313




                            565313






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53474428%2fhow-to-generate-an-array-of-random-numbers-without-any-duplicates-in-java%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Contact image not getting when fetch all contact list from iPhone by CNContact

                                count number of partitions of a set with n elements into k subsets

                                A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks