List of usage examples for java.util Arrays binarySearch
public static int binarySearch(Object[] a, Object key)
From source file:org.calrissian.accumulorecipes.commons.hadoop.GroupedKeyRangePartitioner.java
/** * Sets the hdfs file name to use, containing a newline separated list of Base64 encoded split points that represent ranges for partitioning *///from ww w.ja va 2 s .c o m public static void addSplitFile(JobContext job, String group, String file) { URI uri = new Path(file).toUri(); DistributedCache.addCacheFile(uri, job.getConfiguration()); String[] groups = job.getConfiguration().getStrings(GROUPS_KEY); if (groups == null || Arrays.binarySearch(groups, group) == -1) { String[] newGroups = groups != null ? Arrays.copyOf(groups, groups.length + 1) : new String[] {}; newGroups[newGroups.length - 1] = group; job.getConfiguration().setStrings(GROUPS_KEY, newGroups); job.getConfiguration().set(GROUPS_KEY + "." + group, file); } }
From source file:com.l2jfree.gameserver.model.skills.conditions.ConditionPlayerInstanceId.java
@Override public boolean testImpl(Env env) { if (!(env.player instanceof L2Player)) return false; L2Player player = env.player.getActingPlayer(); if (!player.isInInstance()) return false; int templateId = -1; Instance dyn = InstanceManager.getInstance().getDynamicInstance(player); if (dyn != null) templateId = dyn.getTemplate();/* w ww . j a va2s. co m*/ if (templateId == -1) { InstanceWorld world = InstanceManager.getInstance().getPlayerWorld(player); if (world != null && player.isSameInstance(world.instanceId)) templateId = world.templateId; } if (templateId == -1) return false; return Arrays.binarySearch(_instanceIds, templateId) >= 0; }
From source file:de.bund.bfr.math.LinearFunction.java
@Override public double value(double x) { int index = Arrays.binarySearch(abscissa, x); double fx = 0; if (-index - 1 == abscissa.length) { // "x" is larger than the last value in "abscissa". fx = ordinate[-index - 2];//from w w w . jav a 2 s .co m } else if (index < -1) { // "x" is between "abscissa[-index-2]" and "abscissa[-index-1]". double alpha = (x - abscissa[-index - 2]) / (abscissa[-index - 1] - abscissa[-index - 2]); fx = alpha * ordinate[-index - 1] + (1 - alpha) * ordinate[-index - 2]; } else if (index >= 0) { // "x" is exactly "abscissa[index]". fx = ordinate[index]; } else { // Otherwise, "x" is smaller than the first value in "abscissa" // (hence the returned value should be "ordinate[0]"). fx = ordinate[0]; } return fx; }
From source file:com.music.util.music.ChordUtils.java
public static Chord getChord(ScoreContext ctx, int pitch, Chord previousChord, List<Chord> chords, List<Chord> alternativeChords, List<Chord> otherChords, boolean preferStable, boolean preferUnstable) { //TODO check http://mugglinworks.com/chordmaps/mapC.htm // first transpose to C-scale, as the pre-initialized chords are there pitch = pitch - ctx.getKeyNote();// w w w . j a va 2s .com boolean alternative = Chance.test(13); boolean other = !alternative && Chance.test(7); boolean invert = Chance.test(15); List<Chord> listToIterate = chords; if (alternative && alternativeChords != null) { listToIterate = alternativeChords; } else if (other && otherChords != null) { listToIterate = otherChords; } int note = pitch % 12; boolean trimMiddleNote = Chance.test(5); List<Chord> eligibleChords = new ArrayList<>(); List<Chord> alternativeEligibleChords = new ArrayList<>(); for (Chord chordDef : listToIterate) { int[] chordDefPitches = chordDef.getPitches(); int currentNoteIdx = Arrays.binarySearch(chordDefPitches, note); // if the note in the main part is found in the chord, mark as // eligible. In 2% of the cases, allow unharmonizing chords (the // unharmonic chord may not ultimately be selected, hence the high // percentage) if (currentNoteIdx > -1 || Chance.test(2)) { int[] chord = new int[chordDefPitches.length]; if (currentNoteIdx < 0) { currentNoteIdx = 0; } chord[currentNoteIdx] = pitch; // transpose back to the current key (+ctx.getKeyNote()) int root = pitch - chordDefPitches[currentNoteIdx] + chordDefPitches[0] + ctx.getKeyNote(); for (int i = 0; i < chordDefPitches.length; i++) { chord[i] = root + (chordDefPitches[i] - chordDefPitches[0]) + ctx.getKeyNote(); } Chord eligibleChord = new Chord(); eligibleChord.setPitches(chord); eligibleChord.setFirstToneType(chordDef.getFirstToneType()); eligibleChord.setChordType(chordDef.getChordType()); if (invert) { // sometimes invert all but the root, other times - only the final note(s) for (int i = (Chance.test(50) ? 1 : 2); i < eligibleChord.getPitches().length; i++) { eligibleChord.getPitches()[i] = eligibleChord.getPitches()[i] - 12; } } if (trimMiddleNote) { ArrayUtils.remove(eligibleChord.getPitches(), 1); } // if the current chord doesn't match the preferences, store it as a temp result and continue if (preferStable && !ToneGroups.STABLE.getToneTypes().contains(eligibleChord.getFirstToneType())) { alternativeEligibleChords.add(eligibleChord); continue; } if (preferUnstable && !ToneGroups.UNSTABLE.getToneTypes().contains(eligibleChord.getFirstToneType())) { alternativeEligibleChords.add(eligibleChord); continue; } eligibleChords.add(eligibleChord); } } for (Iterator<Chord> it = eligibleChords.iterator(); it.hasNext();) { Chord chord = it.next(); if (isDisallowedInProgression(chord, previousChord) && Chance.test(95)) { it.remove(); if (alternativeEligibleChords.isEmpty()) { alternativeEligibleChords.add(chord); } } } Chord result = null; if (!eligibleChords.isEmpty()) { result = eligibleChords.get(random.nextInt(eligibleChords.size())); } else if (eligibleChords.isEmpty() && !alternativeEligibleChords.isEmpty()) { // if no suitable chord is found that matches the preferences, but there's one that's otherwise suitable, return it result = alternativeEligibleChords.get(random.nextInt(alternativeEligibleChords.size())); } if (result == null) { logger.debug("Failed to find chord for " + pitch + " in scale " + ctx.getScale()); return null; } return result; }
From source file:edu.berkeley.compbio.phyloutils.NASTDistanceMapper.java
public double map(final int position, final int width, final double dnadist) { // find the floor of the position and width among the known entries int widthQuantizedIndex = Arrays.binarySearch(widths, width); if (widthQuantizedIndex < 0) { //BAD test me widthQuantizedIndex = -(widthQuantizedIndex + 1) - 1; }//from w ww .j a va 2 s . c o m int positionQuantizedIndex = Arrays.binarySearch(positions, position); if (positionQuantizedIndex < 0) { //BAD test me positionQuantizedIndex = -(positionQuantizedIndex + 1) - 1; } double slope = slopeTable.get(widthQuantizedIndex, positionQuantizedIndex); return dnadist * slope; }
From source file:com.opengamma.analytics.math.curve.InterpolatedCurveShiftFunction.java
/** * {@inheritDoc}// w ww . j a v a 2 s .c om */ @Override public InterpolatedDoublesCurve evaluate(final InterpolatedDoublesCurve curve, final double x, final double shift, final String newName) { Validate.notNull(curve, "curve"); final double[] xData = curve.getXDataAsPrimitive(); final double[] yData = curve.getYDataAsPrimitive(); final int n = xData.length; final int index = Arrays.binarySearch(xData, x); if (index >= 0) { final double[] shiftedY = Arrays.copyOf(curve.getYDataAsPrimitive(), n); shiftedY[index] += shift; return InterpolatedDoublesCurve.fromSorted(xData, shiftedY, curve.getInterpolator(), newName); } final double[] newX = new double[n + 1]; final double[] newY = new double[n + 1]; for (int i = 0; i < n; i++) { newX[i] = xData[i]; newY[i] = yData[i]; } newX[n] = x; newY[n] = curve.getYValue(x) + shift; return InterpolatedDoublesCurve.from(newX, newY, curve.getInterpolator(), newName); }
From source file:com.yahoo.ycsb.bulk.hbase.RangePartitioner.java
int findPartition(Text key, Text[] array, int numSubBins) { // find the bin for the range, and guarantee it is positive int index = Arrays.binarySearch(array, key); index = index < 0 ? (index + 1) * -1 : index; // both conditions work with numSubBins == 1, but this check is to avoid // hashing, when we don't need to, for speed if (numSubBins < 2) return index; return (key.toString().hashCode() & Integer.MAX_VALUE) % numSubBins + index * numSubBins; }
From source file:com.opengamma.analytics.financial.interestrate.swaption.method.SwaptionPhysicalLMMDDSuccessiveRootFinderCalibrationEngine.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);//from w w w .ja v a 2 s .c om getMethod().add(method); getCalibrationPrice().add(0.0); _instrumentIndex.add(Arrays.binarySearch( ((SwaptionPhysicalLMMDDCalibrationObjective) getCalibrationObjective()).getLMMParameters() .getIborTime(), swaption.getUnderlyingSwap().getSecondLeg() .getNthPayment(swaption.getUnderlyingSwap().getSecondLeg().getNumberOfPayments() - 1) .getPaymentTime())); }
From source file:Util.java
/** * Searches the specified array of doubles for the specified value using * the binary search algorithm. The array <strong>must</strong> be sorted * (as by the <tt>sort</tt> method, above) prior to making this call. If * it is not sorted, the results are undefined. If the array contains * multiple elements with the specified value, there is no guarantee which * one will be found. The array can be sorted from low values to high or * from high values to low.//w w w . j a v a2 s .com * * @param a the array to be searched. * @param key the value to be searched for. * @return index of the search key, if it is contained in the list; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the list: the index of the first * element greater than the key, or <tt>list.size()</tt>, if all * elements in the list are less than the specified key. Note * that this guarantees that the return value will be >= 0 if * and only if the key is found. */ public static int binarySearch(double[] a, double key) { int index = -1; if (a[0] < a[1]) { index = Arrays.binarySearch(a, key); } else { index = binarySearch(a, key, 0, a.length - 1); } return index; }
From source file:net.sf.jooreports.templates.TemplateAndModelMerger.java
public void process(OpenDocumentArchive archive, Object model) throws IOException, DocumentTemplateException { TemplateFreemarkerNamespace predefinedNamespace = new TemplateFreemarkerNamespace(); predefinedNamespace.applyConfigurations(configurations); for (Iterator it = archive.getEntryNames().iterator(); it.hasNext();) { String entryName = (String) it.next(); if (Arrays.binarySearch(xmlEntries, entryName) >= 0) { Reader reader = archive.getEntryReader(entryName); Writer writer = archive.getEntryWriter(entryName); Template template = new Template(entryName, reader, freemarkerConfiguration); BeansWrapper beansWrapper = new BeansWrapper(); try { Environment environment = template.createProcessingEnvironment(model, writer); environment.setGlobalVariable(TemplateFreemarkerNamespace.NAME, beansWrapper.wrap(predefinedNamespace)); environment.process();/*w w w .j ava 2 s .c o m*/ } catch (TemplateException templateException) { throw new DocumentTemplateException(templateException); } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(writer); } } } if (!predefinedNamespace.getImages().isEmpty()) { addRequiredImages(archive, predefinedNamespace.getImages()); } if (openDocumentSettings.size() > 0) { changeOpenDocumentSettings(archive); } }