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.cg.mapreduce.fpgrowth.mahout.fpm.fpgrowth.FPGrowth.java

private static FrequentPatternMaxHeap growthTopDown(FPTree tree, MutableLong minSupportMutable, int k,
        FPTreeDepthCache treeCache, int level, boolean conditionalOfCurrentAttribute, int currentAttribute,
        StatusUpdater updater) {//from ww w.j a v  a 2s . c  om

    FrequentPatternMaxHeap frequentPatterns = new FrequentPatternMaxHeap(k, true);

    if (!conditionalOfCurrentAttribute) {
        int index = Arrays.binarySearch(tree.getHeaderTableAttributes(), currentAttribute);
        if (index < 0) {
            return frequentPatterns;
        } else {
            int attribute = tree.getAttributeAtIndex(index);
            long count = tree.getHeaderSupportCount(attribute);
            if (count < minSupportMutable.longValue()) {
                return frequentPatterns;
            }
        }
    }

    if (tree.singlePath()) {
        return generateSinglePathPatterns(tree, k, minSupportMutable.longValue());
    }

    updater.update("Top Down Growth:");

    for (int i = 0; i < tree.getHeaderTableCount(); i++) {
        int attribute = tree.getAttributeAtIndex(i);
        long count = tree.getHeaderSupportCount(attribute);
        if (count < minSupportMutable.longValue()) {
            continue;
        }

        FPTree conditionalTree = treeCache.getTree(level);

        FrequentPatternMaxHeap returnedPatterns;
        if (conditionalOfCurrentAttribute) {
            traverseAndBuildConditionalFPTreeData(tree.getHeaderNext(attribute), minSupportMutable.longValue(),
                    conditionalTree, tree);

            returnedPatterns = growthBottomUp(conditionalTree, minSupportMutable, k, treeCache, level + 1, true,
                    currentAttribute, updater);
            frequentPatterns = mergeHeap(frequentPatterns, returnedPatterns, attribute, count, true);

        } else {
            if (attribute == currentAttribute) {
                traverseAndBuildConditionalFPTreeData(tree.getHeaderNext(attribute),
                        minSupportMutable.longValue(), conditionalTree, tree);
                returnedPatterns = growthBottomUp(conditionalTree, minSupportMutable, k, treeCache, level + 1,
                        true, currentAttribute, updater);
                frequentPatterns = mergeHeap(frequentPatterns, returnedPatterns, attribute, count, true);

            } else if (attribute > currentAttribute) {
                traverseAndBuildConditionalFPTreeData(tree.getHeaderNext(attribute),
                        minSupportMutable.longValue(), conditionalTree, tree);
                returnedPatterns = growthBottomUp(conditionalTree, minSupportMutable, k, treeCache, level + 1,
                        false, currentAttribute, updater);
                frequentPatterns = mergeHeap(frequentPatterns, returnedPatterns, attribute, count, false);

            }
        }
        if (frequentPatterns.isFull() && minSupportMutable.longValue() < frequentPatterns.leastSupport()) {
            minSupportMutable.setValue(frequentPatterns.leastSupport());
        }
    }

    return frequentPatterns;
}

From source file:com.opengamma.analytics.math.curve.NodalDoublesCurve.java

/**
  * {@inheritDoc}/*from w  ww.ja  v a2s . c o m*/
  * @throws IllegalArgumentException If the <i>x</i> value was not in the nodal points
  */
@Override
public Double getYValue(final Double x) {
    ArgumentChecker.notNull(x, "x");
    final int index = Arrays.binarySearch(getXDataAsPrimitive(), x);
    if (index < 0) {
        throw new IllegalArgumentException("Curve does not contain data for x point " + x);
    }
    return getYDataAsPrimitive()[index];
}

From source file:com.krawler.esp.servlets.importProjectPlanCSV.java

/**
 * Adds the task into proj_task and temp table. any exception will return a HashMap contining error description
 *///from   ww w  .j  a  va 2s  .c om
