View Category

Find the distance between two points

java
double distance = Point2D.distance(x1, y1, x2, y2);
Point2D point1 = new Point2D.Double(x1, y1);
Point2D point2 = new Point2D.Double(x2, y2);
double distance = point1.distance(point2);
double distance = Math.hypot(x2-x1, y2-y1);

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
java
String formatted = new DecimalFormat("00000000").format(42);
String formatted = String.format("%08d", 42);

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
java
private static String spaces(int spaces) {
StringBuffer sb = new StringBuffer();
for(int i=0; i<spaces; i++) {
sb.append(' ');
}
return sb.toString();
}

private static String rightPad(int number, int spaces) {
String numberString = String.valueOf(number);
return numberString + spaces(spaces - numberString.length());
}
String text = StringUtils.rightPad(String.valueOf(1024), 6)
String formatted = String.format("%-6d", 1024);

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
java
String formatted = String.format("%3.2f", 7./8.);

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
java
private static String spaces(int spaces) {
StringBuffer sb = new StringBuffer();
for(int i=0; i<spaces; i++) {
sb.append(' ');
}
return sb.toString();
}

private static String leftPad(int number, int spaces) {
String numberString = String.valueOf(number);
return spaces(spaces - numberString.length()) + numberString;
}
String formatted = String.format("%10d", 73);

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
java
Random random = new Random();
int randomInt = random.nextInt(200-100+1)+100;

Generate a repeatable random number sequence

Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
java
int[] arr1 = genFillRand(new int[5], new Random(12345), 100, 200);
int[] arr2 = genFillRand(new int[5], new Random(12345), 100, 200);

for (int[] arr : new int[][]{ arr1, arr2 }) { for (int i : arr) System.out.printf("%d ", i); System.out.println(); }