Example usage for java.util Arrays binarySearch

List of usage examples for java.util Arrays binarySearch

Introduction

In this page you can find the example usage for java.util Arrays binarySearch.

Prototype

public static int binarySearch(Object[] a, Object key) 

Source Link

Document

Searches the specified array for the specified object using the binary search algorithm.

Usage

From source file:fi.smaa.libror.UTAGMSSolver.java

private int getConstraintIndex(int critIndex, int altIndex) {
    if (critIndex < 0 || altIndex < 0) {
        throw new IllegalArgumentException("PRECOND violation");
    }/*from ww  w .j a  v  a  2s  .  c o m*/

    int offset = getConstraintOffset(critIndex);
    int index = Arrays.binarySearch(model.getPerfMatrix().getLevels()[critIndex].getData(),
            model.getPerfMatrix().getMatrix().getEntry(altIndex, critIndex));
    assert (index >= 0); // sanity check

    return offset + index;
}

From source file:com.opengamma.analytics.financial.credit.creditdefaultswap.pricing.vanilla.isdanew.ISDACompliantCurve.java

/**
 * Get the zero rate multiplied by time - this is the same as the negative log of the discount factor
 * @param t  Time/*from  w  w  w  .  j  av a  2  s .c  o m*/
 * @return value
 */
public double getRT(final double t) {
    ArgumentChecker.isTrue(t >= 0, "require t >= 0.0");

    // short-cut doing binary search
    if (t <= _t[0]) {
        return _r[0] * t;
    }
    if (t > _t[_n - 1]) {
        return getRT(t, _n - 1); //linear extrapolation 
    }

    final int index = Arrays.binarySearch(_t, t);
    if (index >= 0) {
        return _rt[index] + _offsetRT;
    }

    final int insertionPoint = -(1 + index);
    return getRT(t, insertionPoint);
}

From source file:com.epam.reportportal.apache.http.conn.ssl.AbstractVerifier.java

/**
 * @deprecated (4.3.1) should not be a part of public APIs.
 *//*  ww w .  j  a  va2  s.  c  o m*/
@Deprecated
public static boolean acceptableCountryWildcard(final String cn) {
    final String parts[] = cn.split("\\.");
    if (parts.length != 3 || parts[2].length() != 2) {
        return true; // it's not an attempt to wildcard a 2TLD within a country code
    }
    return Arrays.binarySearch(BAD_COUNTRY_2LDS, parts[1]) < 0;
}

From source file:com.opengamma.financial.analytics.timeseries.YieldCurveConversionSeriesFunction.java

@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context,
        final ComputationTarget target, final ValueRequirement desiredValue) {
    ValueProperties.Builder constraints = null;
    if (_excludedCurves.length != 0) {
        final Set<String> curveNames = desiredValue.getConstraints().getValues(ValuePropertyNames.CURVE);
        if (curveNames != null && curveNames.size() == 1) {
            final String curveName = Iterables.getOnlyElement(curveNames);
            final int index = Arrays.binarySearch(_excludedCurves, curveName);
            if (index >= 0) {
                return null;
            }//from   w  w  w.ja v  a 2s  .  c  om
        }
    }
    Set<String> values = desiredValue.getConstraints()
            .getValues(HistoricalTimeSeriesFunctionUtils.DATA_FIELD_PROPERTY);
    if ((values == null) || values.isEmpty()) {
        constraints = desiredValue.getConstraints().copy().with(
                HistoricalTimeSeriesFunctionUtils.DATA_FIELD_PROPERTY, MarketDataRequirementNames.MARKET_VALUE);
    } else if (values.size() > 1) {
        constraints = desiredValue.getConstraints().copy()
                .withoutAny(HistoricalTimeSeriesFunctionUtils.DATA_FIELD_PROPERTY)
                .with(HistoricalTimeSeriesFunctionUtils.DATA_FIELD_PROPERTY, values.iterator().next());
    }
    values = desiredValue.getConstraints().getValues(HistoricalTimeSeriesFunctionUtils.RESOLUTION_KEY_PROPERTY);
    if ((values == null) || values.isEmpty()) {
        if (constraints == null) {
            constraints = desiredValue.getConstraints().copy();
        }
        constraints.with(HistoricalTimeSeriesFunctionUtils.RESOLUTION_KEY_PROPERTY, "");
    } else if (values.size() > 1) {
        if (constraints == null) {
            constraints = desiredValue.getConstraints().copy();
        }
        constraints.withoutAny(HistoricalTimeSeriesFunctionUtils.RESOLUTION_KEY_PROPERTY)
                .with(HistoricalTimeSeriesFunctionUtils.RESOLUTION_KEY_PROPERTY, values.iterator().next());
    }
    values = desiredValue.getConstraints().getValues(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY);
    if ((values == null) || values.isEmpty()) {
        if (constraints == null) {
            constraints = desiredValue.getConstraints().copy();
        }
        constraints.with(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY, "Null");
    }
    values = desiredValue.getConstraints().getValues(HistoricalTimeSeriesFunctionUtils.INCLUDE_START_PROPERTY);
    if ((values == null) || (values.size() != 1)) {
        if (constraints == null) {
            constraints = desiredValue.getConstraints().copy();
        }
        constraints.with(HistoricalTimeSeriesFunctionUtils.INCLUDE_START_PROPERTY,
                HistoricalTimeSeriesFunctionUtils.YES_VALUE);
    }
    values = desiredValue.getConstraints().getValues(HistoricalTimeSeriesFunctionUtils.END_DATE_PROPERTY);
    if ((values == null) || values.isEmpty()) {
        if (constraints == null) {
            constraints = desiredValue.getConstraints().copy();
        }
        constraints.with(HistoricalTimeSeriesFunctionUtils.END_DATE_PROPERTY, "Now");
    }
    values = desiredValue.getConstraints().getValues(HistoricalTimeSeriesFunctionUtils.INCLUDE_END_PROPERTY);
    if ((values == null) || (values.size() != 1)) {
        if (constraints == null) {
            constraints = desiredValue.getConstraints().copy();
        }
        constraints.with(HistoricalTimeSeriesFunctionUtils.INCLUDE_END_PROPERTY,
                HistoricalTimeSeriesFunctionUtils.YES_VALUE);
    }
    if (constraints == null) {
        // We can satisfy the desired value as-is, just ask for the yield curve specification to drive our behavior
        final ValueProperties curveConstraints;
        values = desiredValue.getConstraints().getValues(ValuePropertyNames.CURVE);
        if (values != null) {
            if (values.isEmpty()) {
                curveConstraints = ValueProperties.withAny(ValuePropertyNames.CURVE).get();
            } else {
                curveConstraints = ValueProperties.with(ValuePropertyNames.CURVE, values).get();
            }
        } else {
            curveConstraints = ValueProperties.none();
        }
        return Collections.singleton(new ValueRequirement(ValueRequirementNames.YIELD_CURVE_SPEC,
                target.toSpecification(), curveConstraints));
    }
    // We need to substitute ourselves with the adjusted constraints
    return Collections
            .singleton(new ValueRequirement(ValueRequirementNames.YIELD_CURVE_CONVERSION_HISTORICAL_TIME_SERIES,
                    target.toSpecification(), constraints.get()));
}