protected HashMap<Integer, String> storeInDB(Connection conn, JSONObject temp, String projectid,
        String appendchoice, String userid, int totalOldTasks, int recordIndex) throws ServiceException {
    int skipped = 0;
    HashMap<Integer, String> skip = new HashMap<Integer, String>();
    try {
        int nonworkweekArr[] = projdb.getNonWorkWeekDays(conn, projectid);
        String holidayArr[] = projdb.getCompHolidays(conn, projectid, "");
        try {
            String tid = UUID.randomUUID().toString();
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
            String startdate = StringUtil.serverHTMLStripper(temp.getString("startdate"));
            java.util.Date SDateVal = sdf.parse(startdate);
            startdate = sdf.format(SDateVal);
            Calendar cal = Calendar.getInstance();
            cal.setTime(SDateVal);
            java.text.SimpleDateFormat sdf1 = new java.text.SimpleDateFormat("yyyy-MM-dd");
            boolean flag = true;
            while (flag) {
                if ((Arrays.binarySearch(nonworkweekArr, SDateVal.getDay()) >= 0
                        || Arrays.binarySearch(holidayArr, sdf1.format(SDateVal)) >= 0)) {
                    cal.setTime(SDateVal);
                    cal.add(Calendar.DATE, 1);
                    SDateVal = cal.getTime();
                    flag = true;
                } else {
                    flag = false;
                }
            }
            temp.remove("startdate");
            temp.put("startdate", sdf1.format(SDateVal));
            java.util.Date EDateVal = new Date();
            String acduration = "";
            String enddate = "";
            String dura = temp.getString("duration");
            if (!temp.getString("enddate").equals("")) {
                enddate = StringUtil.serverHTMLStripper(temp.getString("enddate"));
                EDateVal = sdf.parse(enddate);
                acduration = getActualDuration_importCSV(SDateVal, EDateVal, nonworkweekArr, holidayArr, dura);
            } else {
                if (!StringUtil.isNullOrEmpty(dura)) {
                    EDateVal = projdb.calculateEndDate(conn, SDateVal, dura, nonworkweekArr, holidayArr, "");
                    enddate = sdf.format(EDateVal);
                    acduration = dura;
                } else {
                    throw new ParseException("Insufficient Data", 0);
                }
            }

            temp.put("duration", acduration);
            temp.put("actstartdate", startdate);
            temp.put("enddate", enddate);
            temp.put("level", "0");
            temp.put("isparent", "false");
            temp.put("loginid", userid);
            temp.put("links", "");
            projdb.InsertTask(conn, temp, tid, projectid, Integer.toString(totalOldTasks));
            totalOldTasks++;
            DbUtil.executeUpdate(conn, "INSERT INTO tempImportData VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
                    new Object[] { recordIndex, tid, temp.getString("taskname"), temp.getString("duration"),
                            temp.getString("startdate"), temp.getString("enddate"),
                            temp.getInt("percentcomplete"), temp.getString("priority"), temp.getString("notes"),
                            temp.getString("resourcename"), temp.getString("predecessor"),
                            temp.getString("parent"), "" });
            String resnames = temp.getString("resourcename");
            String[] res = resnames.split(",");
            for (int c = 0; c < res.length; c++) {
                if (!StringUtil.equal(res[c], ""))
                    resNames.add(res[c]);
            }
        } catch (com.krawler.utils.json.base.JSONException ex) {
            //                skip.put(++skipped, MessageSourceProxy.getMessage(KWLErrorMsgs.importCSVInvFormat, null, locale));
            skip.put(++skipped, KWLErrorMsgs.importCSVInvFormat);
        } catch (ParseException ex) {
            //                skip.put(++skipped, MessageSourceProxy.getMessage(KWLErrorMsgs.importCSVInvDateFormat, null, locale));
            skip.put(++skipped, KWLErrorMsgs.importCSVInvDateFormat);
        } catch (ServiceException ex) {
            //                skip.put(++skipped, MessageSourceProxy.getMessage(KWLErrorMsgs.importCSVTaskFailure, null, locale));
            skip.put(++skipped, KWLErrorMsgs.importCSVTaskFailure);
        }
    } catch (ServiceException ex) {
        KrawlerLog.op.warn("Problem Storing Data In DB [importProjectPlanCSV.storeInDB()]:" + ex.toString());
        throw ServiceException.FAILURE("importProjectPlanCSV.storeInDB error", ex);
    }
    return skip;
}

From source file:com.opengamma.util.timeseries.fast.integer.object.FastArrayIntObjectTimeSeries.java

