samedi 26 janvier 2019

How to randomly generate a bunch of sites that have roughly the same amount of space between them?

I included JavaFX as a tag because that's what I use to display the sites, but you shouldn't need to understand JavaFX to answer my question. I wanted to include a full working code-example so you can run it yourself. However, to help me out, you probably only need to look at the randomlyChooseSites() method at the bottom of my example.

In this code I generate a bunch of randomized points on a 2D plane. I would like them to be more equal in distance from each-other without being perfectly equal in distance.

How can I randomly generate points on a 2D plane and have them be closer to equal in distance from each-other than they are now, without being perfectly equal in distance?

public class MCVE extends Application {

private final static int WIDTH = 400;
private final static int HEIGHT = 500;

private final static int AMOUNT_OF_SITES = 50;

private final static SplittableRandom RANDOM = new SplittableRandom();

@Override
public void start(Stage primaryStage) {

   // Create the canvas
   Canvas canvas = new Canvas(WIDTH, HEIGHT);
   GraphicsContext gc = canvas.getGraphicsContext2D();
   drawShapes(gc);

   // Add the canvas to the window
   Group root = new Group();
   root.getChildren().add(canvas);
   primaryStage.setScene(new Scene(root));

   // Show the window
   primaryStage.setTitle("Sweep-Line Test");
   primaryStage.show();
}

/**
 * Draws shapes on the Canvas object.
 *
 * @param gc
 */
private void drawShapes(GraphicsContext gc) {

   gc.setFill(Color.BLACK); // sites should be black

   // create random sites
   HashSet<int[]> siteSet = randomlyChooseSites();

   // add the random sites to the displayed window
   for(int[] i : siteSet) {
      gc.fillRect(i[0], i[1], 5, 5);
   }

}

/**
 * Randomly chooses sites and returns them in a HashSet
 * @return
 */
private HashSet<int[]> randomlyChooseSites() {
   // create a HashSet to hold the sites as two-value int[] arrays.
   HashSet<int[]> siteSet = new HashSet<>();

   int[] point; // holds x and y coordinates
   for(int i = 0; i < AMOUNT_OF_SITES; i++) {
      // randomly choose the coordinates and add them to the HashSet
      point = new int[] {RANDOM.nextInt(WIDTH), RANDOM.nextInt(HEIGHT)};
      siteSet.add(point);
   }

   return siteSet;
}

}




Aucun commentaire:

Enregistrer un commentaire