From source file:jsat.distributions.empirical.MyKernelDensityEstimator.java

@Override
public double cdf(double x) {
    // Only values within a certain range will have an effect on the result, so we will skip to that range!
    int from = Arrays.binarySearch(X, x - h * k.cutOff());
    int to = Arrays.binarySearch(X, x + h * k.cutOff());
    // Mostly likely the exact value of x is not in the list, so it returns the inseration points
    from = from < 0 ? -from - 1 : from;
    to = to < 0 ? -to - 1 : to;/*from   w  ww.  j  a  va  2s .  c  o  m*/

    double sum = 0;

    for (int i = Math.max(0, from); i < Math.min(X.length, to + 1); i++) {
        sum += k.intK((x - X[i]) / h) * getWeight(i);
    }

    /*
     * Slightly different, all things below the from value for the cdf would be adding 1 to the value, as the value of x would be the integration over the
     * entire range, which by definition, is equal to 1.
     */
    // We perform the addition after the summation to reduce the difference size
    if (weights.length == 0) {
        sum += Math.max(0, from);
    } else {
        sum += weights[from];
    }

    return sum / (X.length);
}

From source file:org.jtheque.movies.services.MoviesServiceTest.java

License:asdf

@Test
public void getMoviesWithInvalidFiles() {
    Movie movie1 = moviesService.getMovie("Movie 1");
    Movie movie2 = moviesService.getMovie("Movie 2");

    movie1.setFile(FileUtils.getAnExistingFile().getAbsolutePath());
    movie2.setFile(FileUtils.getAnExistingFile().getAbsolutePath());

    Collection<? extends Movie> movies = moviesService.getMoviesWithInvalidFiles();
    String[] titles = { "Movie 3", "Movie 4", "Movie 5" };

    assertEquals(3, movies.size());//from   w ww  .  j av  a 2  s  . c  om

    for (Movie m : movies) {
        if (Arrays.binarySearch(titles, m.getTitle()) == -1) {
            fail("The returned movies are not the good");
        }
    }

    moviesService.getMovie("Movie 1").setFile(null);

    movies = moviesService.getMoviesWithInvalidFiles();

    assertEquals(4, movies.size());
}

From source file:com.indeed.lsmtree.core.TestImmutableBTreeIndex.java

