/** * Either adds a value to set or does nothing if value is already present. * * @param val Value to add. * @return The instance of value from this set or {@code null} if value was added. */ @Nullable public V addx(V val) { A.notNull(val, "val"); if (comp == null) { for (V v : vals) if (v.equals(val)) return v; vals.add(val); return null; } if (strict) { for (ListIterator<V> it = vals.listIterator(); it.hasNext(); ) { V v = it.next(); // Prefer equals to comparator. if (v.equals(val)) return v; int c = comp.compare(v, val); if (c == 0) throw new IllegalStateException("Inconsistent equals and compare methods."); if (c > 0) { // Back up. it.previous(); it.add(val); return null; } } vals.add(val); return null; } // Full scan first. for (V v : vals) if (v.equals(val)) return v; for (ListIterator<V> it = vals.listIterator(); it.hasNext(); ) { V v = it.next(); if (comp.compare(v, val) > 0) { do { // Back up. v = it.previous(); } while (comp.compare(v, val) == 0); it.add(val); return null; } } vals.add(val); return null; }
private Node<T, V> insertTree(Node<T, V> subTree, T t, V v) // called by public void insert(T t) { // insert to a subtree and return the reference of this subtree Node<T, V> ansNode = null; if (subTree == null) { ansNode = new Node<T, V>(t, v); ansNode.leftChild = null; ansNode.rightChild = null; ansNode.height = 0; // null tree's height is -1 } else if (comp.compare(t, subTree.t) < 0) // insert to the leftSubTree of subTree { subTree.leftChild = insertTree(subTree.leftChild, t, v); if (getHeight(subTree.leftChild) - getHeight(subTree.rightChild) == 2) // subtree is the minimum unbalanced subTree { // singleLeftRotate or doubleLeftRightRorate if (getHeight(subTree.leftChild.leftChild) > getHeight(subTree.leftChild.rightChild)) { ansNode = singleLeftRotate(subTree); } else { ansNode = doubleLeftRightRotate(subTree); } } else { // Only the change of structure of tree causes the change of it's height subTree.height = 1 + (getHeight(subTree.leftChild) >= getHeight(subTree.rightChild) ? getHeight(subTree.leftChild) : getHeight(subTree.rightChild)); ansNode = subTree; } } else if (comp.compare(t, subTree.t) > 0) // insert to the rightSubTree of subTree { subTree.rightChild = insertTree(subTree.rightChild, t, v); if (getHeight(subTree.rightChild) - getHeight(subTree.leftChild) == 2) // subtree is the minimum unbalanced subTree { // singleLeftRotate or doubleLeftRightRorate if (getHeight(subTree.rightChild.rightChild) > getHeight(subTree.rightChild.leftChild)) { ansNode = singleRightRotate(subTree); } else { ansNode = doubleRightLeftRotate(subTree); } } else { // Only the change of structure of tree causes the change of it's height subTree.height = 1 + (getHeight(subTree.leftChild) > getHeight(subTree.rightChild) ? getHeight(subTree.leftChild) : getHeight(subTree.rightChild)); ansNode = subTree; } } return ansNode; }
/** * Like gallopLeft, except that if the range contains an element equal to key, gallopRight returns * the index after the rightmost equal element. * * @param key the key whose insertion point to search for * @param a the array in which to search * @param base the index of the first element in the range * @param len the length of the range; must be > 0 * @param hint the index at which to begin the search, 0 <= hint < n. The closer hint is to the * result, the faster this method will run. * @param c the comparator used to order the range, and to search * @return the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k] */ private static <T> int gallopRight( T key, T[] a, int base, int len, int hint, Comparator<? super T> c) { assert len > 0 && hint >= 0 && hint < len; int ofs = 1; int lastOfs = 0; if (c.compare(key, a[base + hint]) < 0) { // Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs] int maxOfs = hint + 1; while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) < 0) { lastOfs = ofs; ofs = (ofs << 1) + 1; if (ofs <= 0) // int overflow ofs = maxOfs; } if (ofs > maxOfs) ofs = maxOfs; // Make offsets relative to b int tmp = lastOfs; lastOfs = hint - ofs; ofs = hint - tmp; } else { // a[b + hint] <= key // Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs] int maxOfs = len - hint; while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) >= 0) { lastOfs = ofs; ofs = (ofs << 1) + 1; if (ofs <= 0) // int overflow ofs = maxOfs; } if (ofs > maxOfs) ofs = maxOfs; // Make offsets relative to b lastOfs += hint; ofs += hint; } assert -1 <= lastOfs && lastOfs < ofs && ofs <= len; /* * Now a[b + lastOfs] <= key < a[b + ofs], so key belongs somewhere to * the right of lastOfs but no farther right than ofs. Do a binary * search, with invariant a[b + lastOfs - 1] <= key < a[b + ofs]. */ lastOfs++; while (lastOfs < ofs) { int m = lastOfs + ((ofs - lastOfs) >>> 1); if (c.compare(key, a[base + m]) < 0) ofs = m; // key < a[b + m] else lastOfs = m + 1; // a[b + m] <= key } assert lastOfs == ofs; // so a[b + ofs - 1] <= key < a[b + ofs] return ofs; }
private boolean contains(BinaryTreeNodeImpl<E> node, BinaryTreeNodeImpl<E> subroot) { count++; if (subroot == null) { return false; } if (c.compare(node.getData(), subroot.getData()) == 0) { return true; } if (c.compare(node.getData(), subroot.getData()) < 0) { return contains(node, (BinaryTreeNodeImpl<E>) subroot.getLeft()); } else { return contains(node, (BinaryTreeNodeImpl<E>) subroot.getRight()); } }
/** * Returns the length of the run beginning at the specified position in the specified array and * reverses the run if it is descending (ensuring that the run will always be ascending when the * method returns). * * <p>A run is the longest ascending sequence with: * * <p>a[lo] <= a[lo + 1] <= a[lo + 2] <= ... * * <p>or the longest descending sequence with: * * <p>a[lo] > a[lo + 1] > a[lo + 2] > ... * * <p>For its intended use in a stable mergesort, the strictness of the definition of "descending" * is needed so that the call can safely reverse a descending sequence without violating * stability. * * @param a the array in which a run is to be counted and possibly reversed * @param lo index of the first element in the run * @param hi index after the last element that may be contained in the run. It is required that * {@code lo < hi}. * @param c the comparator to used for the sort * @return the length of the run beginning at the specified position in the specified array */ private static <T> int countRunAndMakeAscending(T[] a, int lo, int hi, Comparator<? super T> c) { assert lo < hi; int runHi = lo + 1; if (runHi == hi) return 1; // Find end of run, and reverse range if descending if (c.compare(a[runHi++], a[lo]) < 0) { // Descending while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0) runHi++; reverseRange(a, lo, runHi); } else { // Ascending while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0) runHi++; } return runHi - lo; }
/** * Removes given value from the set and returns the instance stored in the set or {@code null} if * value was not found. * * @param val Value to remove. * @return The instance that was stored in the set or {@code null}. */ @Nullable public V removex(V val) { A.notNull(val, "val"); if (comp == null || !strict) { for (Iterator<V> it = vals.iterator(); it.hasNext(); ) { V v = it.next(); if (v.equals(val)) { it.remove(); return v; } } return null; } assert comp != null && strict; for (Iterator<V> it = vals.iterator(); it.hasNext(); ) { V v = it.next(); // Prefer equals to comparator. if (v.equals(val)) { it.remove(); return v; } if (comp.compare(v, val) > 0) break; } return null; }
/** * Set pairwise ordering between all factories according a comparator. Calls to <code> * {@linkplain Comparator#compare compare}(factory1, factory2)</code> should returns: * * <ul> * <li>{@code -1} if {@code factory1} is preferred to {@code factory2} * <li>{@code +1} if {@code factory2} is preferred to {@code factory1} * <li>{@code 0} if there is no preferred order between {@code factory1} and {@code factory2} * </ul> * * @param <T> The class represented by the {@code category} argument. * @param category The category to set ordering. * @param comparator The comparator to use for ordering. * @return {@code true} if at least one ordering setting has been modified as a consequence of * this call. */ public <T> boolean setOrdering(final Class<T> category, final Comparator<T> comparator) { boolean set = false; final List<T> previous = new ArrayList<T>(); for (final Iterator<T> it = getServiceProviders(category, false); it.hasNext(); ) { final T f1 = it.next(); for (int i = previous.size(); --i >= 0; ) { final T f2 = previous.get(i); final int c; try { c = comparator.compare(f1, f2); } catch (ClassCastException exception) { /* * This exception is expected if the user-supplied comparator follows strictly * the java.util.Comparator specification and has determined that it can't * compare the supplied factories. From ServiceRegistry point of view, it just * means that the ordering between those factories will stay undeterminated. */ continue; } if (c > 0) { set |= setOrdering(category, f1, f2); } else if (c < 0) { set |= setOrdering(category, f2, f1); } } previous.add(f1); } return set; }
public final void ensureSortedIfEnabled() { if (ENSURE_SORTED_PRECONDITIONS_ENABLED) { for (int i = 1; i < array.size(); i++) { Preconditions.checkState(comparator.compare(array.get(i - 1), array.get(i)) <= 0); } } }
@SuppressWarnings("unchecked") @Override public Array<T> sorted(Comparator<? super T> comparator) { final Object[] arr = toArray(this); Arrays.sort(arr, (o1, o2) -> comparator.compare((T) o1, (T) o2)); return wrap(arr); }
/** * Finds the index of the best solution in the list according to a comparator * * @param solutionList * @param comparator * @return The index of the best solution */ public static <S extends Solution<?>> int findIndexOfBestSolution( List<S> solutionList, Comparator<S> comparator) { if (solutionList == null) { throw new JMetalException("The solution list is null"); } else if (solutionList.isEmpty()) { throw new JMetalException("The solution list is empty"); } else if (comparator == null) { throw new JMetalException("The comparator is null"); } int index = 0; S bestKnown = solutionList.get(0); S candidateSolution; int flag; for (int i = 1; i < solutionList.size(); i++) { candidateSolution = solutionList.get(i); flag = comparator.compare(bestKnown, candidateSolution); if (flag == 1) { index = i; bestKnown = candidateSolution; } } return index; }
@Override public <U> Array<T> sortBy( Comparator<? super U> comparator, Function<? super T, ? extends U> mapper) { final Function<? super T, ? extends U> domain = Function1.of(mapper::apply).memoized(); return toJavaStream() .sorted((e1, e2) -> comparator.compare(domain.apply(e1), domain.apply(e2))) .collect(collector()); }
private V getValueTree(T t, Node<T, V> subTree) { V ansV = null; if (subTree == null) { // System.err.println("Key " + t + " does not exist."); // System.err.flush(); ansV = null; } else if (comp.compare(t, subTree.t) == 0) { ansV = subTree.v; } else if (comp.compare(t, subTree.t) < 0) { ansV = getValueTree(t, subTree.leftChild); } else if (comp.compare(t, subTree.t) > 0) { ansV = getValueTree(t, subTree.rightChild); } return ansV; }
ImmutableSortedSet subSet(Object obj, boolean flag, Object obj1, boolean flag1) { Preconditions.checkNotNull(obj); Preconditions.checkNotNull(obj1); boolean flag2; if (comparator.compare(obj, obj1) <= 0) flag2 = true; else flag2 = false; Preconditions.checkArgument(flag2); return subSetImpl(obj, flag, obj1, flag1); }
/** * Finds index of a given item in the list, or {@code -1}, if not found. * * @param item the item to search for * @return index of item in the list, or {@code -1} if not found */ public int findIndex(T item) { for (int i = findInsertionIndex(item); i < array.size() && comparator.compare(item, array.get(i)) == 0; i++) { if (array.get(i).equals(item)) { return i; } } return -1; }
@Override public boolean add(T arg0) { int index = 0; outer: for (index = queue.size() - 1; index >= 0; index--) { int compare = comparator.compare(arg0, queue.get(index)); if (compare == 0) { while (compare == 0 && index >= 0) { index--; compare = comparator.compare(arg0, queue.get(index)); } break outer; } } // loop through queue from the end // compare element in queue with argument queue.add(index, arg0); return false; }
/** * {@inheritDoc} * * @see java.util.NavigableSet#headSet(Object, boolean) * @since 1.6 */ @SuppressWarnings("unchecked") public NavigableSet<E> headSet(E end, boolean endInclusive) { // Check for errors Comparator<? super E> c = backingMap.comparator(); if (c == null) { ((net.sourceforge.retroweaver.harmony.runtime.java.lang.Comparable<E>) end).compareTo(end); } else { c.compare(end, end); } return new TreeSet<E>(backingMap.headMap(end, endInclusive)); }
public SortedSet subSet(Object fromElement, Object toElement) { Iterator it = iterator(); SortedMultiSet newSet = new SortedMultiSet(); while (it.hasNext()) { Object o = it.next(); int compare1 = 0; int compare2 = 0; if (comparator != null) { compare1 = comparator.compare(o, fromElement); compare2 = comparator.compare(o, toElement); } else { Comparable c = (Comparable) o; compare1 = c.compareTo(fromElement); compare2 = c.compareTo(toElement); } if ((compare1 >= 0) && (compare2 < 0)) { newSet.add(o); } } return newSet; }
/** * {@inheritDoc} * * @see java.util.NavigableSet#tailSet(Object, boolean) * @since 1.6 */ @SuppressWarnings("unchecked") public NavigableSet<E> tailSet(E start, boolean startInclusive) { // Check for errors Comparator<? super E> c = backingMap.comparator(); if (c == null) { ((net.sourceforge.retroweaver.harmony.runtime.java.lang.Comparable<E>) start) .compareTo(start); } else { c.compare(start, start); } return new TreeSet<E>(backingMap.tailMap(start, startInclusive)); }
@Override public Action effectuer(Humain h) { if (nextAction != null) h.getEsprit().getActions().push(nextAction); Action a; if (comp.compare((double) (h.getAttr().get(attribute)), d)) { a = listeActions.get(0).effectuer(h); } else { a = listeActions.get(1).effectuer(h); } return a; }
@Test public void testReverseOrderRandomIntegers() { Comparator<Integer> naturalOrder = new NaturalOrder<Integer>(); Comparator<Integer> reverse = CollectionUtil.reverseOrder(naturalOrder); Random random = new Random(243249878l); // Stable "random" sequence for (int i = 0; i < 65536; i++) { // Verified to be ~ 50/50 lt/gt int integer = random.nextInt(); int integerToo = random.nextInt(); assertEquals(0, reverse.compare(integer, integer)); assertEquals(0, reverse.compare(integerToo, integerToo)); int natural = naturalOrder.compare(integer, integerToo); if (natural == 0) { // Actually never hits, but eq case is tested above assertEquals(0, reverse.compare(integer, integerToo)); } else if (natural < 0) { assertTrue(reverse.compare(integer, integerToo) > 0); } else { assertTrue(reverse.compare(integer, integerToo) < 0); } } }
/** * Private method that moves an element down the FourHeap if it is greater that the value of any * of its children. Modifies FourHeap structure. Takes an index to be filled by percolating. */ private void percolateDown(int index) { // children = (4*index) + 1, (4*index) +2, (4*index) +3, (4*index) +4 boolean done = false; while (!done) { int i = (index * 4) + 1; int min = index; while (i <= size - 1 && i <= (index * 4) + 4) { if (comparator.compare(arrayHeap[i], arrayHeap[min]) < 0) { min = i; } i++; } if (comparator.compare(arrayHeap[index], arrayHeap[min]) > 0) { E minimumValue = arrayHeap[min]; arrayHeap[min] = arrayHeap[index]; arrayHeap[index] = minimumValue; index = min; } else { done = true; } } }
/** * {@inheritDoc} * * @see java.util.NavigableSet#subSet(Object, boolean, Object, boolean) * @since 1.6 */ @SuppressWarnings("unchecked") public NavigableSet<E> subSet(E start, boolean startInclusive, E end, boolean endInclusive) { Comparator<? super E> c = backingMap.comparator(); int compare = (c == null) ? ((net.sourceforge.retroweaver.harmony.runtime.java.lang.Comparable<E>) start) .compareTo(end) : c.compare(start, end); if (compare <= 0) { return new TreeSet<E>(backingMap.subMap(start, startInclusive, end, endInclusive)); } throw new IllegalArgumentException(); }
/** * Remove test cases from the list of test-cases. This allows only certain test cases to be run in * a test suite. The comparator defines which test case is to be removed. * * @param testCases * @param testCaseIds * @param comparator */ private static void removeTestCaseDescriptors( List<ITestCaseDescriptor> testCases, Collection<String> testCaseIds, Comparator comparator) { final Iterator<ITestCaseDescriptor> iterator = testCases.iterator(); while (iterator.hasNext()) { final ITestCaseDescriptor testCase = iterator.next(); final String currentTestCaseId = testCase.getId(); if (comparator.compare(currentTestCaseId, testCaseIds) == 0) { logger.info(String.format("Removing test case with ID [%s]", testCase.getId())); iterator.remove(); } } }
private void add(BinaryTreeNodeImpl<E> node, BinaryTreeNodeImpl<E> subroot) { if (c.compare(node.getData(), subroot.getData()) == 0) { return; // element found; no duplicate added } if (c.compare(node.getData(), subroot.getData()) < 0) { if (subroot.getLeft() == null) { subroot.setLeft(node); node.setParent(subroot); return; } else { add(node, (BinaryTreeNodeImpl<E>) subroot.getLeft()); } } else { if (subroot.getRight() == null) { subroot.setRight(node); node.setParent(subroot); return; } else { add(node, (BinaryTreeNodeImpl<E>) subroot.getRight()); } } }
private static <C> void assertListsEqual( List<C> expectedList, List<C> actualList, Comparator<C> comparator, String name) { List<C> notFoundExpected = new ArrayList<C>(); List<C> notFoundActual = new ArrayList<C>(); for (C expected : expectedList) { boolean found = false; for (C actual : actualList) { if (comparator.compare(actual, expected) == 0) { found = true; break; } } if (!found) { notFoundExpected.add(expected); } } for (C actual : actualList) { boolean found = false; for (C expected : expectedList) { if (comparator.compare(actual, expected) == 0) { found = true; break; } } if (!found) { notFoundActual.add(actual); } } if (!notFoundExpected.isEmpty()) { fail("Not found expected " + name + " " + Arrays.toString(notFoundExpected.toArray())); } if (!notFoundActual.isEmpty()) { fail("Not expected " + name + " " + Arrays.toString(notFoundActual.toArray())); } }
@Override public void after(@NotNull final List<? extends VFileEvent> events) { incModificationCount(); for (FilePointerPartNode node : myPointersToUpdateUrl) { synchronized (this) { VirtualFilePointerImpl pointer = node.leaf; String urlBefore = pointer.getUrlNoUpdate(); Pair<VirtualFile, String> after = node.update(); String urlAfter = after.second; if (URL_COMPARATOR.compare(urlBefore, urlAfter) != 0) { // url has changed, reinsert FilePointerPartNode root = myPointers.get(pointer.getListener()); int useCount = node.useCount; node.remove(); FilePointerPartNode newNode = root.findPointerOrCreate(VfsUtilCore.urlToPath(urlAfter), 0, after); VirtualFilePointerImpl existingPointer = newNode.leaf; if (existingPointer != null) { // can happen when e.g. file renamed to the existing file // merge two pointers pointer.myNode = newNode; } else { newNode.associate(pointer, after); } newNode.incrementUsageCount(useCount); } } } VirtualFilePointer[] pointersToFireArray = toPointers(myPointersToFire); for (VirtualFilePointer pointer : pointersToFireArray) { ((VirtualFilePointerImpl) pointer).myNode.update(); } for (EventDescriptor event : myEvents) { event.fireAfter(); } if (pointersToFireArray.length != 0) { myBus.syncPublisher(VirtualFilePointerListener.TOPIC).validityChanged(pointersToFireArray); } myPointersToUpdateUrl = Collections.emptyList(); myEvents = Collections.emptyList(); myPointersToFire = Collections.emptyList(); for (FilePointerPartNode root : myPointers.values()) { root.checkConsistency(); } }
/** * Private method that moves an element up the FourHeap if it is less that the value of its * parent. Modifies FourHeap structure. Takes an index to be filled by percolating. */ private void percolateUp(int index) { boolean done = false; while (!done && index > 0) { int parent = (int) Math.floor((index - 1) / 4); if (comparator.compare(arrayHeap[index], arrayHeap[parent]) < 0) { E temp = arrayHeap[index]; arrayHeap[index] = arrayHeap[parent]; arrayHeap[parent] = temp; index = parent; } else { done = true; } } }
/** Assigns fitness for all the solutions. */ public void fitnessAssign() { double[] strength = new double[solutionSet_.size()]; double[] rawFitness = new double[solutionSet_.size()]; double kDistance; // Calculate the strength value // strength(i) = |{j | j <- SolutionSet and i dominate j}| for (int i = 0; i < solutionSet_.size(); i++) { for (int j = 0; j < solutionSet_.size(); j++) { if (dominance_.compare(solutionSet_.get(i), solutionSet_.get(j)) == -1) { strength[i] += 1.0; } // if } // for } // for // Calculate the raw fitness // rawFitness(i) = |{sum strenght(j) | j <- SolutionSet and j dominate i}| for (int i = 0; i < solutionSet_.size(); i++) { for (int j = 0; j < solutionSet_.size(); j++) { if (dominance_.compare(solutionSet_.get(i), solutionSet_.get(j)) == 1) { rawFitness[i] += strength[j]; } // if } // for } // for // Add the distance to the k-th individual. In the reference paper of SPEA2, // k = sqrt(population.size()), but a value of k = 1 recommended. See // http://www.tik.ee.ethz.ch/pisa/selectors/spea2/spea2_documentation.txt int k = 1; for (int i = 0; i < distance.length; i++) { Arrays.sort(distance[i]); kDistance = 1.0 / (distance[i][k] + 2.0); // Calcule de D(i) distance // population.get(i).setFitness(rawFitness[i]); solutionSet_.get(i).setFitness(rawFitness[i] + kDistance); } // for } // fitnessAsign
public <S extends Solution<?>> S findWorstSolution( Collection<S> solutionList, Comparator<S> comparator) { if ((solutionList == null) || (solutionList.isEmpty())) { throw new IllegalArgumentException("No solution provided: " + solutionList); } S worstKnown = solutionList.iterator().next(); for (S candidateSolution : solutionList) { if (comparator.compare(worstKnown, candidateSolution) < 0) { worstKnown = candidateSolution; } } return worstKnown; }
public static <S extends Solution<?>> boolean isSolutionDominatedBySolutionList( S solution, List<? extends S> solutionSet) { boolean result = false; Comparator<S> dominance = new DominanceComparator<S>(); int i = 0; while (!result && (i < solutionSet.size())) { if (dominance.compare(solution, solutionSet.get(i)) == 1) { result = true; } i++; } return result; }