/** * Private helper method for performing fast intersection. * * @param <E> * @param sortedData * @param sortedQueries * @param result */ private static <E extends Comparable<E>> void fastIntersect( List<E> sortedData, List<E> sortedQueries, SortedSet<E> result) { int medianQueryIndex = sortedQueries.size() / 2; E medianQuery = sortedQueries.get(medianQueryIndex); int index = Collections.binarySearch(sortedData, medianQuery); if (index >= 0) { result.add(medianQuery); } else { index = (-1 * index) + 1; } if (index - 1 >= 0 && medianQueryIndex - 1 >= 0) { fastIntersect( sortedData.subList(0, index), sortedQueries.subList(0, medianQueryIndex), result); } if (index + 1 < sortedData.size() && medianQueryIndex + 1 < sortedQueries.size()) { fastIntersect( sortedData.subList(index + 1, sortedData.size()), sortedQueries.subList(medianQueryIndex + 1, sortedQueries.size()), result); } }
@Override public void databaseChanged(DatabaseChangeEvent e) { synchronized (set) { int pos; switch (e.getType()) { case ADDED_ENTRY: pos = -Collections.binarySearch(set, e.getEntry(), comp) - 1; set.add(pos, e.getEntry()); // addEntry(e.getEntry()); // set.add(e.getEntry()); // changed = true; // Collections.sort(set, comp); break; case REMOVED_ENTRY: set.remove(e.getEntry()); changed = true; break; case CHANGED_ENTRY: // Entry changed. Resort list: // Collections.sort(set, comp); pos = Collections.binarySearch(set, e.getEntry(), comp); int posOld = set.indexOf(e.getEntry()); if (pos < 0) { set.remove(posOld); set.add(-pos - 1, e.getEntry()); } // changed = true; break; } } }
public boolean insert(Record r, String tableName) { int tableSearchIndex = Collections.binarySearch(this.tableNames, tableName); if (tableSearchIndex < 0) { // make new table if necessary tableSearchIndex = -tableSearchIndex - 1; this.tableNames.add(tableSearchIndex, tableName); this.rowStorage.add(tableSearchIndex, new ArrayList<Record>()); this.columnIDNumbers.add(tableSearchIndex, new ArrayList<IDNumber>()); this.columnClientNames.add(tableSearchIndex, new ArrayList<ClientName>()); this.columnPhoneNumbers.add(tableSearchIndex, new ArrayList<PhoneNumber>()); this.inMemoryRow.add(tableSearchIndex, new ArrayList<Boolean>()); this.inMemoryColumnIDN.add(tableSearchIndex, new ArrayList<Boolean>()); this.inMemoryColumnCN.add(tableSearchIndex, new ArrayList<Boolean>()); this.inMemoryColumnPN.add(tableSearchIndex, new ArrayList<Boolean>()); } int binSearchIndex = -Collections.binarySearch(this.rowStorage.get(tableSearchIndex), r) - 1; if (binSearchIndex < 0) { // skip records with same ID return false; } this.rowStorage.get(tableSearchIndex).add(binSearchIndex, r); this.inMemoryRow.get(tableSearchIndex).add(binSearchIndex, new Boolean(false)); this.columnIDNumbers.get(tableSearchIndex).add(binSearchIndex, r.id); this.inMemoryColumnIDN.get(tableSearchIndex).add(binSearchIndex, new Boolean(false)); this.columnClientNames.get(tableSearchIndex).add(binSearchIndex, r.clientName); this.inMemoryColumnCN.get(tableSearchIndex).add(binSearchIndex, new Boolean(false)); this.columnPhoneNumbers.get(tableSearchIndex).add(binSearchIndex, r.phoneNumber); this.inMemoryColumnPN.get(tableSearchIndex).add(binSearchIndex, new Boolean(false)); return true; }
@Override public boolean process() { uniqueRows = new ArrayList<K>(new HashSet<K>(rows)); Collections.sort(uniqueRows); uniqueCols = new ArrayList<J>(new HashSet<J>(cols)); Collections.sort(uniqueCols); final List<Assignment> assignments = new ArrayList<Assignment>(costs.length); for (int i = 0; i < costs.length; i++) { final K rowObj = rows.get(i); final J colObj = cols.get(i); final int r = Collections.binarySearch(uniqueRows, rowObj); final int c = Collections.binarySearch(uniqueCols, colObj); assignments.add(new Assignment(r, c, costs[i])); } Collections.sort(assignments); // Test we do not have duplicates. Assignment previousAssgn = assignments.get(0); for (int i = 1; i < assignments.size(); i++) { final Assignment assgn = assignments.get(i); if (assgn.equals(previousAssgn)) { errorMessage = BASE_ERROR_MESSAGE + "Found duplicate assignment at index: " + assgn + "."; return false; } previousAssgn = assgn; } final int nRows = uniqueRows.size(); final int nCols = uniqueCols.size(); final int[] kk = new int[costs.length]; final int[] number = new int[nRows]; final double[] cc = new double[costs.length]; Assignment a = assignments.get(0); kk[0] = a.c; cc[0] = a.cost; int currentRow = a.r; int nOfEl = 0; for (int i = 1; i < assignments.size(); i++) { a = assignments.get(i); kk[i] = a.c; cc[i] = a.cost; nOfEl++; if (a.r != currentRow) { number[currentRow] = nOfEl; nOfEl = 0; currentRow = a.r; } } number[currentRow] = nOfEl + 1; scm = new SparseCostMatrix(cc, kk, number, nCols); alternativeCost = computeAlternativeCosts(); return true; }
public static void main(String[] args) { List numL = Arrays.asList(5, 10, -5, -10); Collections.sort(numL); int v1 = Collections.binarySearch(numL, 5); int v2 = Collections.binarySearch(numL, 4); System.out.println(v1 + v2); }
private void search(File currentDirectory) { FileTreeIterator iter = new FileTreeIterator(currentDirectory); while (iter.hasNext()) { File file = iter.next(); boolean accept = fileFilter.accept(file); synchronized (FileList.this) { if (searchID == searchCounter.get()) { if (accept) { int i = searchConstraints == null ? Collections.binarySearch(fileList, file) : Collections.binarySearch(fileList, file, searchConstraints); if (i >= 0) { // already exists? great } else { fileList.add(-i - 1, file); } } } else { return; } } } }
private void parseFile(String filename) throws IOException { BufferedReader fileIn = new BufferedReader(new FileReader(filename)); String line; // some persistent loop variables int tempo = 120; int key = 0; int timesig = 4; int measure = 0; while ((line = fileIn.readLine()) != null) { // we assume that listOfNotes is sorted. if (line.charAt(0) == '#' || line.equals("")) continue; String[] lineTokens = line.split(" "); switch (lineTokens[0]) { case "tempo": tempo = Integer.valueOf(lineTokens[1]); continue; case "key": key = Integer.valueOf(lineTokens[1]); continue; case "timesig": timesig = Integer.valueOf(lineTokens[1]); // put timesig into the global list Vector<Integer> measureSig = new Vector<Integer>(2); measureSig.add(measure); measureSig.add(timesig); this.timesigChanges.add( measureSig); // note that this always preserves order, as measure is monotone // increasing continue; case "measure": measure = Integer.valueOf(lineTokens[1]) - 1; continue; } // now assuming the note start duration format String noteVal = keyTransform(lineTokens[0], key); double start = Double.valueOf(lineTokens[1]) + measure * timesig; double end = start + Double.valueOf(lineTokens[2]); // create two new NoteBeat nodes for start and end in case we need them NoteBeat startNote = new NoteBeat(start, tempo); NoteBeat endNote = new NoteBeat(end, tempo); // look for the start and the end in the list of preexisting ones int startPosition = Collections.binarySearch(this.listOfBeats, startNote); // process them if (startPosition < 0) { // insert new node into arraylist startNote.addNoteOn(noteVal); this.listOfBeats.add(-startPosition - 1, startNote); } else { // add this note to the noteOn list in pre-existing node this.listOfBeats.get(startPosition).addNoteOn(noteVal); } int endPosition = Collections.binarySearch(this.listOfBeats, endNote); if (endPosition < 0) { endNote.addNoteOff(noteVal); this.listOfBeats.add(-endPosition - 1, endNote); } else { this.listOfBeats.get(endPosition).addNoteOff(noteVal); } } }
@SuppressWarnings({"rawtypes", "unchecked"}) private void externalizeMap(LinkedHashMap map, ObjectOutput out) throws IOException { int keyType = 0, valueType = 1, size; Iterator<Entry> it; Iterator cit; Entry e; Object value; if (map == null) { out.writeInt(0); out.flush(); return; } size = map.keySet().size(); if (map.keySet().iterator().next().getClass().equals(String.class)) { keyType = 1; } cit = map.values().iterator(); value = cit.next(); if (((ArrayList) value).get(0).getClass().equals(Commit.class)) { valueType = 0; } else if (((ArrayList) value).get(0).getClass().equals(PersonFrequency.class)) { valueType = 2; } out.writeInt(size); out.writeInt(keyType); out.writeInt(valueType); it = map.entrySet().iterator(); while (it.hasNext()) { e = it.next(); out.writeInt(((ArrayList) e.getValue()).size()); cit = ((ArrayList) e.getValue()).iterator(); while (cit.hasNext()) { value = cit.next(); switch (valueType) { case 0: out.writeInt(Collections.binarySearch(allCommits, ((Commit) value))); break; case 1: out.writeInt(((BranchRef) value).index); break; default: out.writeInt(((PersonFrequency) value).index); out.writeInt(((PersonFrequency) value).freq); out.writeLong(((PersonFrequency) value).since); out.writeLong(((PersonFrequency) value).until); } } switch (keyType) { case 0: out.writeInt(Collections.binarySearch(allCommits, (Commit) e.getKey())); break; case 1: out.writeUTF(((String) e.getKey())); } } out.flush(); }
/* ************************************************************ */ public List pesquisarEntreValores( List resultadoDaPesquisa, String nomeAtributoComparado, Comparator comparadorAtributo, Object valorInicial, Object valorFinal) { if (resultadoDaPesquisa != null) { // Configura o método get para obter os valores comparados String nomeMetodo = "get" + nomeAtributoComparado.substring(0, 1).toUpperCase() + nomeAtributoComparado.substring(1, nomeAtributoComparado.length()); // Ordena o resultado da pesquisa em ordem crescente dos valores do // atributo comparado: List resultado = new ArrayList(); resultado.addAll(resultadoDaPesquisa); Util.ordenarObjetos(resultado, comparadorAtributo); // Isola o conjunto de valores do atributo comparado em uma lista de // valores, que tem a mesma ordenação e tamanho da lista de objetos // do resultado da pesquisa: List valoresAtributoComparado = new ArrayList(); for (int i = 0; i < resultado.size(); i++) { valoresAtributoComparado.add(Util.executarMetodo(resultado.get(i), nomeMetodo, null)); } // Da lista de valores, recupera o primeiro que seja maior ou igual // a valorInicial: int indiceValorInicial = Collections.binarySearch(valoresAtributoComparado, valorInicial); if (indiceValorInicial < 0) { indiceValorInicial = -(indiceValorInicial + 1); } // Da lista de valores, recupera o último que seja menor ou igual a // valorFinal: int indiceValorFinal = Collections.binarySearch(valoresAtributoComparado, valorFinal); if (indiceValorFinal < 0) { indiceValorFinal = -(indiceValorFinal + 1); } else { indiceValorFinal++; } // Recupera os objetos entre indiceValorInicial e indiceValorFinal: resultado = resultado.subList(indiceValorInicial, indiceValorFinal); // Retorna os objetos que satisfazem aos critérios, caso existam if (resultado.size() > 0) { return resultado; } } return null; }
public static <T> void select(Population<T> population) { ArrayList<Individual<T>> pop = population.getPop(); ArrayList<Individual<T>> newPop = new ArrayList<Individual<T>>(); ArrayList<Double> probabilities = new ArrayList<Double>(); Individual<T> parent1; Individual<T> parent2; Individual<T> child1; Individual<T> child2; double totalFitness = 0; double rnd; int popSize = Config.POP_SIZE.getIntValue(); int index; if (Config.MIN.isEnabled()) { Collections.sort(pop, Collections.reverseOrder()); } else if (Config.MAX.isEnabled()) { Collections.sort(pop); } for (Individual<T> in : pop) { totalFitness += in.getFitness(); } for (Individual<T> in : pop) { probabilities.add(in.getFitness() / totalFitness); } while (newPop.size() < popSize) { rnd = Math.random(); index = Math.abs(Collections.binarySearch(probabilities, rnd)) - 1; if (index == probabilities.size()) { index -= 1; } parent1 = pop.get(index); rnd = Math.random(); index = Math.abs(Collections.binarySearch(probabilities, rnd)) - 1; if (index == probabilities.size()) { index -= 1; } parent2 = pop.get(index); child1 = parent1.cross(parent2); child2 = parent2.cross(parent1); child1.mutate(); child2.mutate(); newPop.add(child1); newPop.add(child2); } population.setPop(newPop); }
public Record retrieve(IDNumber id, String tableName) { int tableSearchIndex = Collections.binarySearch(this.tableNames, tableName); if (tableSearchIndex < 0) { return null; } int binSearchIndex = Collections.binarySearch(this.columnIDNumbers.get(tableSearchIndex), id); if (binSearchIndex < 0) { return null; } return this.rowStorage.get(tableSearchIndex).get(binSearchIndex); }
private boolean alterCacheStatusRecordOnly(Record r, String tableName, boolean status) { int tableSearchIndex = Collections.binarySearch(this.tableNames, tableName); if (tableSearchIndex < 0) { return false; } int binSearchIndex = Collections.binarySearch(this.rowStorage.get(tableSearchIndex), r); if (binSearchIndex < 0) { return false; } this.inMemoryRow.get(tableSearchIndex).set(binSearchIndex, status); return true; }
public boolean checkInStorage(Record r, String tableName) { // return this.checkInStorage(r.id, tableName) && this.checkInStorage(r.clientName, tableName) // && this.checkInStorage(r.phoneNumber, tableName); int tableSearchIndex = Collections.binarySearch(this.tableNames, tableName); if (tableSearchIndex < 0) { return false; } int binSearchIndex = Collections.binarySearch(this.rowStorage.get(tableSearchIndex), r); if (binSearchIndex < 0) { return false; } return this.inMemoryRow.get(tableSearchIndex).get(binSearchIndex); }
/** * 由母库数据建立0层路网 * * @param task * @param data * @throws Exception */ public void fromDB() throws Exception { List<String> meshNos = DataManager.getMeshNos(this.taskData.task); TeleDao teleDao = new TeleDao(); Session session = TeleHbSessionFactory.getOrgHbSession(this.taskData.task.getLevel()).getSession(); List<NodeNew> meshBorderNodeList = new ArrayList<NodeNew>(); for (String meshNo : meshNos) { List<Node> node_oList = teleDao.getNodeList(meshNo, session); List<NodeNew> nodeList = new ArrayList<NodeNew>(node_oList.size()); // 读取关系节点 for (Node node_o : node_oList) { NodeNew nodeNew = new NodeNew(); nodeNew.convert(node_o); if (node_o.getByistaskborder() == NodeType.meshBorder) { meshBorderNodeList.add(nodeNew); } nodeList.add(nodeNew); } this.nodeList.addAll(nodeList); Collections.sort(nodeList, comparableNodeId); // 读取道路 List<Road> roadList = teleDao.getRoadList(meshNo, session); for (Road road_O : roadList) { RoadNew road = new RoadNew(); // 属性赋值,正规化计算 road.convert(this, road_O); this.roadList.add(road); // 建立拓扑关系 // add node to road int indexStart = Collections.binarySearch(nodeList, road.startNode, comparableNodeId); road.startNode = nodeList.get(indexStart); int indexEnd = Collections.binarySearch(nodeList, road.endNode, comparableNodeId); road.endNode = nodeList.get(indexEnd); // add road to node road.startNode.roads.add(road); road.endNode.roads.add(road); } // 读取复杂路口 List<Intersection_O> intersectionList = teleDao.getIntersectionList(meshNo, session); for (Intersection_O intersection_O : intersectionList) { IntersectionNew intersection = new IntersectionNew(); intersection.convert(this, intersection_O); this.intersectionList.add(intersection); } } // 建立mesh边界的拓扑关系 this.makeBorderTopo(meshBorderNodeList); // }
@Override protected void onPostExecute(SocialTwitterApi.GetRequest api) { super.onPostExecute(api); if (isDetached() || getActivity() == null) { return; } if (api.isSuccessful()) { ArrayList<FeedTwitterStatus> feed = api.getResponseObj().getStatusList(); Collections.sort(feed); if (mTweetList.size() == 0) { // 新規取得 mTweetList.addAll(feed); } else { FeedTwitterStatus latestTweet = mTweetList.get(0); // 取得済みの最新ツイートより新しいものを追加 int index = Collections.binarySearch(feed, latestTweet); if (index > 0) { mTweetList.addAll(0, feed.subList(0, index)); } else if (index < 0) { // indexが-1の時全部最新ツイート // -2以下の場合がないと想定 Timber.d("onPostExecute: latestTweetIndex in new feed" + index); mTweetList.addAll(0, feed); } else { Timber.d("onPostExecute: already added"); } } mAdapter.notifyDataSetChanged(); } mSwipeRefreshLayout.setRefreshing(false); }
public static void main(String[] args) { ArrayList nums = new ArrayList(); nums.add(2); nums.add(-5); nums.add(3); nums.add(0); // 输出:[2, -5, 3, 0] System.out.println(nums); // 输出最大元素,将输出3 System.out.println(Collections.max(nums)); // 输出最小元素,将输出-5 System.out.println(Collections.min(nums)); // 将nums中的0使用1来代替 Collections.replaceAll(nums, 0, 1); // 输出:[2, -5, 3, 1] System.out.println(nums); // 判断-5 在List集合中出现的次数,返回1 System.out.println(Collections.frequency(nums, -5)); // 对nums集合排序 Collections.sort(nums); // 输出:[-5, 1, 2, 3] System.out.println(nums); // 只有排序后的List集合才可用二分法查询,输出3 System.out.println(Collections.binarySearch(nums, 3)); }
@SuppressWarnings({"rawtypes", "unchecked"}) private LinkedHashMap computePersonFreq(LinkedHashMap map) { if (map == null) return null; ArrayList<PersonFrequency> values; ArrayList ev; LinkedHashMap res = new LinkedHashMap<Object, ArrayList<PersonFrequency>>(map.size(), 1); Entry e; Set<Entry> es = map.entrySet(); Iterator<Entry> esit = es.iterator(); Iterator<Commit> evit; PersonFrequency p; long pTs; Commit c; int i; while (esit.hasNext()) { e = esit.next(); ev = (ArrayList) e.getValue(); evit = ev.iterator(); values = new ArrayList<PersonFrequency>(ev.size()); while (evit.hasNext()) { c = evit.next(); pTs = c.getCommittingInfo().getWhen().getTime(); i = Collections.binarySearch(allAuthors, c.getAuthoringInfo()); p = new PersonFrequency(i); i = GitWorks.addUnique(values, p); p = values.get(i); p.freq++; if (p.since > pTs) p.since = pTs; if (p.until < pTs) p.until = pTs; } values.trimToSize(); res.put(e.getKey(), values); } return res; }
private Object[] getFromCache(RowMetaInterface keyMeta, Object[] keyData) throws KettleValueException { if (meta.isMemoryPreservationActive()) { if (meta.isUsingSortedList()) { KeyValue keyValue = new KeyValue(keyData, null); int idx = Collections.binarySearch(data.list, keyValue, data.comparator); if (idx < 0) return null; // nothing found keyValue = (KeyValue) data.list.get(idx); return keyValue.getValue(); } else { if (meta.isUsingIntegerPair()) { Long value = data.longIndex.get(keyMeta.getInteger(keyData, 0)); if (value == null) return null; return new Object[] { value, }; } else { try { byte[] value = data.hashIndex.get(RowMeta.extractData(keyMeta, keyData)); if (value == null) return null; return RowMeta.getRow(data.valueMeta, value); } catch (Exception e) { logError("Oops", e); throw new RuntimeException(e); } } } } else { return (Object[]) data.look.get(new RowMetaAndData(keyMeta, keyData)); } }
/** ************************ TEST ACCESS ******************************************* */ @Test public void testSearchIterator() throws InterruptedException { final int perTreeSelections = 100; testRandomSelection( perThreadTrees, perTreeSelections, (test) -> { IndexedSearchIterator<Integer, Integer> iter1 = test.testAsSet.iterator(); IndexedSearchIterator<Integer, Integer> iter2 = test.testAsList.iterator(); return (key) -> { Integer found1 = iter1.hasNext() ? iter1.next(key) : null; Integer found2 = iter2.hasNext() ? iter2.next(key) : null; Assert.assertSame(found1, found2); if (found1 != null) Assert.assertEquals(iter1.indexOfCurrent(), iter2.indexOfCurrent()); int index = Collections.binarySearch(test.canonicalList, key, test.comparator); if (index < 0) { Assert.assertNull(found1); } else { Assert.assertEquals(key, found1); Assert.assertEquals(index, iter1.indexOfCurrent()); } // check that by advancing the same key again we get null, but only do it on one of the // two iterators // to ensure they both advance differently if (ThreadLocalRandom.current().nextBoolean()) Assert.assertNull(iter1.next(key)); else Assert.assertNull(iter2.next(key)); }; }); }
/** * Sorts the rows of the table alphabetically. * * @param column index of the column to sort. In this table there are only 2 columns. */ public void sort(int column) { // Orders the layer alphabetically according the Spanish // alphabetically rules switch (column) { case 0: stringComparator.setColumn(WFSLayerStringComparator.LAYER_NAME); break; case 1: stringComparator.setColumn(WFSLayerStringComparator.GEOMETRY_TYPE); break; } if (previousColumnSorted != column) stringComparator.setAscendingOrdering(true); previousColumnSorted = (short) column; WFSLayerNode layer = getSelectedValue(); Collections.sort(layers, stringComparator); if (layer != null) { updatingSelection = true; unselectAllFeatures(); int row = Collections.binarySearch(layers, layer, stringComparator); if (row != -1) { ListSelectionModel model = getSelectionModel(); model.setLeadSelectionIndex(row); } updatingSelection = false; } stringComparator.setAscendingOrdering(!stringComparator.isAscendingOrdering()); }
/** * Recalculate the prefix border following an i-extension * * @param prefixLastItemset last itemset of the previous prefix * @param prefixBorder the previous prefix border * @param item1 the last item * @param item2 the item that will be appended * @param willAddSecondItem if the item will be added to an itemset containing a single item * @return the updated border */ private List<Position> recalculateBorderForIExtension( List<Integer> prefixLastItemset, List<Position> prefixBorder, int item1, int item2, boolean willAddSecondItem) { // Create the new border (a list of position) List<Position> newBorder = new ArrayList<Position>(); // for each sequence where the prefix appeared for (Position previousPosition : prefixBorder) { int sid = previousPosition.sid; // get where the last two items of the prefix appeared int previousItemsetID = previousPosition.position; IEPositionList positionLists = iePositionList[sid]; // find the position that is immediately larger or equal than the current one // by checking each position in the list of positions for the pair List<Short> listPositions = positionLists.getListForPair(item1, item2); if (listPositions != null) { // for each position loop: for (short pos : listPositions) { // if the position is larger or equal to the current one if (pos >= previousItemsetID) { // IMPORTANT: // if the prefix has two items in its last itemset, // then we also need to check that the full last itemset of prefix is at the current // position // This will not be done very optimally but it is it difficult to do a better solution. if (willAddSecondItem == false) { // We take the SE position list of the current sequence SEPositionList plists = sePositionList[sid]; // For each item of the last itemset of the prefix for (int i = 0; i < prefixLastItemset.size() - 1; i++) { // We check if that item appears at that position Integer itemX = prefixLastItemset.get(i); List<Short> plistX = plists.getListForItem(itemX); int index = Collections.binarySearch(plistX, pos); // if not, then we stop considering this position if (index < 0) { continue loop; } } // If the loop has finished, that means that all items from the last itemset of // the prefix have appeared at the position pos } // Then we add the position to the new border Position newPosition = new Position(sid, pos); newBorder.add(newPosition); // After that we will continue to the next sequence to continue creating the new border break; } } } } return newBorder; }
void removeBreakpoint(Breakpoint breakpoint) { String templateName = breakpoint.getTemplateName(); synchronized (templateDebugInfos) { TemplateDebugInfo tdi = findTemplateDebugInfo(templateName); if (tdi != null) { List breakpoints = tdi.breakpoints; int pos = Collections.binarySearch(breakpoints, breakpoint); if (pos >= 0) { breakpoints.remove(pos); for (Iterator iter = tdi.templates.iterator(); iter.hasNext(); ) { TemplateReference ref = (TemplateReference) iter.next(); Template t = ref.getTemplate(); if (t == null) { iter.remove(); } else { removeDebugBreak(t, breakpoint); } } } if (tdi.isEmpty()) { templateDebugInfos.remove(templateName); } } } }
/** * Random selection ("sampling") of a record out of the sample * * @return index of the record selected * @throws ArrayIndexOutOfBoundsException internal error - returned index larger than number of * records in sample */ public int randomSample() throws ArrayIndexOutOfBoundsException { Random r = new Random(); // generate random number for sampling int sampleThreshold = 1; if (maxThreshold == 0) { // TODO: need a good workaround for this or an assert // This occurs when all thresholds = 0 because of rounding. Usually this disappears // when the distribution (thresholds) are multiplied by 100 or 1000. System.out.println("Problem: maxThreshold = 0"); // return 0; } else { sampleThreshold = (int) maxThreshold; } long rand = (long) r.nextInt(sampleThreshold); // lookup index of element where random number falls within the boundaries int index = Collections.binarySearch(thresholdStore, rand); if (index < 0) index = (index + 1) * -1; assert index < thresholdStore.size() : "Array index too large; rand = " + rand + ", max threshold = " + maxThreshold + ", index = " + index + ", max index = " + thresholdStore.size(); return index; }
private int searchSubregionTile(RouteSubregion subregion) { RoutingSubregionTile key = new RoutingSubregionTile(subregion); long now = System.nanoTime(); int ind = Collections.binarySearch( subregionTiles, key, new Comparator<RoutingSubregionTile>() { @Override public int compare(RoutingSubregionTile o1, RoutingSubregionTile o2) { if (o1.subregion.left == o2.subregion.left) { return 0; } return o1.subregion.left < o2.subregion.left ? 1 : -1; } }); if (ind >= 0) { for (int i = ind; i <= subregionTiles.size(); i++) { if (i == subregionTiles.size() || subregionTiles.get(i).subregion.left > subregion.left) { ind = -i - 1; return ind; } if (subregionTiles.get(i).subregion == subregion) { return i; } } } timeToLoadHeaders += (System.nanoTime() - now); return ind; }
public Token getSuccessor(Token token) { List tokens = sortedTokens(); int index = Collections.binarySearch(tokens, token); assert index >= 0 : token + " not found in " + StringUtils.join(tokenToEndPointMap.keySet(), ", "); return (Token) ((index == (tokens.size() - 1)) ? tokens.get(0) : tokens.get(index + 1)); }
public static void main(String args[]) { String os[] = {"GNU/Linux", "Windows 7", "Solaris", "Amiga OS", "FreeBSD", "Mac OS X"}; LinkedList<String> al_operating_systems = new LinkedList<>(Arrays.asList(os)); // Lista di os Collections.sort(al_operating_systems); // ordina la collezione System.out.print("Collezione ordinata: "); System.out.println(al_operating_systems); int ix = Collections.binarySearch( al_operating_systems, "Be OS", null); // ricerca se presente l'elemento Be Os if (ix < 0) // se non è presente aggiungilo al_operating_systems.add(-(ix + 1), "Be OS"); System.out.print("Collezione con elemento Be OS aggiunto: "); System.out.println(al_operating_systems); Collections.rotate(al_operating_systems, 3); // ruota gli elementi di 3 posizioni System.out.print("Collezione con elementi ruotati: "); System.out.println(al_operating_systems); System.out.print("Elemento della collezione minore: ["); // elemento più piccolo System.out.println(Collections.min(al_operating_systems) + "]"); System.out.print("Elemento della collezione maggiore: ["); // elemento più grande System.out.println(Collections.max(al_operating_systems) + "]"); }
@Override public void addSubattribute(Attribute attribute) { AttributeImpl attributeImpl = (AttributeImpl) attribute; // The attribute is bound and has to be removed from its parent (informationobject or parent // attribute if (attributeImpl.getInformationObject() != null || attributeImpl.getParentAttribute() != null) { if (attributeImpl.getParentAttribute() != null) { attributeImpl.getParentAttribute().removeSubattribute(attributeImpl); } else { attributeImpl.getInformationObject().removeAttribute(attributeImpl); } } attributeImpl.setParentAttribute(this); int index = Collections.binarySearch(subattributes, attributeImpl); if (index < 0) { subattributes.add(-index - 1, attributeImpl); } else { subattributes.add(index, attributeImpl); } if (parentAttribute != null) { ((AttributeImpl) parentAttribute).resortAttributes(); } if (informationObject != null) { ((InformationObjectImpl) informationObject).resortAttributes(); } }
/** * Checks if this sensitivity equals another within the specified tolerance. * * <p>This returns true if the two instances have the same keys, with arrays of the same length, * where the {@code double} values are equal within the specified tolerance. * * @param other the other sensitivity * @param tolerance the tolerance * @return true if equal up to the tolerance */ public boolean equalWithTolerance(CurveCurrencyParameterSensitivities other, double tolerance) { List<CurveCurrencyParameterSensitivity> mutable = new ArrayList<>(other.sensitivities); // for each sensitivity in this instance, find matching in other instance for (CurveCurrencyParameterSensitivity sens1 : sensitivities) { // list is already sorted so binary search is safe int index = Collections.binarySearch(mutable, sens1, CurveCurrencyParameterSensitivity::compareKey); if (index >= 0) { // matched, so must be equal CurveCurrencyParameterSensitivity sens2 = mutable.get(index); if (!DoubleArrayMath.fuzzyEquals( sens1.getSensitivity(), sens2.getSensitivity(), tolerance)) { return false; } mutable.remove(index); } else { // did not match, so must be zero if (!DoubleArrayMath.fuzzyEqualsZero(sens1.getSensitivity(), tolerance)) { return false; } } } // all that remain from other instance must be zero for (CurveCurrencyParameterSensitivity sens2 : mutable) { if (!DoubleArrayMath.fuzzyEqualsZero(sens2.getSensitivity(), tolerance)) { return false; } } return true; }
/** * Searches for the index of a given element * * @param e the element * @return the index or -1 if the list does not contain this element */ public int indexOf(E e) { int index = Collections.binarySearch(_list, e, _comp); if (index < 0) { return -1; } return index; }
/** * Returns the row index for a given key. * * @param key the key. * @return the row index. */ public int getRowIndex(Comparable key) { if (this.sortRowKeys) { return Collections.binarySearch(this.rowKeys, key); } else { return this.rowKeys.indexOf(key); } }