@Override
public T getValueFast(final int time) {
    final int binarySearch = Arrays.binarySearch(_times, time);
    if (binarySearch >= 0 && _times[binarySearch] == time) {
        return _values[binarySearch];
    } else {//from   w  ww  .  j  a v  a 2 s.com
        throw new NoSuchElementException();
    }
}

From source file:com.opengamma.util.timeseries.fast.longint.object.FastArrayLongObjectTimeSeries.java

@Override
public T getValueFast(final long time) {
    final int binarySearch = Arrays.binarySearch(_times, time);
    if (binarySearch >= 0 && _times[binarySearch] == time) {
        return _values[binarySearch];
    } else {/* w ww.j a  va 2  s  .  co  m*/
        throw new NoSuchElementException();
    }
}

From source file:org.dspace.app.rest.utils.MultipartFileSender.java

private static boolean matches(String matchHeader, String toMatch) {
    String[] matchValues = matchHeader.split("\\s*,\\s*");
    Arrays.sort(matchValues);//www  .j  a v a2s .c om
    return Arrays.binarySearch(matchValues, toMatch) > -1 || Arrays.binarySearch(matchValues, "*") > -1;
}

From source file:com.opengamma.util.timeseries.fast.longint.FastArrayLongDoubleTimeSeries.java

@Override
public double getValueFast(final long time) {
    final int binarySearch = Arrays.binarySearch(_times, time);
    if (binarySearch >= 0 && _times[binarySearch] == time) {
        return _values[binarySearch];
    } else {/*  www .  j  a v a  2 s  . co  m*/
        throw new NoSuchElementException();
    }
}

From source file:com.simiacryptus.mindseye.lang.Tensor.java

/**
 * Normalize distribution tensor.//from  w ww .  j  a  v a2 s.  co m
 *
 * @return the tensor
 */
public Tensor normalizeDistribution() {
    double[] sortedValues = Arrays.stream(getData()).sorted().toArray();
    Tensor result = map(
            v -> Math.abs(((double) Arrays.binarySearch(sortedValues, v)) / ((double) sortedValues.length)));
    return result;
}

From source file:net.mariottini.swing.JFontChooser.java

/**
 * Sets the currently selected font. The dialog will try to change the listboxes selections
 * according to the font set./*from  www. j a v a 2s  .co m*/
 * 
 * @param font
 *          the font to select.
 */
public void setSelectedFont(Font font) {
    fontList.setSelectedValue(font.getFamily(), true);
    styleList.setSelectedIndex(font.getStyle());
    int size = font.getSize();
    int index = Arrays.binarySearch(SIZES, new Integer(size));
    if (index >= 0) {
        sizeList.setSelectedIndex(index);
        sizeList.ensureIndexIsVisible(index);
    } else {
        sizeText.setText(String.valueOf(size));
    }
}

From source file:net.sf.maltcms.chromaui.project.spi.descriptors.CachingChromatogram2D.java

@Override
public int getIndexFor(double scan_acquisition_time) {
    init();//from   ww w . j  a  va  2s  . c  o  m
    double[] satArray = getSatArray();
    int idx = Arrays.binarySearch(satArray, scan_acquisition_time);
    if (idx >= 0) {// exact hit
        log.log(Level.FINE, "sat {0}, scan_index {1}", new Object[] { scan_acquisition_time, idx });
        return idx;
    } else {// imprecise hit, find closest element
        int insertionPosition = (-idx) - 1;
        if (insertionPosition <= 0) {
            log.log(Level.WARNING, "Insertion position was {0}, setting to index 0", insertionPosition);
        }
        if (insertionPosition >= satArray.length) {
            log.log(Level.WARNING, "Insertion position was {0}, setting to index {1}",
                    new Object[] { insertionPosition, satArray.length - 1 });
        }
        double current = satArray[Math.min(satArray.length - 1, insertionPosition)];
        double previous = satArray[Math.max(0, insertionPosition - 1)];
        if (Math.abs(scan_acquisition_time - previous) <= Math.abs(scan_acquisition_time - current)) {
            int index = Math.max(0, insertionPosition - 1);
            return index;
        } else {
            return insertionPosition;
        }
    }
}