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:geovista.readers.csv.GeogCSVReader.java

public Object[] readFile(InputStream is) {
    ICsvListReader listReader = null;//  w  w  w. ja v a  2 s.  com
    // CSVParser shredder = new CSVParser(is);
    // shredder.setCommentStart("#;!");
    // shredder.setEscapes("nrtf", "\n\r\t\f");
    String[] headers = null;
    String[] types = null;
    int[] dataTypes = null;
    String[][] fileContent = null; // not including headers
    int dataBegin;
    Object[] data;
    try {

        listReader = new CsvListReader(new InputStreamReader(is), this.prefs());
        // Thread.dumpStack();

        headers = this.readLine(listReader);

        String[] line = null;
        ArrayList<String[]> lines = new ArrayList<String[]>();
        while ((line = this.readLine(listReader)).length > 0) {
            lines.add(line);
        }
        // String[] firstLine = lines.get(0);
        int nColumns = headers.length;
        int nRows = lines.size();

        fileContent = new String[nRows][nColumns];
        for (int row = 0; row < nRows; row++) {
            for (int column = 0; column < nColumns; column++) {
                String aString = lines.get(row)[column];
                fileContent[row][column] = aString;
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    // types = this.readLine(listReader);// first line tells us types
    // (maybe)
    // types = fileContent[0];
    types = headers;
    dataTypes = new int[types.length];
    int len;
    if (types[0].equalsIgnoreCase("int") || types[0].equalsIgnoreCase("double")
            || types[0].equalsIgnoreCase("string")) {
        dataBegin = 1;
        headers = fileContent[0];
        data = new Object[headers.length + 1];// plus one for the headers
        // themselves
        len = fileContent.length - dataBegin;
        for (int i = 0; i < headers.length; i++) {
            if (types[i].equalsIgnoreCase("int")) {
                data[i + 1] = new int[len];
                dataTypes[i] = GeogCSVReader.DATA_TYPE_INT;
            } else if (types[i].equalsIgnoreCase("double")) {
                data[i + 1] = new double[len];
                dataTypes[i] = GeogCSVReader.DATA_TYPE_DOUBLE;
            } else if (types[i].equalsIgnoreCase("string")) {
                data[i + 1] = new String[len];
                dataTypes[i] = GeogCSVReader.DATA_TYPE_STRING;
            } else {
                throw new IllegalArgumentException("GeogCSVReader.readFile, unknown type = " + types[i]);
            }
        }
    } else {
        // sniff the types (is there a better way?)
        dataBegin = 0;
        // headers = firstLine;
        data = new Object[headers.length + 1];// plus one for the headers
        // themselves
        len = fileContent.length - dataBegin;
        for (int i = 0; i < headers.length; i++) {
            String firstString = fileContent[1][i];
            String secondString = fileContent[2][i];
            String thirdString = fileContent[3][i];
            int lastRowNum = fileContent.length - 1;// -2
            String lastString = fileContent[lastRowNum][i];

            if (isNumeric(firstString) && isNumeric(secondString) && isNumeric(thirdString)
                    && isNumeric(lastString)) {
                if (isInt(fileContent, i) == false) {
                    // if (isDouble(firstString) || isDouble(secondString)
                    // || isDouble(thirdString) || isDouble(lastString)) {
                    data[i + 1] = new double[len];
                    dataTypes[i] = GeogCSVReader.DATA_TYPE_DOUBLE;
                } else {
                    data[i + 1] = new int[len];
                    dataTypes[i] = GeogCSVReader.DATA_TYPE_INT;
                }
            } else {
                data[i + 1] = new String[len];
                dataTypes[i] = GeogCSVReader.DATA_TYPE_STRING;
            }
        }
    }
    data[0] = headers;

    String[] line = null;

    for (int row = dataBegin; row < len + dataBegin; row++) {

        line = fileContent[row];

        int[] ints = null;
        double[] doubles = null;
        String[] strings = null;

        for (int column = 0; column < line.length; column++) {
            String item = line[column];
            if (item == null) {
                item = ""; // horrid hack
            }
            if (dataTypes[column] == GeogCSVReader.DATA_TYPE_INT) {

                if (Arrays.binarySearch(GeogCSVReader.NULL_STRINGS, item) >= 0) {
                    ints = (int[]) data[column + 1];
                    ints[row - dataBegin] = GeogCSVReader.NULL_INT;
                } else {
                    ints = (int[]) data[column + 1];
                    try {
                        ints[row - dataBegin] = Integer.parseInt(item);
                    } catch (NumberFormatException nfe) {
                        logger.warning("could not parse " + item + " in column " + column);
                        // nfe.printStackTrace();
                        ints[row - dataBegin] = GeogCSVReader.NULL_INT;
                    }
                }
            } else if (dataTypes[column] == GeogCSVReader.DATA_TYPE_DOUBLE) {
                if (Arrays.binarySearch(GeogCSVReader.NULL_STRINGS, item) >= 0) {
                    doubles = (double[]) data[column + 1];
                    doubles[row - dataBegin] = GeogCSVReader.NULL_DOUBLE;
                } else {
                    doubles = (double[]) data[column + 1];
                    doubles[row - dataBegin] = parseDouble(item);
                }
            } else if (dataTypes[column] == GeogCSVReader.DATA_TYPE_STRING) {
                strings = (String[]) data[column + 1];
                strings[row - dataBegin] = item;
            } else {
                throw new IllegalArgumentException("GeogCSVReader.readFile, unknown type = " + types[row]);
            } // end if

        } // next column
    } // next row
    return data;

}

From source file:com.nttec.everychan.ui.presentation.PresentationModel.java

private synchronized void updateViewModels(PostModel[] posts, boolean showIndex, CancellableTask task,
        RebuildCallback rebuildCallback) {
    if (task == null)
        task = CancellableTask.NOT_CANCELLABLE;
    synchronized (lock) {
        notReady = true;/*from   w  w  w .  ja va2 s  .c om*/
    }
    if (presentationList == null) {
        presentationList = new ArrayList<PresentationItemModel>(posts.length); //   ? ?(?)
        attachments = new ArrayList<Triple<AttachmentModel, String, String>>();
    }

    if (task.isCancelled())
        return;

    String[] subscriptions = null;
    if (source.pageModel.type == UrlPageModel.TYPE_THREADPAGE
            && MainApplication.getInstance().settings.highlightSubscriptions()) {
        subscriptions = MainApplication.getInstance().subscriptions.getSubscriptions(source.pageModel.chanName,
                source.pageModel.boardName, source.pageModel.threadNumber);
    }

    boolean headersRebuilding = false;
    int indexCounter = 0;

    boolean rebuild = false;
    if (posts.length < presentationList.size()) {
        rebuild = true;
        Logger.d(TAG, "rebuild: new list is shorter");
    } else {
        for (int i = 0, size = presentationList.size(); i < size; ++i) {
            if (!presentationList.get(i).sourceModel.number.equals(posts[i].number)
                    || ChanModels.hashPostModel(posts[i]) != presentationList.get(i).sourceModelHash) {
                rebuild = true;
                Logger.d(TAG, "rebuild: changed item " + i);
                break;
            }
            if (showIndex) {
                if (!posts[i].deleted)
                    ++indexCounter;
                if (headersRebuilding |= presentationList.get(i).isDeleted != posts[i].deleted) {
                    presentationList.get(i).buildSpannedHeader(!posts[i].deleted ? indexCounter : -1,
                            source.boardModel.bumpLimit, reduceNames ? source.boardModel.defaultUserName : null,
                            source.pageModel.type == UrlPageModel.TYPE_SEARCHPAGE ? posts[i].parentThread
                                    : null,
                            subscriptions != null ? Arrays.binarySearch(subscriptions, posts[i].number) >= 0
                                    : false);
                }
            }
            presentationList.get(i).isDeleted = posts[i].deleted;
        }
    }

    if (task.isCancelled())
        return;

    if (rebuild) {
        if (rebuildCallback != null)
            rebuildCallback.onRebuild();
        presentationList.clear();
        postNumbersMap.clear();
        attachments.clear();
        indexCounter = 0;
    }

    final boolean openSpoilers = MainApplication.getInstance().settings.openSpoilers();

    for (int i = presentationList.size(); i < posts.length; ++i) {
        if (task.isCancelled())
            return;
        PresentationItemModel model = new PresentationItemModel(posts[i], source.pageModel.chanName,
                source.pageModel.boardName,
                source.pageModel.type == UrlPageModel.TYPE_THREADPAGE ? source.pageModel.threadNumber : null,
                dateFormat, spanClickListener, imageGetter, ThemeUtils.ThemeColors.getInstance(theme),
                openSpoilers, floatingModels, subscriptions);
        postNumbersMap.put(posts[i].number, i);
        if (source.pageModel.type == UrlPageModel.TYPE_THREADPAGE) {
            for (String ref : model.referencesTo) {
                Integer postPosition = postNumbersMap.get(ref);
                if (postPosition != null && postPosition < presentationList.size()) {
                    presentationList.get(postPosition).addReferenceFrom(model.sourceModel.number);
                }
            }
        }
        presentationList.add(model);
        for (int j = 0; j < model.attachmentHashes.length; ++j) {
            attachments.add(Triple.of(posts[i].attachments[j], model.attachmentHashes[j], posts[i].number));
        }

        model.buildSpannedHeader(showIndex && !posts[i].deleted ? ++indexCounter : -1,
                source.boardModel.bumpLimit, reduceNames ? source.boardModel.defaultUserName : null,
                source.pageModel.type == UrlPageModel.TYPE_SEARCHPAGE ? posts[i].parentThread : null,
                subscriptions != null ? Arrays.binarySearch(subscriptions, posts[i].number) >= 0 : false);

        if (source.pageModel.type == UrlPageModel.TYPE_THREADPAGE) {
            model.hidden = isHiddenDelegate.isHidden(source.pageModel.chanName, source.pageModel.boardName,
                    source.pageModel.threadNumber, posts[i].number);
        } else if (source.pageModel.type == UrlPageModel.TYPE_BOARDPAGE
                || source.pageModel.type == UrlPageModel.TYPE_CATALOGPAGE) {
            model.hidden = isHiddenDelegate.isHidden(source.pageModel.chanName, source.pageModel.boardName,
                    posts[i].number, null);
        }
        if (!model.hidden && ( //?
        source.pageModel.type == UrlPageModel.TYPE_THREADPAGE
                || source.pageModel.type == UrlPageModel.TYPE_BOARDPAGE
                || source.pageModel.type == UrlPageModel.TYPE_CATALOGPAGE)) {
            for (AutohideActivity.CompiledAutohideRule rule : autohideRules) {
                if ((rule.inComment && model.spannedComment != null
                        && rule.pattern.matcher(model.spannedComment).find())
                        || (rule.inSubject && posts[i].subject != null
                                && rule.pattern.matcher(posts[i].subject).find())
                        || (rule.inName && (posts[i].name != null && rule.pattern.matcher(posts[i].name).find())
                                || (posts[i].trip != null && rule.pattern.matcher(posts[i].trip).find()))) {
                    model.hidden = true;
                    model.autohideReason = rule.regex;
                }
            }
        }
    }

    if (source.pageModel.type == UrlPageModel.TYPE_THREADPAGE) {
        for (PresentationItemModel model : presentationList) {
            if (task.isCancelled())
                return;
            model.buildReferencesString();
        }
    }

    if (source.threads != null) {
        for (int i = 0; i < source.threads.length; ++i) {
            if (task.isCancelled())
                return;
            presentationList.get(i).buildPostsCountString(source.threads[i].postsCount,
                    source.threads[i].attachmentsCount);
            presentationList.get(i).buildStickyClosedString(source.threads[i].isSticky,
                    source.threads[i].isClosed);
        }
    }
    notReady = false;
}

From source file:net.sf.maltcms.chromaui.project.spi.wizard.DBProjectVisualPanel1.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    FileChooserBuilder fcb = new FileChooserBuilder(DBProjectVisualPanel1.class);
    final String[] fileExtensions = new String[] { "csv", "tsv", "txt", "cdf", "nc", "mz5", "mzml", "mzxml",
            "mzdata" };
    Arrays.sort(fileExtensions);//from  w w  w  .java  2  s  . c  o m
    //fcb.setFilesOnly(true);
    fcb.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else {
                String ext = StringTools.getFileExtension(file.getName().toLowerCase());
                int idx = Arrays.binarySearch(fileExtensions, ext);
                if (idx >= 0) {
                    Logger.getLogger(getClass().getName()).log(Level.INFO,
                            "Found matching file extension at index: {0}={1}",
                            new Object[] { idx, fileExtensions[idx] });
                    return true;
                }
                return false;
            }
        }

        @Override
        public String getDescription() {
            return "Peak lists, Raw chromatograms (recursive)";
        }
    });
    fcb.setTitle("Select Input Files");
    //        jfc.setMultiSelectionEnabled(true);
    File[] files = fcb.showMultiOpenDialog();
    if (files != null) {
        for (File f : files) {
            if (f.isDirectory()) {
                Collection<File> l = FileUtils.listFiles(f, fileExtensions, true);
                for (File file : l) {
                    Logger.getLogger(getClass().getName()).log(Level.INFO,
                            "Adding file below selected directory: {0}", file);
                    getListModel().addElement(file);
                }
            } else {
                Logger.getLogger(getClass().getName()).log(Level.INFO, "Adding selected file: {0}", f);
                getListModel().addElement(f);
            }
        }
        firePropertyChange("VALIDATE", null, null);
    }
}