public void testSeekPrevious() throws Exception {
    final int[] ints = createTree();
    final ImmutableBTreeIndex.Reader<Integer, Long> reader = new ImmutableBTreeIndex.Reader(tmpDir,
            new IntSerializer(), new LongSerializer(), false);
    final int max = ints[ints.length - 1];
    final AtomicInteger done = new AtomicInteger(8);
    for (int i = 0; i < 8; i++) {
        final int index = i;
        new Thread(new Runnable() {
            @Override/* w  ww.  j a  v  a  2s  .  co  m*/
            public void run() {
                try {
                    final Random r = new Random(index);
                    for (int i = 0; i < treeSize; i++) {
                        int rand = r.nextInt(max + 10);
                        int insertionindex = Arrays.binarySearch(ints, rand);
                        final Iterator<Generation.Entry<Integer, Long>> iterator = reader.reverseIterator(rand,
                                true);
                        final boolean hasPrevious = iterator.hasNext();
                        Generation.Entry<Integer, Long> entry = null;
                        assertEquals(
                                "rand: " + rand + " hasPrevious: " + hasPrevious
                                        + (hasPrevious ? " previous: " + (entry = iterator.next()) : ""),
                                hasPrevious, insertionindex != -1);
                        if (hasPrevious) {
                            if (entry == null)
                                entry = iterator.next();
                            assertTrue(entry.getKey() <= rand);
                            assertTrue(entry.getKey().longValue() == entry.getValue());
                        }
                        if (insertionindex >= 0) {
                            if (entry == null)
                                entry = iterator.next();
                            assertTrue(rand == ints[insertionindex]);
                            assertTrue(entry.getKey() == rand);
                            Generation.Entry<Integer, Long> result = reader.get(rand);
                            assertTrue(result.getValue() == rand);
                        } else {
                            if (hasPrevious) {
                                assertTrue(ints[(~insertionindex) - 1] < rand);
                                assertTrue(ints[(~insertionindex) - 1] == entry.getKey());
                            }
                            Generation.Entry<Integer, Long> result = reader.get(rand);
                            assertTrue(result == null);
                        }
                    }
                } finally {
                    done.decrementAndGet();
                }
            }
        }).start();
    }
    while (done.get() > 0) {
        Thread.yield();
    }
    reader.close();
}

From source file:com.saucelabs.sauce_ondemand.driver.SauceOnDemandSPIImpl.java

private void populateProfilePreferences(FirefoxProfile profile, Map<String, List<String>> paramMap) {
    for (Map.Entry<String, List<String>> mapEntry : paramMap.entrySet()) {
        String key = mapEntry.getKey();
        if (Arrays.binarySearch(NON_PROFILE_PARAMETERS, key) == -1) {
            //add it to the profile
            profile.setPreference(key, getFirstParameter(paramMap, key));
        }//from w  w  w  . ja va2s.co  m
    }
}

From source file:com.linkedin.pinot.core.segment.index.readers.ImmutableDictionaryReaderTest.java

@Test
public void testFloatDictionary() throws Exception {
    try (FloatDictionary floatDictionary = new FloatDictionary(
            PinotDataBuffer.fromFile(new File(TEMP_DIR, FLOAT_COLUMN_NAME + V1Constants.Dict.FILE_EXTENSION),
                    ReadMode.mmap, FileChannel.MapMode.READ_ONLY, FLOAT_COLUMN_NAME),
            NUM_VALUES)) {/*from  w ww. ja v a2  s. c  o m*/
        for (int i = 0; i < NUM_VALUES; i++) {
            Assert.assertEquals(floatDictionary.get(i), _floatValues[i], 0.0f);
            Assert.assertEquals(floatDictionary.getIntValue(i), (int) _floatValues[i]);
            Assert.assertEquals(floatDictionary.getLongValue(i), (long) _floatValues[i]);
            Assert.assertEquals(floatDictionary.getFloatValue(i), _floatValues[i], 0.0f);
            Assert.assertEquals(floatDictionary.getDoubleValue(i), _floatValues[i], 0.0);
            Assert.assertEquals(Float.parseFloat(floatDictionary.getStringValue(i)), _floatValues[i], 0.0f);

            Assert.assertEquals(floatDictionary.indexOf(_floatValues[i]), i);

            float randomFloat = RANDOM.nextFloat();
            Assert.assertEquals(floatDictionary.insertionIndexOf(randomFloat),
                    Arrays.binarySearch(_floatValues, randomFloat));
        }
    }
}

From source file:CharMap.java

/**
 * Removes the mapping for a key from this map if it is present and returns
 * the value to which this map previously associated the key, or {@code
 * null} if the map contained no mapping for the key.
 *
 * @param key key whose mapping is to be removed from the map 
 *
 * @return the previous value associated with key, or {@code null} if there
 * was no mapping for key./*from ww w . j  a va  2 s .  com*/
 */
@SuppressWarnings("unchecked")
public V remove(char key) {
    char k = key;
    int index = Arrays.binarySearch(keyIndices, k);

    if (index >= 0) {
        V old = (V) (values[index]);

        Object[] newValues = Arrays.copyOf(values, values.length - 1);
        char[] newIndices = Arrays.copyOf(keyIndices, keyIndices.length - 1);

        // shift the elements up to remove the values
        for (int i = index; i < values.length - 1; ++i) {
            newValues[i] = values[i + 1];
            newIndices[i] = keyIndices[i + 1];
        }

        // update the arrays with the shorted versions
        values = newValues;
        keyIndices = newIndices;
        return old;
    }

    return null;
}