简体   繁体   中英

generate random numbers without repetition - java

i'm writing a program for a complicated mathematical operation. I read numbers from a file, then use these numbers to generate as many as possible of sets of 10 random numbers whose sum is 590 and has 5 even numbers and 5 odd numbers (the sum and number of odd and even is changeable). every time I run the code, I get either repeated sets or repeated numbers withing the set.

how to fix this so I have unique sets with 10 unique numbers?

here is my code:

 public static void main(String args[])
  {
     List<Long> numbers = new ArrayList<Long>();
  try{
  FileInputStream fstream = new FileInputStream("numbers.txt");
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  while ((strLine = br.readLine()) != null)   {
      numbers.add(Long.valueOf(strLine));
  }
  Long[] selectedNumbers = new Long[10];
  Random r = new Random();
  for (int j =0; j<100000; j++){
      long sum = 0;
      int odd = 0;
      int even = 0;
      for(int i = 0; i < selectedNumbers.length; i++){
          selectedNumbers[i] = numbers.get(r.nextInt(numbers.size()));
          if (selectedNumbers[i] % 2 == 0)
          {
              even++;
          } 
          else
          {
              odd++;
          }
          sum = sum + selectedNumbers[i];         
      }

          if (even == 5 && sum == 590 )
          {
              for(int k = 0; k < selectedNumbers.length; k++)
              {
                  System.out.print(selectedNumbers[k] + "\t");
              }
              System.out.print("\n");
          }



  }
  in.close();
    }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }

Checkout SecureRandom on this site. It complies with FIPS140-2 or at least did. I've used it to generate "random" 128-bit GUIDs to use as a database ID and I can say for certain that in tests I've inserted around 50 million records into a database and never once hit the same number.

系统时间+ randomNumber可以确保您的号码不会重复!

You are working with the same array that you read in at the beginning and use random index values to pick it's elements.

This is not what your post states:

... to generate as many as possible of sets of 10 random numbers whose sum is 590 and has 5 even numbers and 5 odd numbers ...

Again, your 10 (or whatever number you actually enter) values are not picked at random. Only their order would differ. And, yes, if you pick 10 random integers from 0 to 10 ten times, you could get the same numbers several times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM