import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; /** * This utility class contains some methods for lists of integers. * * * @author Franck van Breugel */ public class Test2E { private Test2E() {} /** * Returns an empty list of integers. * * @return an empty list of integers. */ public static List empty() { return new ArrayList(); } /** * Returns the list containing the given number. * * @param number an integer. * @return the list containing the given number. * @throws IllegalArgumentException if number <= 0 */ public static List single(int number) throws IllegalArgumentException { if (number <= 0) { throw new IllegalArgumentException(); } else { List single = new ArrayList(); single.add(number); return single; } } /** * Returns the list consisting of the integer 1, 2, ..., number. * * @param number an integer. * @pre. number > 0 * @return the list consisting of the integer 1, 2, ..., number. */ public static List interval(int number) { List interval = new ArrayList(); for (int n = 1; n <= number; n++) { interval.add(n); } return interval; } /** * Given a string of digits, each pair of digits * represents an interval. For example, the string
* 14217944
* represents the intervals
* [1, 2, 3, 4], [], [7, 8, 9], [4]
* Note that the second interval is empty since 2 > 1. Combine * all these intervals and return the resulting sorted list. For * the above example, this gives us
* [1, 2, 3, 4, 7, 8, 9]
* For the string
* 1446
* the list [1, 2, 3, 4, 5, 6] is returned. Note that the list * does not contain duplicates. * * @param sequence a string of digits. * @pre. sequence != null && sequence.length() > 0 && sequence.length is even && sequence only contains digits * @return the union of the intervals specified by the given sequence. */ public static List union(String sequence) { Set set = new TreeSet(); for (int i = 0; i < sequence.length(); i = i + 2) { int first = sequence.charAt(i) - '0'; int second = sequence.charAt(i + 1) - '0'; for (int j = first; j <= second; j++) { set.add(j); } } List list = new ArrayList(set); return list; } }