From source file:com.bt.download.android.gui.Librarian.java

private void syncApplicationsProviderSupport() {
    try {/*from  w w w . ja v  a  2s  .  co m*/

        List<FileDescriptor> fds = Librarian.instance().getFiles(Constants.FILE_TYPE_APPLICATIONS, 0,
                Integer.MAX_VALUE, false);

        int packagesSize = fds.size();
        String[] packages = new String[packagesSize];
        for (int i = 0; i < packagesSize; i++) {
            packages[i] = fds.get(i).album;
        }
        Arrays.sort(packages);

        List<ApplicationInfo> applications = context.getPackageManager().getInstalledApplications(0);

        int size = applications.size();

        ArrayList<String> newPackagesList = new ArrayList<String>(size);

        for (int i = 0; i < size; i++) {
            ApplicationInfo appInfo = applications.get(i);

            try {
                if (appInfo == null) {
                    continue;
                }

                newPackagesList.add(appInfo.packageName);

                File f = new File(appInfo.sourceDir);
                if (!f.canRead()) {
                    continue;
                }

                int index = Arrays.binarySearch(packages, appInfo.packageName);
                if (index >= 0) {
                    continue;
                }

                String data = appInfo.sourceDir;
                String title = appInfo.packageName;
                String packageName = appInfo.packageName;
                String version = "";

                Apk apk = new Apk(context, appInfo.sourceDir);
                String[] result = parseApk(apk);
                if (result != null) {
                    if (result[1] == null) {
                        continue;
                    }
                    title = result[1];
                    version = result[0];
                }

                ContentValues cv = new ContentValues();
                cv.put(ApplicationsColumns.DATA, data);
                cv.put(ApplicationsColumns.SIZE, f.length());
                cv.put(ApplicationsColumns.TITLE, title);
                cv.put(ApplicationsColumns.MIME_TYPE, Constants.MIME_TYPE_ANDROID_PACKAGE_ARCHIVE);
                cv.put(ApplicationsColumns.VERSION, version);
                cv.put(ApplicationsColumns.PACKAGE_NAME, packageName);

                ContentResolver cr = context.getContentResolver();

                Uri uri = cr.insert(Applications.Media.CONTENT_URI, cv);

                if (appInfo.icon != 0) {
                    try {
                        InputStream is = null;
                        OutputStream os = null;

                        try {
                            is = apk.openRawResource(appInfo.icon);
                            os = cr.openOutputStream(uri);

                            byte[] buff = new byte[4 * 1024];
                            int n = 0;
                            while ((n = is.read(buff, 0, buff.length)) != -1) {
                                os.write(buff, 0, n);
                            }

                        } finally {
                            if (os != null) {
                                os.close();
                            }
                            if (is != null) {
                                is.close();
                            }
                        }
                    } catch (Throwable e) {
                        Log.e(TAG, "Can't retrieve icon image for application " + appInfo.packageName);
                    }
                }
            } catch (Throwable e) {
                Log.e(TAG, "Error retrieving information for application " + appInfo.packageName);
            }
        }

        // clean uninstalled applications
        String[] newPackages = newPackagesList.toArray(new String[0]);
        Arrays.sort(newPackages);

        // simple way n * log(n)
        for (int i = 0; i < packagesSize; i++) {
            String packageName = packages[i];
            if (Arrays.binarySearch(newPackages, packageName) < 0) {
                ContentResolver cr = context.getContentResolver();
                cr.delete(Applications.Media.CONTENT_URI,
                        ApplicationsColumns.PACKAGE_NAME + " LIKE '%" + packageName + "%'", null);
            }
        }

    } catch (Throwable e) {
        Log.e(TAG, "Error performing initial applications provider synchronization with device", e);
    }
}

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

