Java Code Examples for java.util.Arrays#binarySearch()
The following examples show how to use
java.util.Arrays#binarySearch() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SparseVector.java From flink with Apache License 2.0 | 6 votes |
@Override public SparseVector slice(int[] indices) { SparseVector sliced = new SparseVector(indices.length); int nnz = 0; sliced.indices = new int[indices.length]; sliced.values = new double[indices.length]; for (int i = 0; i < indices.length; i++) { int pos = Arrays.binarySearch(this.indices, indices[i]); if (pos >= 0) { sliced.indices[nnz] = i; sliced.values[nnz] = this.values[pos]; nnz++; } } if (nnz < sliced.indices.length) { sliced.indices = Arrays.copyOf(sliced.indices, nnz); sliced.values = Arrays.copyOf(sliced.values, nnz); } return sliced; }
Example 2
Source File: EntityLiving.java From Nukkit with GNU General Public License v3.0 | 6 votes |
public Block getTargetBlock(int maxDistance, Integer[] transparent) { try { Block[] blocks = this.getLineOfSight(maxDistance, 1, transparent); Block block = blocks[0]; if (block != null) { if (transparent != null && transparent.length != 0) { if (Arrays.binarySearch(transparent, block.getId()) < 0) { return block; } } else { return block; } } } catch (Exception ignored) { } return null; }
Example 3
Source File: JGenProg2017_0076_t.java From coming with MIT License | 6 votes |
public String getNameKey(long instant) { long[] transitions = iTransitions; int i = Arrays.binarySearch(transitions, instant); if (i >= 0) { return iNameKeys[i]; } i = ~i; if (i < transitions.length) { if (i > 0) { return iNameKeys[i - 1]; } return "UTC"; } if (iTailZone == null) { return iNameKeys[i - 1]; } return iTailZone.getNameKey(instant); }
Example 4
Source File: ZoneRules.java From desugar_jdk_libs with GNU General Public License v2.0 | 6 votes |
/** * Gets the standard offset for the specified instant in this zone. * <p> * This provides access to historic information on how the standard offset * has changed over time. * The standard offset is the offset before any daylight saving time is applied. * This is typically the offset applicable during winter. * * @param instant the instant to find the offset information for, not null, but null * may be ignored if the rules have a single offset for all instants * @return the standard offset, not null */ public ZoneOffset getStandardOffset(Instant instant) { // For desugar: use TimeZone if given. Note this always the returns the time zone's current // standard offset and doesn't work for historical dates where the standard offset differed. if (timeZone != null) { return offsetFromMillis(timeZone.getRawOffset()); } if (savingsInstantTransitions.length == 0) { return standardOffsets[0]; } long epochSec = instant.getEpochSecond(); int index = Arrays.binarySearch(standardTransitions, epochSec); if (index < 0) { // switch negative insert position to start of matched range index = -index - 2; } return standardOffsets[index + 1]; }
Example 5
Source File: JGenProg2017_00100_t.java From coming with MIT License | 6 votes |
public long nextTransition(long instant) { long[] transitions = iTransitions; int i = Arrays.binarySearch(transitions, instant); i = (i >= 0) ? (i + 1) : ~i; if (i < transitions.length) { return transitions[i]; } if (iTailZone == null) { return instant; } long end = transitions[transitions.length - 1]; if (instant < end) { instant = end; } return iTailZone.nextTransition(instant); }
Example 6
Source File: DdlHelper.java From jaybird with GNU Lesser General Public License v2.1 | 6 votes |
/** * Helper method for executing DDL (or technically: any statement), ignoring the specified list of error codes. * * @param connection * Connection to execute statement * @param sql * DDL statement * @param ignoreErrors * Firebird error codes to ignore * @throws SQLException * SQLException for executing statement, except for errors with the error code listed in * <code>ignoreErrors</code> * @see org.firebirdsql.gds.ISCConstants */ public static void executeDDL(final Connection connection, final String sql, final int... ignoreErrors) throws SQLException { if (ignoreErrors != null) { Arrays.sort(ignoreErrors); } try (Statement stmt = connection.createStatement()) { stmt.execute(sql); } catch (SQLException ex) { if (ignoreErrors == null || ignoreErrors.length == 0) throw ex; for (Throwable current : ex) { if (current instanceof SQLException && Arrays.binarySearch(ignoreErrors, ((SQLException) current).getErrorCode()) >= 0) { return; } } throw ex; } }
Example 7
Source File: ArraySearchTests.java From morpheus-core with Apache License 2.0 | 5 votes |
@Test(dataProvider = "types") @SuppressWarnings("unchecked") public <T> void testFindPreviousValue(Class<T> type, ArrayStyle style) { final Function<T,T> previousResolver = v -> { if (v instanceof Integer) return (T)(new Integer(((Integer)v) - 1)); if (v instanceof Long) return (T)(new Long(((Long)v) - 1L)); if (v instanceof Double) return (T)new Double(((Double)v) - 1d); if (v instanceof Date) return (T)new Date(((Date)v).getTime() - 5000); if (v instanceof LocalDate) return (T)((LocalDate)v).minusDays(1); if (v instanceof LocalTime) return (T)((LocalTime)v).minusNanos(1); if (v instanceof LocalDateTime) return (T)((LocalDateTime)v).minusSeconds(1); if (v instanceof ZonedDateTime) return (T)((ZonedDateTime)v).minusSeconds(1); if (v instanceof Currency) return (T)currencies[currencyList.indexOf(v) - 1]; if (v instanceof Month) return (T)LocalDate.of(2000, ((Month)v).getValue(), 1).minusDays(10).getMonth(); if (v instanceof String) return (T)alphabet[Arrays.binarySearch(alphabet, v.toString())-1]; throw new IllegalArgumentException("Type not supported: " + v); }; if (ArrayType.of(type) != ArrayType.BOOLEAN) { final Random random = new Random(); final Array<T> array = createArray(type, style).sort(true); Assert.assertTrue(ArraySortTests.isAscending(array, 0, array.length()), "The array is in ascending order"); for (int i=0; i<5000; ++i) { final int index = random.nextInt(array.length()); if (index > 0) { final T value = array.getValue(index); final T expectedPrevious = array.getValue(index-1); final Optional<T> previousValue = array.previous(value).map(ArrayValue::getValue); Assert.assertTrue(previousValue.isPresent(), "A lower value exists for index " + index); Assert.assertEquals(previousValue.get(), expectedPrevious, "Matches expected previous value for index " + index); final T valueAdjusted = previousResolver.apply(value); final Optional<T> previousValueAdj = array.previous(valueAdjusted).map(ArrayValue::getValue); Assert.assertTrue(previousValueAdj.isPresent(), "A lower value exists for index " + index); Assert.assertEquals(previousValueAdj.get(), expectedPrevious, "Matches expected previous value for index " + index); } } } }
Example 8
Source File: PrecisionRecallCurve.java From deeplearning4j with Apache License 2.0 | 5 votes |
/** * Get the point (index, threshold, precision, recall) at the given threshold.<br> * Note that if the threshold is not found exactly, the next highest threshold exceeding the requested threshold * is returned * * @param threshold Threshold to get the point for * @return point (index, threshold, precision, recall) at the given threshold */ public Point getPointAtThreshold(double threshold) { //Return (closest) point number, precision, recall, whether it's interpolated or not //Binary search to find closest threshold int idx = Arrays.binarySearch(this.threshold, threshold); if (idx < 0) { //Not found (usual case). binarySearch javadoc: /* index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. */ idx = -idx - 1; } //At this point: idx = exact, on the next highest double thr = this.threshold[idx]; double pr = precision[idx]; double rec = recall[idx]; return new Point(idx, thr, pr, rec); }
Example 9
Source File: PrimeFinder.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
/** * Returns a prime number which is <code>>= desiredCapacity</code> * and very close to <code>desiredCapacity</code> (within 11% if * <code>desiredCapacity >= 1000</code>). * * @param desiredCapacity the capacity desired by the user. * @return the capacity which should be used for a hashtable. */ public static final int nextPrime(int desiredCapacity) { int i = Arrays.binarySearch(primeCapacities, desiredCapacity); if (i<0) { // desired capacity not found, choose next prime greater // than desired capacity i = -i -1; // remember the semantics of binarySearch... } return primeCapacities[i]; }
Example 10
Source File: TLongHashSet.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
/** * Removes any values in the set which are not contained in * <tt>array</tt>. * * @param array an <code>array</code> of long primitives. * @return true if the set was modified by the retain all operation */ public boolean retainAll(long[] array) { boolean changed = false; Arrays.sort(array); long[] set = _set; byte[] states = _states; for (int i = set.length; i-- > 0;) { if (states[i] == FULL && (Arrays.binarySearch(array,set[i]) < 0)) { remove(set[i]); changed = true; } } return changed; }
Example 11
Source File: Histogram.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
public int getFrequency(int value) { int pos = Arrays.binarySearch(values, value); if (pos < 0) return 0; assert(values[pos] == value); return counts[pos]; }
Example 12
Source File: PrefHelper.java From Easy_xkcd with Apache License 2.0 | 5 votes |
public boolean checkWhatIfFav(int number) { String fav = sharedPrefs.getString(WHATIF_FAV, ""); if (fav.equals("")) { return false; } String[] favList = fav.split(","); int[] favInt = new int[favList.length]; for (int i = 0; i < favInt.length; i++) favInt[i] = Integer.parseInt(favList[i]); Arrays.sort(favInt); int a = Arrays.binarySearch(favInt, number); return (a >= 0); }
Example 13
Source File: PacketDownloadProxyInfo.java From SubServers-2 with Apache License 2.0 | 5 votes |
@Override public ObjectMap<Integer> send(SubDataClient client) { ObjectMap<Integer> data = new ObjectMap<Integer>(); if (tracker != null) data.set(0x0000, tracker); ObjectMap<String> proxies = new ObjectMap<String>(); for (Proxy proxy : plugin.api.getProxies().values()) { if (this.proxies == null || Arrays.binarySearch(this.proxies, proxy.getName().toLowerCase()) >= 0) { proxies.set(proxy.getName(), proxy.forSubData()); } } data.set(0x0001, proxies); if (this.proxies != null && plugin.api.getMasterProxy() != null && (this.proxies.length <= 0 || Arrays.binarySearch(this.proxies, plugin.api.getMasterProxy().getName().toLowerCase()) >= 0)) data.set(0x0002, plugin.api.getMasterProxy().forSubData()); return data; }
Example 14
Source File: ZoneRules.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
/** * Gets the next transition after the specified instant. * <p> * This returns details of the next transition after the specified instant. * For example, if the instant represents a point where "Summer" daylight savings time * applies, then the method will return the transition to the next "Winter" time. * * @param instant the instant to get the next transition after, not null, but null * may be ignored if the rules have a single offset for all instants * @return the next transition after the specified instant, null if this is after the last transition */ public ZoneOffsetTransition nextTransition(Instant instant) { if (savingsInstantTransitions.length == 0) { return null; } long epochSec = instant.getEpochSecond(); // check if using last rules if (epochSec >= savingsInstantTransitions[savingsInstantTransitions.length - 1]) { if (lastRules.length == 0) { return null; } // search year the instant is in int year = findYear(epochSec, wallOffsets[wallOffsets.length - 1]); ZoneOffsetTransition[] transArray = findTransitionArray(year); for (ZoneOffsetTransition trans : transArray) { if (epochSec < trans.toEpochSecond()) { return trans; } } // use first from following year if (year < Year.MAX_VALUE) { transArray = findTransitionArray(year + 1); return transArray[0]; } return null; } // using historic rules int index = Arrays.binarySearch(savingsInstantTransitions, epochSec); if (index < 0) { index = -index - 1; // switched value is the next transition } else { index += 1; // exact match, so need to add one to get the next } return new ZoneOffsetTransition(savingsInstantTransitions[index], wallOffsets[index], wallOffsets[index + 1]); }
Example 15
Source File: Main.java From Box with Apache License 2.0 | 5 votes |
/** * Check the class name to make sure it's not a "core library" * class. If there is a problem, this updates the error count and * throws an exception to stop processing. * * @param name {@code non-null;} the fully-qualified internal-form * class name */ private void checkClassName(String name) { boolean bogus = false; if (name.startsWith("java/")) { bogus = true; } else if (name.startsWith("javax/")) { int slashAt = name.indexOf('/', 6); if (slashAt == -1) { // Top-level javax classes are verboten. bogus = true; } else { String pkg = name.substring(6, slashAt); bogus = (Arrays.binarySearch(JAVAX_CORE, pkg) >= 0); } } if (! bogus) { return; } /* * The user is probably trying to include an entire desktop * core library in a misguided attempt to get their application * working. Try to help them understand what's happening. */ context.err.println("\ntrouble processing \"" + name + "\":\n\n" + IN_RE_CORE_CLASSES); errors.incrementAndGet(); throw new StopProcessing(); }
Example 16
Source File: ImplicitObjectELResolver.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Override public boolean isReadOnly(ELContext context, Object base, Object property) { Objects.requireNonNull(context); if (base == null && property != null) { int idx = Arrays.binarySearch(SCOPE_NAMES, property.toString()); if (idx >= 0) { context.setPropertyResolved(base, property); return true; } } return false; }
Example 17
Source File: HijrahChronology.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
/** * Returns the epochMonth found by locating the epochDay in the table. The * epochMonth is the index in the table * * @param epochDay * @return The index of the element of the start of the month containing the * epochDay. */ private int epochDayToEpochMonth(int epochDay) { // binary search int ndx = Arrays.binarySearch(hijrahEpochMonthStartDays, epochDay); if (ndx < 0) { ndx = -ndx - 2; } return ndx; }
Example 18
Source File: ColGroupUncompressed.java From systemds with Apache License 2.0 | 5 votes |
@Override public double get(int r, int c) { // find local column index int ix = Arrays.binarySearch(_colIndexes, c); if(ix < 0) throw new RuntimeException("Column index " + c + " not in uncompressed group."); // uncompressed get value return _data.quickGetValue(r, ix); }
Example 19
Source File: Helpers.java From UsbSerial with MIT License | 4 votes |
static boolean exists(long[] devices, int vendorId, int productId) { return Arrays.binarySearch(devices, createDevice(vendorId, productId)) >= 0; }
Example 20
Source File: TimeDiscretizationFromArray.java From finmath-lib with Apache License 2.0 | 4 votes |
@Override public int getTimeIndex(final double time) { return Arrays.binarySearch(timeDiscretization, roundToTimeTickSize(time)); }