/** Demo class for working with Arrays */ public class ArrayDemo { // CONSTANT array to represent months public static final String[] months = new String[]{ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; /** Yields: the month name, given its number m * Precondition: 1 <= m <= 12 */ public static String theMonth(int m) { return months[m-1]; /* if (m == 1) { return "January"; } else if (m == 2) { return "Febuary"; } else if (m == 3) { return "March"; } else if (m == 4) { return "April"; } else if (m == 5) { return "May"; } else if (m == 6) { return "June"; } else if (m == 7) { return "July"; } else if (m == 8) { return "August"; } else if (m == 9) { return "September"; } else if (m == 10) { return "October"; } else if (m == 11) { return "November"; } else if (m == 12) { return "December"; } */ } /** Yields: index of first occurrence of c in b[h..k] * Precondition: c is in b[h..k] */ public static int findFirstInRange(int c, int[] b, int h, int k) { // Store in i the index of the first c in b[h..k] int i = h; // invariant: c is not in b[h..i–1] while (b[i] != c) { i= i + 1; } // post: b[i] == c and c is not in b[h..i-1] return i; } /** Yields: a random int in 0..p.length-1; i is returned with probability p[i]. * Precondition: the entries of p are positive and sum to at least 1. */ public static int roll(double[] p) { double r= Math.random(); // r in [0,1) // Think of the interval [0,1] as divided into segments of size p[i]. // Store into i the segment number in which r falls. int i= 0; double pEnd= p[0]; // invariant: r >= sum of p[0] .. p[i–1]; pEnd = sum of p[0] .. p[i] while ( r >= pEnd ) { pEnd= pEnd + p[i+1]; i= i + 1; } // post: sum of p[0] .. p[i-1] <= r < sum of p[0] .. p[i] return i; } /** Procedure swaps b[h] and b[k] */ public static void swap (int[] b, int h, int k) { int temp= b[h]; b[h]= b[k]; b[k]= temp; } }