Masood Delfarah
Masood Delfarah

Reputation: 697

java random generator

I want to generate some random doubles and add them into an ArrayList, but it seems that the nextDouble() function returns a unique double every time, not a new one

Random r = new Random();
ArrayList<Pair> centers = new ArrayList<Pair>();  
ArrayList<ArrayList<Pair>> classes = new ArrayList<ArrayList<Pair>>();  
for (int i=0 ; i < 100; i++) {
    // Random r = new Random ();
    // System.out.println (r.nextDouble ()) ;
    double a = r.nextDouble () * 10;
    double b = r.nextDouble () * 10;
    centers.add (new Pair (a, b ));
    System.out.println (centers);
}               

Can anyone help me with this? Is this a mistake of optimization?

Upvotes: 0

Views: 1756

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200138

I ran this code:

public static void main(String[] args) {
  Random r = new Random();
  ArrayList<Pair> centers = new ArrayList<Pair>();
  for(int i = 0; i < 100; i++ ) {
    double a = r.nextDouble() * 10;
    double b = r.nextDouble() * 10;
    centers.add( new Pair(a, b) );
  }
  System.out.println(centers);
}

This was the output:

[(8.08, 8.06), (9.97, 1.83), (3.83, 3.19), (2.97, 2.51), (9.40, 2.88), (7.78, 2.59), (1.67, 9.07) ...

Isn't that what you want? FYI, this is the Pair class I used:

class Pair {
  private final double a, b;
  Pair(double a, double b) { this.a = a; this.b = b; }
  @Override public String toString() { return String.format("(%.2f, %.2f)", a, b); }
}

Upvotes: 4

Related Questions