1 package org.peterd.util;
2
3 import java.awt.Dimension;
4 import java.util.Random;
5
6
7 public final class Misc {
8 private Misc() {}
9
10 public static boolean equal(Object a, Object b) {
11 if (a == null || b == null) {
12 return a == b;
13 } else {
14 return a.equals(b);
15 }
16 }
17
18 public static <E> E or(E a, E b) {
19 if (a == null) return b;
20 else return a;
21 }
22
23 public static boolean arraysEqual(Object[] a, Object[] b) {
24 if (a.length != b.length) return false;
25 for (int i = 0; i < a.length; i++) {
26 if (!Misc.equal(a[i],b[i])) return false;
27 }
28 return true;
29 }
30
31 public static <X extends Comparable<X>> boolean arraySorted(X[] a) {
32 for (int i = 0; i < a.length - 1; i++) {
33 if (a[i].compareTo(a[i+1]) > 0) return false;
34 }
35 return true;
36 }
37
38 public static void randomlyPermute(Object[] a) {
39 int i = a.length;
40 while (i > 1) {
41 int idx = random.nextInt(i);
42 i--;
43 Object tmp = a[idx];
44 a[idx] = a[i];
45 a[i] = tmp;
46 }
47 }
48
49 public static <E> E randomElementOf(E[] a) {
50 if (a.length == 0) {
51 throw new IllegalArgumentException("Cannot take random element from 0-length array");
52 }
53 return a[random.nextInt(a.length)];
54 }
55
56 public static Random random = new Random();
57
58
59 public static Dimension maxDimensions(Dimension a, Dimension b) {
60 return new Dimension(Math.max(a.width, b.width),
61 Math.max(a.height, b.height));
62 }
63
64 public static void appendNSpaces(StringBuilder b, int n) {
65 for (int i = 0; i < n; i++) {
66 b.append(' ');
67 }
68 }
69 }