import java.util.Random; /** This class contains utility methods for array manipulation. */ public class ArrayUtil { /** Creates an array filled with random values. @param length the length of the array @param n the number of possible random values @return an array with elements 0 ... length - 1 filled with randomly selected integers between 0 and n-1 */ public static int[] randomIntArray(int length, int n, long seed) { int[] a = new int[length]; Random generator = new Random(seed); for (int i = 0; i < length; i++) a[i] = generator.nextInt(n); return a; } /** Creates an array filled with values in ascending order. @param length the length of the array @return an array filled with the numbers between 1 and length, in order */ public static int[] ascendingIntArray(int length) { int[] a = new int[length]; for (int i = 0; i < length; i++) a[i] = i + 1; return a; } /** Creates an array filled with values in descending order. @param length the length of the array @return an array filled with the numbers between length and 1, in descending order */ public static int[] descendingIntArray(int length) { int[] a = new int[length]; for (int i = 0; i < length; i++) a[i] = length - i; return a; } /** Creates an array filled with two sequences of values in ascending order. @param length the length of the array @return an array with both the first half and the second half filled with numbers in ascending order */ public static int[] doubleAscendingIntArray(int length) { int[] a = new int[length]; int i; // Fill the first half in ascending order. for (i = 0; i < length / 2; i++) a[i] = i + 1; // Start over at 1 to fill the second half. for (int j = 1; i < length; i++, j++) a[i] = j; return a; } /** Creates an array filled with values in ascending order, except for the first element, which is a large value @param length the length of the array @return an array filled with the numbers between 1 and length, in order, but with a large value in the first element */ public static int[] firstOutOfOrderIntArray(int length) { int[] a = new int[length]; for (int i = 0; i < length; i++) a[i] = i; a[0] = length; return a; } /** Creates an array filled with the same value in each element except for the first and last elements and a few middle elements, which contain selected larger and smaller values @param length the length of the array @return an array filled with numbers, most of which are equal, but with different values in several elements */ public static int[] mostEqualIntArray(int length, int max) { int[] a = new int[length]; for (int i = 0; i < length; i++) a[i] = max / 4; a[0] = max / 2; a[length - 1] = max / 2; a[length / 2] = max / 2 + 1; a[length / 2 - 1] = 1; a[length / 2 + 1] = max - 1; return a; } /** Prints all elements in an array. @param a the array to print */ public static void print(int[] a) { for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } }