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:com.opengamma.analytics.math.surface.InterpolatedFromCurvesSurfaceAdditiveShiftFunction.java

/**
 * {@inheritDoc}//from w ww . j  a v a  2  s  .co m
 * @throws UnsupportedOperationException If the <i>x</i> (<i>y</i>) position of the shift does not coincide with one of the <i>x</i> (<i>y</i>) intersections 
 * of the curves with the axis
 */
@Override
public InterpolatedFromCurvesDoublesSurface evaluate(final InterpolatedFromCurvesDoublesSurface surface,
        final double x, final double y, final double shift, final String newName) {
    Validate.notNull(surface, "surface");
    final boolean xzCurves = surface.isXZCurves();
    final double[] points = surface.getPoints();
    if (xzCurves) {
        final int index = Arrays.binarySearch(points, y);
        final Curve<Double, Double>[] curves = surface.getCurves();
        if (index >= 0) {
            final Curve<Double, Double>[] newCurves = Arrays.copyOf(surface.getCurves(), points.length);
            newCurves[index] = CurveShiftFunctionFactory.getShiftedCurve(curves[index], x, shift);
            return InterpolatedFromCurvesDoublesSurface.fromSorted(xzCurves, points, newCurves,
                    surface.getInterpolator(), newName);
        }
        throw new UnsupportedOperationException(
                "Cannot get shift for y-value not in original list of curves: asked for " + y);
    }
    final int index = Arrays.binarySearch(points, x);
    final Curve<Double, Double>[] curves = surface.getCurves();
    if (index >= 0) {
        final Curve<Double, Double>[] newCurves = Arrays.copyOf(surface.getCurves(), points.length);
        newCurves[index] = CurveShiftFunctionFactory.getShiftedCurve(curves[index], y, shift);
        return InterpolatedFromCurvesDoublesSurface.fromSorted(xzCurves, points, newCurves,
                surface.getInterpolator(), newName);
    }
    throw new UnsupportedOperationException(
            "Cannot get shift for x-value not in original list of curves: asked for " + x);
}

From source file:de.uniba.wiai.kinf.pw.projects.lillytab.reasoner.abox.TermSet.java

@Override
public SortedSet<IDLTerm<I, L, K, R>> subSet(DLTermOrder termType) {
    final DLTermOrder[] values = DLTermOrder.values();
    final int typeIndex = Arrays.binarySearch(values, termType);
    assert (typeIndex > 0) && (typeIndex < values.length - 1);
    final DLTermOrder before = values[typeIndex - 1];
    final DLTermOrder after = values[typeIndex + 1];
    final DLDummyTerm<I, L, K, R> beforeTerm = new DLDummyTerm<>(before);
    final DLDummyTerm<I, L, K, R> afterTerm = new DLDummyTerm<>(after);

    return subSet(beforeTerm, afterTerm);
}

From source file:ArrayHunt.java

/** Play one game. */
public boolean play() {
    int i;/*from  w w w. j  av a2s  . c  o m*/

    // Fill the array with random data (hay?)
    for (i = 0; i < MAX; i++) {
        haystack[i] = (int) (r.nextFloat() * MAX);
    }

    // Precondition for binary search is that data be sorted!
    Arrays.sort(haystack);

    // Look for needle in haystack
    i = Arrays.binarySearch(haystack, NEEDLE);

    if (i >= 0) { // Found it, we win.
        System.out.println("Value " + NEEDLE + " occurs at haystack[" + i + "]");
        return true;
    } else { // Not found, we lose.
        System.out.println("Value " + NEEDLE + " does not occur in haystack; nearest value is "
                + haystack[-(i + 2)] + " (found at " + -(i + 2) + ")");
        return false;
    }
}

From source file:com.reactivetechnologies.analytics.mapper.DataMappers.java

DataMappers() {
    scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new TypeFilter() {

        @Override//  w  ww  .  j  a v  a2  s .c  o  m
        public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
                throws IOException {
            if (metadataReader.getClassMetadata().getClassName().equals(DataMappers.class.getName()))
                return false;
            String[] iFaces = metadataReader.getClassMetadata().getInterfaceNames();
            Arrays.sort(iFaces);
            return Arrays.binarySearch(iFaces, DataMapper.class.getName()) >= 0;
        }
    });

    Set<BeanDefinition> set = scanner.findCandidateComponents(ClassUtils.getPackageName(DataMapper.class));
    if (set.isEmpty()) {
        throw new BeanCreationException("No data mapper implementation classes could be found under package ["
                + ClassUtils.getPackageName(DataMapper.class) + "]");
    }
    for (BeanDefinition bd : set) {
        try {
            DataMapper dm = (DataMapper) ObjenesisHelper.newInstance(Class.forName(bd.getBeanClassName()));
            cache.put(dm.type(), dm);
            log.debug("Found data mapper:: Type [" + dm.type() + "] \t" + dm.getClass());
        } catch (ClassNotFoundException e) {
            throw new BeanCreationException("Unable to instantiate data mapper class", e);
        }

    }
}

From source file:org.apache.shindig.common.util.StringEncoding.java

/** Decodes the given encoded string and returns the original raw bytes. */
public byte[] decode(String encoded) {
    if (encoded.length() == 0) {
        return ArrayUtils.EMPTY_BYTE_ARRAY;
    }//from  w  w  w .j  a v  a  2s  .  co m
    int encodedLength = encoded.length();
    int outLength = encodedLength * SHIFT / 8;
    byte[] result = new byte[outLength];
    int buffer = 0;
    int next = 0;
    int bitsLeft = 0;
    for (char c : encoded.toCharArray()) {
        buffer <<= SHIFT;
        buffer |= Arrays.binarySearch(DIGITS, c) & MASK;
        bitsLeft += SHIFT;
        if (bitsLeft >= 8) {
            result[next++] = (byte) (buffer >> (bitsLeft - 8));
            bitsLeft -= 8;
        }
    }
    assert next == outLength && bitsLeft < SHIFT;
    return result;
}

From source file:com.opengamma.analytics.financial.interestrate.swaption.method.SwaptionPhysicalLMMDDSuccessiveLeastSquareCalibrationEngine.java

@Override
public void addInstrument(final InstrumentDerivative instrument, final PricingMethod method) {
    Validate.notNull(instrument, "Instrument");
    Validate.notNull(method, "Method");
    Validate.isTrue(instrument instanceof SwaptionPhysicalFixedIbor,
            "Calibration instruments should be swaptions");
    SwaptionPhysicalFixedIbor swaption = (SwaptionPhysicalFixedIbor) instrument;
    getBasket().add(instrument);/* w w  w.j  a v  a 2s  .co  m*/
    getMethod().add(method);
    getCalibrationPrice().add(0.0);
    _instrumentIndex.add(Arrays.binarySearch(
            ((SwaptionPhysicalLMMDDSuccessiveLeastSquareCalibrationObjective) getCalibrationObjective())
                    .getLMMParameters().getIborTime(),
            swaption.getUnderlyingSwap().getSecondLeg()
                    .getNthPayment(swaption.getUnderlyingSwap().getSecondLeg().getNumberOfPayments() - 1)
                    .getPaymentTime()));
}

From source file:com.opengamma.analytics.math.surface.NodalObjectsSurface.java

/**
 * {@inheritDoc}/*  www  .j a v a2 s  .c  o m*/
 * @throws IllegalArgumentException If the <i>(x, y)</i> value is not a nodal point 
 */
@Override
public V getZValue(final T x, final U y) {
    Validate.notNull(x, "x");
    Validate.notNull(y, "y");
    final T[] xArray = getXData();
    final int index = Arrays.binarySearch(xArray, x);
    if (index < 0) {
        throw new IllegalArgumentException("No x-y-z data in surface for (" + x + ", " + y + ")");
    }
    final U[] yArray = getYData();
    if (yArray[index].equals(y)) {
        final V[] zArray = getZData();
        return zArray[index];
    }
    throw new IllegalArgumentException("No x-y-z data in surface for (" + x + ", " + y + ")");
}

From source file:org.springside.modules.test.data.H2Fixtures.java

/**
 * ,excludeTables.disable./*from  w  w w  . ja  va2 s.  com*/
 */
public static void deleteAllTable(DataSource dataSource, String... excludeTables) {

    List<String> tableNames = new ArrayList<String>();
    ResultSet rs = null;
    try {
        rs = dataSource.getConnection().getMetaData().getTables(null, null, null, new String[] { "TABLE" });
        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            if (Arrays.binarySearch(excludeTables, tableName) < 0) {
                tableNames.add(tableName);
            }
        }

        deleteTable(dataSource, tableNames.toArray(new String[tableNames.size()]));
    } catch (SQLException e) {
        Exceptions.unchecked(e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

From source file:net.phoenix.nlp.pos.recognitor.DateTimeRecognitor.java

private Status parseStatus(Term term) {
    if (term.getTermNatures().isNature(Nature.Number))
        return Status.Number;
    String name = term.getName();
    name = name.trim();/*from w w w.j  a  va2s . c o m*/
    if (name.length() == 0)
        return Status.Other;
    // ?
    if (name.length() == 1) {
        if (Arrays.binarySearch(this.qualifiers, name.charAt(0)) >= 0)
            return Status.Qualifier;
        else if (Arrays.binarySearch(this.numbers, name.charAt(0)) >= 0)
            return Status.Number;
        else
            return Status.Other;
    }

    // + //?
    boolean isNumber = true;
    int pos = 0;
    // 
    while (isNumber && pos < name.length() - 1) {
        isNumber = (Arrays.binarySearch(this.numbers, name.charAt(pos)) >= 0);
        pos++;
    }
    if (isNumber) {
        if (Arrays.binarySearch(this.qualifiers, name.charAt(pos)) >= 0)
            return Status.Date;
        else if (Arrays.binarySearch(this.numbers, name.charAt(pos)) >= 0)
            return Status.Number;
        else
            return Status.Other;
    }

    return Status.Other;
}

From source file:com.github.dactiv.common.unit.Fixtures.java

/**
 * ,excludeTables.disable./*from w w  w .j a  v a2 s.  c o  m*/
 * @throws SQLException 
 */
public static void deleteAllTable(DataSource h2DataSource, String... excludeTables) throws SQLException {

    List<String> tableNames = new ArrayList<String>();

    try {
        ResultSet rs = h2DataSource.getConnection().getMetaData().getTables(null, null, null,
                new String[] { "TABLE" });

        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            if (Arrays.binarySearch(excludeTables, tableName) < 0) {
                tableNames.add(tableName);
            }
        }

        deleteTable(h2DataSource, tableNames.toArray(new String[tableNames.size()]));

    } catch (SQLException e) {
        throw e;
    }

}