Wednesday, February 20, 2013

A Java Random Points Generator


The two simple Java classes below can be used to generate random points within a rectangular box. The generated random points are output in a CSV file.




Point.java

package com.packa9e;

public class Point {
 public double x, y;
 public Point(double x, double y) {
  super();
  this.x = x;
  this.y = y;
 }
}

RandomPointsGenerator.java

package com.packa9e;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;

public class RandomPointsGenerator {

 private static final Random RANDOM = new Random();
 private static final String OUTPUTFILEPATH = "file/randomPoints.csv";
 
 private double left, right, top, bottom;
 private double width, height;
 
 /**
  * The four parameters represent the four edges that enclose the rectangle
  * @param left
  * @param right
  * @param top
  * @param bottom
  */
 public RandomPointsGenerator(double left, double  right, double bottom, double top){
  this.left = left;
  this.right = right;
  this.bottom = bottom;
  this.top = top;
  if (top <= bottom || right <= left){
   JOptionPane.showMessageDialog(null, "Please input valid edges for the rectangle.");
   System.exit(0);
  }
  width = right - left;
  height = top - bottom;
 }
 
 /**
  * get n random points inside the rectangle bounded by the four edges
  * @param n
  * @return points
  */
 public ArrayList getRandomPoints(int n){  
  ArrayList points = new ArrayList();
  double x, y;
  for (int i = 0 ; i < n ; i ++){
   x = left + RANDOM.nextDouble()* width;
   y = bottom + RANDOM.nextDouble() * height;
   points.add(new Point(x, y));
  }
  return points; 
 }
 
 /**
  * output the n random points in a CSV file
  * @param n
  */
 public void outputRandomPoints(int n){
  ArrayList points = getRandomPoints(n);
  try {
   FileWriter write = new FileWriter(OUTPUTFILEPATH);
   BufferedWriter writer = new BufferedWriter(write);
   for (Point point : points){
    writer.write(point.x  + "," + point.y);
    writer.newLine();
   }
   writer.close();
  } catch (IOException e) {
   JOptionPane.showMessageDialog(null, "There's some IO exception");
   System.exit(0);
  }
  System.out.println("Success.");
 }
 
 public static void main(String[] args) {
  RandomPointsGenerator generator = new RandomPointsGenerator(10, 50, 12, 45);
  generator.outputRandomPoints(16);
 }
}

(The "</point></point></point></point>" is a bug of the syntax highlighter)

Output (randomPoints.csv):

No comments:

Post a Comment