@Override
public int getIndexFor(double scan_acquisition_time) {
    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);
        }//from  w  w  w  .ja  va2s  . co  m
        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;
        }
    }
}

From source file:de.tap.easy_xkcd.utils.PrefHelper.java

public boolean checkWhatIfFav(int number) {
    String fav = sharedPrefs.getString(WHATIF_FAV, "");
    if (fav.equals("")) {
        return false;
    }/*from w ww .  j  a va  2 s.  c o m*/
    String[] favList = Favorites.sortArray(fav.split(","));
    int[] favInt = new int[favList.length];
    for (int i = 0; i < favInt.length; i++) {
        favInt[i] = Integer.parseInt(favList[i]);
    }
    int a = Arrays.binarySearch(favInt, number);
    return (a >= 0);
}

From source file:de.tap.easy_xkcd.utils.PrefHelper.java

public void removeWhatifFav(int number) {
    String[] old = sharedPrefs.getString(WHATIF_FAV, "").split(",");
    old = Favorites.sortArray(old);/*  w  w w .ja  v a  2  s  .  c  om*/
    int[] oldInt = new int[old.length];
    for (int i = 0; i < old.length; i++) {
        oldInt[i] = Integer.parseInt(old[i]);
    }
    int a = Arrays.binarySearch(oldInt, number);
    String[] out = new String[old.length - 1];
    Log.d("favorites", sharedPrefs.getString(WHATIF_FAV, ""));
    Log.d("a", String.valueOf(a));
    if (out.length != 0 && a >= 0) {
        System.arraycopy(old, 0, out, 0, a);
        System.arraycopy(old, a + 1, out, a, out.length - a);
        StringBuilder sb = new StringBuilder();
        sb.append(out[0]);
        for (int i = 1; i < out.length; i++) {
            sb.append(",");
            sb.append(out[i]);
        }
        SharedPreferences.Editor editor = sharedPrefs.edit();
        editor.putString(WHATIF_FAV, sb.toString());
        editor.commit();
    } else {
        SharedPreferences.Editor editor = sharedPrefs.edit();
        editor.putString(WHATIF_FAV, "");
        editor.commit();
    }

}

