import java.util.Map; import java.util.Set; import java.util.TreeMap; /** * This utility class contains some methods for sets of integers. * * @author Franck van Breugel */ public class Test2B { private Test2B() {} /** * Tests whether the given set is empty. * * @param set a set of integers. * @pre. set != null * @return true if the set is empty, false otherwise. */ public static boolean isEmpty(Set set) { return set.isEmpty(); } /** * If the given set contains 0, then it is removed from the * set, otherwise it is added. * * @param set a set of integers. * @pre. set != null */ public static void swapZero(Set set) { if (set.contains(0)) { set.remove(0); } else { set.add(0); } } /** * Returns the sum of the integers in the given set. * * @param set a set of integers. * @pre. set != null * @return the sum of the integers in the given set. */ public static int sum(Set set) { int sum = 0; for (Integer element : set) { sum += element; } return sum; } /** * Returns the difference between any pair of different * integers in the set that occurs most frequently. * In case of ties, the smallest such difference is returned. * The difference is of integers i and j is | i - j |. * Consider for example the set
* { 2, 6, 10, 14, 15, 20, 25, 27 }
* The differences 4 and 5 both occur six times. Since * 4 is smaller than 5, 4 would be returned by this method. * * @param set a set of integers. * @pre. set != null && set.size() > 1 * @return the difference between any pair of different * integers in the set that occurs most frequently. */ public static int maximalDifference(Set set) { Map differenceCount = new TreeMap(); for (Integer first : set) { for (Integer second : set) { if (first != second) { int difference = Math.abs(first - second); int count; if (!differenceCount.containsKey(difference)) { count = 0; } else { count = differenceCount.get(difference); } differenceCount.put(difference, count + 1); } } } int maximalCount = 0; int maximalDifference = 0; for (Integer element : differenceCount.keySet()) { if (maximalCount < differenceCount.get(element)) { maximalCount = differenceCount.get(element); maximalDifference = element; } } return maximalDifference; } }