/** * 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; }
@Test public void testNext() { boolean expected = true; EasyMock.expect(peekIterator.hasNext()).andReturn(expected).times(4); String defaultString = "S1"; String resString = "S2"; EasyMock.expect(peekIterator.next()).andReturn(defaultString); EasyMock.expect(binaryFn.apply(EasyMock.eq(defaultString), EasyMock.isNull())) .andReturn(resString); EasyMock.expect(peekIterator.next()).andReturn(defaultString); EasyMock.expect(comparator.compare(EasyMock.eq(resString), EasyMock.eq(defaultString))) .andReturn(0); EasyMock.expect(peekIterator.next()).andReturn(defaultString); EasyMock.expect(binaryFn.apply(EasyMock.eq(resString), EasyMock.eq(defaultString))) .andReturn(resString); EasyMock.expect(comparator.compare(EasyMock.eq(resString), EasyMock.eq(defaultString))) .andReturn(1); EasyMock.replay(peekIterator); EasyMock.replay(binaryFn); EasyMock.replay(comparator); String actual = testingIterator.next(); Assert.assertEquals(resString, actual); EasyMock.verify(peekIterator); EasyMock.verify(comparator); EasyMock.verify(binaryFn); }
protected static void assertLesser( Comparator<ExhaustiveSearchNode> comparator, ExhaustiveSearchNode a, ExhaustiveSearchNode b) { assertTrue( "Node (" + a + ") must be lesser than node (" + b + ").", comparator.compare(a, b) < 0); assertTrue( "Node (" + b + ") must be greater than node (" + a + ").", comparator.compare(b, a) > 0); }
public void testProcessReportsComparator() throws Exception { final Comparator<ProcessReports> comparator = new ProcessControl.ProcessReportsComparator(); final AgentIdentity agentIdentity1 = new StubAgentIdentity("my agent"); final AgentProcessReport agentProcessReport1 = new StubAgentProcessReport(agentIdentity1, AgentProcessReport.STATE_RUNNING); final RandomStubFactory<ProcessReports> processReportsStubFactory1 = RandomStubFactory.create(ProcessReports.class); final ProcessReports processReports1 = processReportsStubFactory1.getStub(); processReportsStubFactory1.setResult("getAgentProcessReport", agentProcessReport1); assertEquals(0, comparator.compare(processReports1, processReports1)); final AgentProcessReport agentProcessReport2 = new StubAgentProcessReport(agentIdentity1, AgentProcessReport.STATE_FINISHED); final RandomStubFactory<ProcessReports> processReportsStubFactory2 = RandomStubFactory.create(ProcessReports.class); final ProcessReports processReports2 = processReportsStubFactory2.getStub(); processReportsStubFactory2.setResult("getAgentProcessReport", agentProcessReport2); assertEquals(0, comparator.compare(processReports2, processReports2)); assertTrue(comparator.compare(processReports1, processReports2) < 0); assertTrue(comparator.compare(processReports2, processReports1) > 0); }
@Override protected int partition(Comparator<Object> c, int p, int r) { char[] x = keyTable[p]; Object temp = null; int i = p; int j = r; while (true) { while (c.compare(keyTable[j], x) > 0) { j--; } if (i < j) { while (c.compare(keyTable[i], x) < 0) { i++; } } if (i < j) { temp = keyTable[j]; keyTable[j] = keyTable[i]; keyTable[i] = (char[]) temp; temp = valueTable[j]; valueTable[j] = valueTable[i]; valueTable[i] = temp; } else { return j; } } }
/** * Compare two file lists for files which have been created, modified or deleted. * * @param parent The parent entry * @param previous The original list of files * @param files The current list of files */ private void checkAndNotify(FileEntry parent, FileEntry[] previous, File[] files) { int c = 0; FileEntry[] current = files.length > 0 ? new FileEntry[files.length] : FileEntry.EMPTY_ENTRIES; for (FileEntry entry : previous) { while (c < files.length && comparator.compare(entry.getFile(), files[c]) > 0) { current[c] = createFileEntry(parent, files[c]); doCreate(current[c]); c++; } if (c < files.length && comparator.compare(entry.getFile(), files[c]) == 0) { doMatch(entry, files[c]); checkAndNotify(entry, entry.getChildren(), listFiles(files[c])); current[c] = entry; c++; } else { checkAndNotify(entry, entry.getChildren(), FileUtils.EMPTY_FILE_ARRAY); doDelete(entry); } } for (; c < files.length; c++) { current[c] = createFileEntry(parent, files[c]); doCreate(current[c]); } parent.setChildren(current); }
void sort(int from, int to, Comparator<T> cmp) { int width = to - from; if (to - from <= 15) selectionSort(from, to, cmp); else { T pivot = myarray[rand.nextInt(width) + from]; T tmp; int i = from - 1; int j = to; for (; ; ) { do i++; while (cmp.compare(myarray[i], pivot) < 0); do j--; while (cmp.compare(pivot, myarray[j]) < 0); if (i >= j) break; tmp = myarray[i]; myarray[i] = myarray[j]; myarray[j] = tmp; } sort(from, i, cmp); sort(i, to, cmp); } }
@Test public void testUnsignedComparatorMRef() { Comparator<Integer> cmp = Integer::compareUnsigned; assertEquals(0, cmp.compare(0, 0)); assertEquals(1, cmp.compare(-100, 100)); assertEquals(-1, cmp.compare(100, -100)); }
private GeneralRange( Comparator<? super T> comparator, boolean hasLowerBound, @Nullable T lowerEndpoint, BoundType lowerBoundType, boolean hasUpperBound, @Nullable T upperEndpoint, BoundType upperBoundType) { this.comparator = checkNotNull(comparator); this.hasLowerBound = hasLowerBound; this.hasUpperBound = hasUpperBound; this.lowerEndpoint = lowerEndpoint; this.lowerBoundType = checkNotNull(lowerBoundType); this.upperEndpoint = upperEndpoint; this.upperBoundType = checkNotNull(upperBoundType); if (hasLowerBound) { comparator.compare(lowerEndpoint, lowerEndpoint); } if (hasUpperBound) { comparator.compare(upperEndpoint, upperEndpoint); } if (hasLowerBound && hasUpperBound) { int cmp = comparator.compare(lowerEndpoint, upperEndpoint); // be consistent with Range checkArgument( cmp <= 0, "lowerEndpoint (%s) > upperEndpoint (%s)", lowerEndpoint, upperEndpoint); if (cmp == 0) { checkArgument(lowerBoundType != OPEN | upperBoundType != OPEN); } } }
@Test public void testCustomMatcher() { Comparator mock = mock(Comparator.class); mock.compare("Hello", "World"); mock.compare("Foo", "Bar"); mock.compare("Foo", null); BasicMatcher<Object> myFooBarMatcher = new BasicMatcher<Object>() { @Override public boolean matches(Object value) { return "Foo".equals(value) || "Bar".equals(value); } @Override public Class<Object> getType() { return Object.class; } @Override protected String asString() { return "(Foo or Bar)"; } }; verifyOnce().on(mock).compare(match(myFooBarMatcher), match(myFooBarMatcher)); }
/** * Sort a range in the array * * @param <T> The data type of the array * @param S The array * @param start The index of the first element in the range to sort * @param end Unused, instead start + 3 is always the last element in the range. * @return The array */ @Override public <T> T[] sort(T[] S, int start, int end, Comparator<T> comparator) { if (comparator == null) comparator = naturalOrderingComparator; int i0 = start; int i1 = start + 1; int i2 = start + 2; int i3 = start + 3; if (comparator.compare(S[i0], S[i1]) > i0) { permutator.swap(S, i0, i1); } if (comparator.compare(S[i2], S[i3]) > i0) { permutator.swap(S, i2, i3); } if (comparator.compare(S[i1], S[i3]) > i0) { // This establishes the maximum into S[i3] permutator.swap(S, i1, i3); } if (comparator.compare(S[i0], S[i2]) > i0) { // This establishes the minimum into S[i0] permutator.swap(S, i0, i2); } if (comparator.compare(S[i1], S[i2]) > i0) { // This sorts the remaining two elements permutator.swap(S, i1, i2); } return S; }
/** {@inheritDoc} */ @Override protected void iterateSimplex(final Comparator<RealPointValuePair> comparator) throws FunctionEvaluationException, OptimizationException, IllegalArgumentException { while (true) { incrementIterationsCounter(); // save the original vertex final RealPointValuePair[] original = simplex; final RealPointValuePair best = original[0]; // perform a reflection step final RealPointValuePair reflected = evaluateNewSimplex(original, 1.0, comparator); if (comparator.compare(reflected, best) < 0) { // compute the expanded simplex final RealPointValuePair[] reflectedSimplex = simplex; final RealPointValuePair expanded = evaluateNewSimplex(original, khi, comparator); if (comparator.compare(reflected, expanded) <= 0) { // accept the reflected simplex simplex = reflectedSimplex; } return; } // compute the contracted simplex final RealPointValuePair contracted = evaluateNewSimplex(original, gamma, comparator); if (comparator.compare(contracted, best) < 0) { // accept the contracted simplex return; } } }
/** * Return a Comparator that will order the specified units in preferred unload order. If needed it * may also inspect the transport holding the units. */ public static Comparator<Unit> getUnloadableUnitsComparator( final List<Unit> units, final Route route, final PlayerID player) { // compare transports final Comparator<Unit> unloadableTransportsComparator = getUnloadableTransportsComparator(units, route, player, false); // if noTies is set, sort by hashcode so that result is deterministic final Comparator<Unit> movableUnitsComparator = getMovableUnitsComparator(units, route); return (u1, u2) -> { final Unit t1 = TripleAUnit.get(u1).getTransportedBy(); final Unit t2 = TripleAUnit.get(u2).getTransportedBy(); // check if unloadable units are in a transport if (t1 != null && t2 == null) { return -1; } if (t1 == null && t2 != null) { return 1; } if (t1 != null && t2 != null) { final int compareTransports = unloadableTransportsComparator.compare(t1, t2); if (compareTransports != 0) { return compareTransports; } } // we are sorting air units, or no difference found yet // if noTies is set, sort by hashcode so that result is deterministic return movableUnitsComparator.compare(u1, u2); }; }
public static <T1, T2, T3, T4> Comparator<Tuple4<T1, T2, T3, T4>> comparator( Comparator<? super T1> t1Comp, Comparator<? super T2> t2Comp, Comparator<? super T3> t3Comp, Comparator<? super T4> t4Comp) { return (Comparator<Tuple4<T1, T2, T3, T4>> & Serializable) (t1, t2) -> { final int check1 = t1Comp.compare(t1._1, t2._1); if (check1 != 0) { return check1; } final int check2 = t2Comp.compare(t1._2, t2._2); if (check2 != 0) { return check2; } final int check3 = t3Comp.compare(t1._3, t2._3); if (check3 != 0) { return check3; } final int check4 = t4Comp.compare(t1._4, t2._4); if (check4 != 0) { return check4; } // all components are equal return 0; }; }
private void sortTail() { // size > limit here T[] d = data; int l = limit, s = size; Comparator<? super T> cmp = comparator; Arrays.sort(d, l, s, cmp); if (cmp.compare(d[s - 1], d[0]) < 0) { // Common case: descending sequence // Assume size - limit <= limit here System.arraycopy(d, 0, d, s - l, 2 * l - s); System.arraycopy(d, l, d, 0, s - l); } else { // Merge presorted 0..limit-1 and limit..size-1 @SuppressWarnings("unchecked") T[] buf = (T[]) new Object[l]; int i = 0, j = l, k = 0; // d[l-1] is guaranteed to be the worst element, thus no need to // check it while (i < l - 1 && k < l && j < s) { if (cmp.compare(d[i], d[j]) <= 0) { buf[k++] = d[i++]; } else { buf[k++] = d[j++]; } } if (k < l) { System.arraycopy(d, i < l - 1 ? i : j, d, k, l - k); } System.arraycopy(buf, 0, d, 0, k); } size = l; }
@Test public void testUnsignedComparator() { Comparator<Integer> cmp = (x, y) -> Integer.compareUnsigned(x, y); assertEquals(0, cmp.compare(0, 0)); assertEquals(1, cmp.compare(-100, 100)); assertEquals(-1, cmp.compare(100, -100)); }
@Override public SortedMap<K, V> subMap(K fromKey, K toKey) { Comparator<K> comparator = naturalComparator(); return ((comparator.compare(this.entry.getKey(), toKey) < 0) && (comparator.compare(this.entry.getKey(), fromKey) >= 0)) ? this : Collections.<K, V>emptySortedMap(); }
@Test public void testNotMatcher() { Comparator mock = mock(Comparator.class); mock.compare("Hello", "World"); mock.compare("Foo", "Bar"); mock.compare("Foo", null); verifyOnce().on(mock).compare(not(mType(List.class)), "World"); }
private void assertComparators( Player p1, Player p2, Comparator<Player> desc, Comparator<Player> asc) { Assert.assertTrue(desc.compare(p1, p2) > 0); Assert.assertTrue(desc.compare(p2, p1) < 0); Assert.assertTrue(desc.compare(p1, p1) == 0); Assert.assertTrue(asc.compare(p1, p2) < 0); Assert.assertTrue(asc.compare(p2, p1) > 0); Assert.assertTrue(asc.compare(p1, p1) == 0); }
/** Execute() method */ public Object execute(Object object) throws JMetalException { if (null == object) { throw new JMetalException("Null parameter"); } else if (!(object instanceof Solution)) { throw new JMetalException("Invalid parameter class"); } int i = 0; int best = 0; evaluations = 0; Solution solution = (Solution) object; int rounds = improvementRounds; if (rounds <= 0) { return new Solution(solution); } do { i++; Solution mutatedSolution = new Solution(solution); mutationOperator.execute(mutatedSolution); // Evaluate the getNumberOfConstraints if (problem.getNumberOfConstraints() > 0) { problem.evaluateConstraints(mutatedSolution); best = constraintComparator.compare(mutatedSolution, solution); if (best == 0) { // none of then is better that the other one problem.evaluate(mutatedSolution); evaluations++; best = dominanceComparator.compare(mutatedSolution, solution); } else if (best == -1) { // mutatedSolution is best problem.evaluate(mutatedSolution); evaluations++; } } else { problem.evaluate(mutatedSolution); evaluations++; best = dominanceComparator.compare(mutatedSolution, solution); } if (best == -1) { // mutated is best solution = mutatedSolution; } else if (best == 1) { // original is best } else { // mutatedSolution and original are non-dominated if (archive != null) { archive.add(mutatedSolution); } } } while (i < rounds); return new Solution(solution); }
@Override public SortedSet<E> subSet(E fromElement, E toElement) { Comparator<E> comparator = naturalComparator(); return ((comparator.compare(this.element, toElement) < 0) && (comparator.compare(this.element, fromElement) >= 0)) ? this : Collections.<E>emptySortedSet(); }
@Override public int compareTo(Path o) { if (TagGenerator.SCORE_BY_LENGTH) { return LENGTH_FIRST_COMPARATOR.compare(this, o); } if (Math.abs(score - o.score) > SCORE_EPS) { return score > o.score ? -1 : 1; } return LENGTH_FIRST_COMPARATOR.compare(this, o); }
/** * Routine which can be used instead of the one taking an interval, for the situation where the * endpoints are being retrieved from different data structures */ public boolean overlaps( Object otherLowEndpoint, Object otherHighEndpoint, Comparator endpointComparator) { if (endpointComparator.compare(highEndpoint, otherLowEndpoint) <= 0) { return false; } if (endpointComparator.compare(lowEndpoint, otherHighEndpoint) >= 0) { return false; } return true; }
@Override public int compare(Literal l1, Literal l2) { if (l1 == l2) return 0; int c = l1.name.compareTo(l2.name); if (c != 0) return c; if (l1.isNegation != l2.isNegation) return l1.isNegation ? Integer.MAX_VALUE : Integer.MIN_VALUE; // same name, negation sign // check mode and temporal c = l1.mode.compareTo(l2.mode); if (c != 0) return c; if (isCheckTemporal) { c = null == temporalComparator ? DEFAULT_TEMPORAL_COMPARTOR.compare(l1.temporal, l2.temporal) : temporalComparator.compare(l1.temporal, l2.temporal); // System.out.println("literalComparator.checkTemporal:("+l1+","+l2+")="+c); if (c != 0) return c; // if (null == l1.temporal) { // if (null != l2.temporal) { // Temporal t2=l2.temporal; // if (Long.MIN_VALUE == t2.startTime) return Long.MAX_VALUE==t2.endTime?0 :Integer.MAX_VALUE; // return Integer.MIN_VALUE; // } // } else { // Temporal t1=l1.temporal; // if (null == l2.temporal) { // if (Long.MIN_VALUE == t1.startTime) return Long.MAX_VALUE==t1.endTime?0: Integer.MIN_VALUE; // return Integer.MAX_VALUE; // } else { // Temporal t2 = l2.temporal; // c = null == temporalComparator ? t1.compareTo(t2) : temporalComparator.compare(t1, t2); // if (c != 0) return c; // } // } } c = l1.predicates.length - l2.predicates.length; if (c != 0) return c; for (int i = 0; i < l1.predicates.length; i++) { if (!l1.isPredicateGrounded(i) && !l2.isPredicateGrounded(i)) { } else if (l1.isPredicateGrounded(i) && l2.isPredicateGrounded(i)) { c = l1.predicates[i].compareTo(l2.predicates[i]); if (c != 0) return c; } else { return l1.isPredicateGrounded(i) ? Integer.MAX_VALUE : Integer.MIN_VALUE; } } return 0; }
@Test public void stubThrowingAnException() { asError.expect(IllegalArgumentException.class); Comparator<String> comparator = mock(Comparator.class); when(comparator.compare(any(String.class), any(String.class))) .thenThrow(new IllegalArgumentException()); comparator.compare("a", "b"); }
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; }
@Test public void testOnlyOneNull() { ProductDimension dimension = createOtherProductDimension(); assertThat( "Null should be greater than non-null", comparator.compare(null, dimension), Matchers.greaterThan(0)); assertThat( "Non-null should be less than null", comparator.compare(dimension, null), Matchers.lessThan(0)); }
public void testCompareSingleProperty() { comparator = new MultiKeyComparator(new boolean[] {false}); firstValues = new MultiKeyUntyped(new Object[] {3d}); secondValues = new MultiKeyUntyped(new Object[] {4d}); assertTrue(comparator.compare(firstValues, secondValues) < 0); comparator = new MultiKeyComparator(new boolean[] {true}); assertTrue(comparator.compare(firstValues, secondValues) > 0); assertTrue(comparator.compare(firstValues, firstValues) == 0); }
public void testCompareTwoProperties() { comparator = new MultiKeyComparator(new boolean[] {false, false}); firstValues = new MultiKeyUntyped(new Object[] {3d, 3L}); secondValues = new MultiKeyUntyped(new Object[] {3d, 4L}); assertTrue(comparator.compare(firstValues, secondValues) < 0); comparator = new MultiKeyComparator(new boolean[] {false, true}); assertTrue(comparator.compare(firstValues, secondValues) > 0); assertTrue(comparator.compare(firstValues, firstValues) == 0); }
public void testCompare_sameQuadrant() { final DoublesPair first = DoublesPair.of(0.0, 0.0); final DoublesPair second = DoublesPair.of(1.0, 0.0); final Comparator<DoublesPair> test = QuadrantDoublesPairComparator.INSTANCE; assertTrue(test.compare(first, first) == 0); assertTrue(test.compare(first, second) < 0); assertTrue(test.compare(second, first) > 0); assertTrue(test.compare(second, second) == 0); }