From source file:org.apache.fop.complexscripts.scripts.ArabicScriptProcessor.java

private static boolean hasIsolateInitial(int ch) {
    return Arrays.binarySearch(isolatedInitials, ch) >= 0;
}

From source file:info.magnolia.cms.filters.RangeSupportFilter.java

private boolean matches(String matchHeader, String toMatch) {
    String[] matchValues = matchHeader.split("\\s*,\\s*");
    Arrays.sort(matchValues);//  w  w w  .j ava 2 s  .c o m
    return Arrays.binarySearch(matchValues, toMatch) > -1 || Arrays.binarySearch(matchValues, "*") > -1;
}

From source file:edu.jhuapl.bsp.detector.OpenMath.java

public static double interp1(double[] list1, double[] list2, double x) {
    int i = Arrays.binarySearch(list1, x);
    if (i >= 0) {
        return list2[i];
    } // found the element
    i = -(i + 1) - 1; // not found, adjust the insertion point
    if (i == 0) {
        return list2[0];
    } else if (i >= list1.length) {
        return list2[list2.length - 1];
    } else {//from  w w  w.  j  a  va 2  s.  c  om
        return (x - list1[i]) * ((list2[i + 1] - list2[i]) / (list1[i + 1] - list1[i])) + list2[i];
    }
}