/* * Takes a set of sketch nodes, and returns an ArrayList<Integer> such that * arr.get(i) gives the index of the sketch node that node i is closest too. * * Need to work the return values a little bit. Make a proper data * structure. */ public ArrayList<ArrayList<Integer>> distSketch(int len, Counter sketchNodes) { ArrayList<Integer> closestIndex = new ArrayList<Integer>(); for (int i = 0; i < len; i++) closestIndex.set(i, -1); ArrayList<Double> closestDist = new ArrayList<Double>(); for (int i = 0; i < len; i++) closestDist.set(i, Double.MAX_VALUE); ArrayList<ArrayList<Integer>> sketchReverseIndex = new ArrayList<ArrayList<Integer>>(); for (int index : sketchNodes.keySet()) { Counter distances = this.bfs(index); for (int j = 0; j < len; j++) { double curDist = closestDist.get(j); double dist = distances.getPath(index); if (dist < curDist) { closestIndex.set(j, index); } } sketchReverseIndex.add(new ArrayList<Integer>()); } for (int j = 0; j < len; j++) { int closest = closestIndex.get(j); sketchReverseIndex.get(closest).add(j); } // Return sketchReverseIndex, closestIndex forward index, and index // correspondence bimap return sketchReverseIndex; }
public void sortFrontbyR(){ sortByR = new ArrayList(); for (int i = 0 ; i < Fronts.size() ; i++){ ArrayList tempfront = (ArrayList) Fronts.get(i); for (int j = 0 ; j < tempfront.size() ; j++){ for (int a = 0 ; a < tempfront.size() ; a++){ if (a > j){ NSGAII.Solutions.QRTPSolution.OneSolution first = (NSGAII.Solutions.QRTPSolution.OneSolution) tempfront.get(j); double x = first.getRecall(); NSGAII.Solutions.QRTPSolution.OneSolution second = (NSGAII.Solutions.QRTPSolution.OneSolution) tempfront.get(a); double y = second.getRecall(); if (y > x){ tempfront.set(j, second); tempfront.set(a, first); }else{} } } } sortByR.add(tempfront); } }
public int partition(int[] array, int index) { // the basics ArrayList<Integer> source = new ArrayList<Integer>(); for (int c : array) source.add(new Integer(c)); int wall = 0; int wall2 = 1; Integer pivot = source.get(index); // the switch source.set(index, source.get(source.size() - 1)); source.set(source.size() - 1, pivot); // the loop Integer store = new Integer(0); for (int x = 0; x < source.size() - 1; x++) { if (source.get(x).compareTo(pivot) < 0) { swap(source, wall, x); wall++; wall2++; } else if (source.get(x).compareTo(pivot) == 0) { swap(source, wall2, x); wall2++; } // System.out.println(Arrays.toString(source.toArray())); } // the switch 2.0 swap(source, wall, source.size() - 1); for (int x = 0; x < source.size(); x++) array[x] = source.get(x).intValue(); return wall; }
private static void getTopDocuments(int num, HashMap<String, Float> scoremap, String filename) throws FileNotFoundException { PrintWriter out = new PrintWriter(filename); Iterator<String> itr = scoremap.keySet().iterator(); ArrayList<String> urls = new ArrayList<String>(); ArrayList<Float> scores = new ArrayList<Float>(); while (itr.hasNext()) { String key = itr.next(); if (scores.size() < num) { scores.add(scoremap.get(key)); urls.add(key); } else { int index = scores.indexOf(Collections.min(scores)); if (scores.get(index) < scoremap.get(key)) { scores.set(index, scoremap.get(key)); urls.set(index, key); } } } while (scores.size() > 0) { int index = scores.indexOf(Collections.max(scores)); out.println(urls.get(index) + "\t" + scores.get(index)); urls.remove(index); scores.remove(index); } out.close(); }
// Executes the given action public void executeAction(Action a) { // For each state variable, retrieve the DD for it, evaluate it // w.r.t. the current state and build a new state. ArrayList new_state = new ArrayList(); int c; for (c = 0; c < (_nVars << 1); c++) { new_state.add("-"); } for (c = 0; c < (_nVars << 1); c++) { Object cur_assign = _state.get(c); if (cur_assign instanceof Boolean) { // System.out.println(a._tmID2DD); int nonprime_id = c + 1; int prime_id = nonprime_id - _nVars; Object DD = a._tmID2DD.get(new Integer(prime_id)); _state.set(prime_id - 1, TRUE); double p_true = _mdp._context.evaluate(DD, _state); // System.out.println("ID: " + nonprime_id + ", " + prime_id + ": " + // _mdp._context.printNode(DD) + " -> " + // _mdp._df.format(p_true)); new_state.set(c, (_r.nextFloat() < p_true) ? TRUE : FALSE); } } _state = new_state; }
public String toString(Molecule molecule) { // write header String returnString = String.format( "%%mem=%dGB\n%%nprocshared=%d\n#p geom=connect %s/genecp empiricaldispersion=gd3bj opt\n", mem, nprocshared, method); returnString += "\ntitle\n\n0 1\n"; // write geometry returnString = returnString + molecule.getGJFstring() + "\n"; // initialize some variables Atom fromAtom = null; Atom toAtom = null; Integer fromAtomNumber = 0; Integer toAtomNumber = 0; Double bondOrder = 0.0; DefaultWeightedEdge thisEdge = null; // read connectivity data into parallel arrays ArrayList<Integer> fromAtoms = new ArrayList<Integer>(); ArrayList<Integer> toAtoms = new ArrayList<Integer>(); ArrayList<Double> bondOrders = new ArrayList<Double>(); ArrayList<Boolean> visited = new ArrayList<Boolean>(); for (DefaultWeightedEdge e : molecule.connectivity.edgeSet()) { fromAtom = molecule.connectivity.getEdgeSource(e); fromAtomNumber = molecule.contents.indexOf(fromAtom) + 1; toAtom = molecule.connectivity.getEdgeTarget(e); toAtomNumber = molecule.contents.indexOf(toAtom) + 1; bondOrder = molecule.connectivity.getEdgeWeight(e); fromAtoms.add(fromAtomNumber); toAtoms.add(toAtomNumber); bondOrders.add(bondOrder); visited.add(false); } // write connectivity data for (int i = 0; i < molecule.contents.size(); i++) { returnString = returnString + (i + 1) + " "; for (int j = 0; j < fromAtoms.size(); j++) { if (fromAtoms.get(j) == i + 1 && visited.get(j) == false) { returnString = returnString + toAtoms.get(j) + " " + String.format("%.1f ", bondOrders.get(j)); visited.set(j, true); } if (toAtoms.get(j) == i + 1 && visited.get(j) == false) { returnString = returnString + fromAtoms.get(j) + " " + String.format("%.1f ", bondOrders.get(j)); visited.set(j, true); } } returnString = returnString + "\n"; } // write footer returnString += String.format("\n@%s\n\n", basis); return returnString; }
public void toggleFavorite(int index) { Board t = getItem(index); t.favorite = !t.favorite; mDataShown.set(index, t); mAllData.set(mAllData.indexOf(t), t); Log.i("debug", "State : " + t.favorite); super.notifyDataSetChanged(); }
// shuffle elements of AL "varList" public void shuffle() { int randomIndex; for (int i = numVars - 1; i > 0; i--) { // pick an index at random randomIndex = (int) ((i + 1) * Math.random()); // swap the values at position i and randomIndex varList.set(i, varList.set(randomIndex, varList.get(i))); } }
static void shuffle(ArrayList keys) { int size = keys.size(); for (int i = size; i > 1; i--) { int r = rng.nextInt(i); Object t = keys.get(i - 1); keys.set(i - 1, keys.get(r)); keys.set(r, t); } }
public ArrayList<Integer> addPawnNum(Color color, ArrayList<Integer> pawnList) { for (int i = 0; i < COL_NUM; i++) { if (row.get(i).is(color, Piece.Type.PAWN)) { pawnList.set(i, pawnList.get(i) + 1); } else if (row.get(i).is(color, Piece.Type.PAWN)) { pawnList.set(i, pawnList.get(i) + 1); } } return pawnList; }
// Shuffles Arraylist like a deck of cards private static ArrayList<Restaurant> shuffle(ArrayList<Restaurant> places) { int j = 0; Restaurant temp = null; // Randomly swaps one index with another for (int i = 0; i < places.size(); i++) { j = ThreadLocalRandom.current().nextInt(0, i + 1); temp = places.get(j); places.set(j, places.get(i)); places.set(i, temp); } return places; }
private void reconstructMoves(SearchNode searcher) { while (searcher != null) { solution.add(searcher.getObject()); searcher = searcher.getParent(); } for (int i = 0; i < solution.size() / 2; ++i) { T temp = solution.get(i); int other = solution.size() - i - 1; solution.set(i, solution.get(other)); solution.set(other, temp); } }
public static ArrayList<Card> bubblesort(ArrayList<Card> cards) { for (int i = 1; i < cards.size(); i++) { for (int j = 0; j < cards.size() - 1; j++) { // comparing cards by rank if (cards.get(j).getRank() > cards.get(j + 1).getRank()) { Card tempcard = cards.get(j); cards.set(j, cards.get(j + 1)); cards.set(j + 1, tempcard); } } } return cards; }
public <T extends Comparable<T>> void sortList(ArrayList<T> arr) { int i, j; T newValue; for (i = 1; i < arr.size(); i++) { newValue = arr.get(i); j = i; while (j > 0 && arr.get(j - 1).compareTo(newValue) > 0) { arr.set(j, arr.get(j - 1)); j--; } arr.set(j, newValue); } }
/** Tokenize string s into an array */ public static String[] tokenize(String s) { ArrayList<String> r = new ArrayList<String>(); String remain = s; int n = 0, pos; remain = remain.trim(); while (remain.length() > 0) { if (remain.startsWith("\"")) { // Field in quotes pos = remain.indexOf('"', 1); if (pos == -1) break; r.add(remain.substring(1, pos)); if (pos + 1 < remain.length()) pos++; } else { // Space-separated field pos = remain.indexOf(' ', 0); if (pos == -1) { r.add(remain); remain = ""; } else r.add(remain.substring(0, pos)); } remain = remain.substring(pos + 1); remain = remain.trim(); // - is used as a placeholder for empy fields if (r.get(n).equals("-")) r.set(n, ""); n++; } return r.toArray(new String[0]); }
public int store(int offset) { int temp = pop(); runStack.set(offset, temp); return offset; }
public static void qsHelp(int lo, int hi, ArrayList<Book> d) { if (lo >= hi) return; int tmpLo = lo; int tmpHi = hi; Book pivot = d.get(lo); while (tmpLo < tmpHi) { // first, slide markers in as far as possible without swaps while (d.get(tmpLo).compareTo(pivot) < 0) { // System.out.println("2"); tmpLo++; } while (d.get(tmpHi).compareTo(pivot) > 0) { // System.out.println("3"); tmpHi--; } swap(tmpLo, tmpHi, d); } // pivot has been floating around... plant it where it belongs d.set(tmpLo, pivot); // recurse on lower and upper ranges qsHelp(lo, tmpLo - 1, d); qsHelp(tmpLo + 1, hi, d); } // end qsHelp
private void fixTabs(int tabSize) { int rowIndex = 0; for (StringBuilder row1 : rows) { String row = row1.toString(); StringBuilder newRow = new StringBuilder(); char[] chars = row.toCharArray(); for (char c : chars) { if (c == '\t') { int spacesLeft = tabSize - newRow.length() % tabSize; if (DEBUG) { System.out.println("Found tab. Spaces left: " + spacesLeft); } String spaces = StringUtils.repeatString(" ", spacesLeft); newRow.append(spaces); } else { String character = Character.toString(c); newRow.append(character); } } rows.set(rowIndex, newRow); rowIndex++; } }
public void setColor(int index, int color) { int old_color = m_colors.get((index + 4 - m_rotation) % 4); m_colors.set((index + 4 - m_rotation) % 4, color); m_hash_code -= old_color; m_hash_code += color; }
protected Collection<FileInfo> loadFileInfos(long fileId) { final ArrayList<FileInfo> infos = new ArrayList<FileInfo>(); while (fileId != -1) { final Cursor cursor = myDatabase.rawQuery( "SELECT name,size,parent_id FROM Files WHERE file_id = " + fileId, null); if (cursor.moveToNext()) { FileInfo info = createFileInfo(fileId, cursor.getString(0), null); if (!cursor.isNull(1)) { info.FileSize = cursor.getLong(1); } infos.add(0, info); fileId = cursor.isNull(2) ? -1 : cursor.getLong(2); } else { fileId = -1; } cursor.close(); } for (int i = 1; i < infos.size(); ++i) { final FileInfo oldInfo = infos.get(i); final FileInfo newInfo = createFileInfo(oldInfo.Id, oldInfo.Name, infos.get(i - 1)); newInfo.FileSize = oldInfo.FileSize; infos.set(i, newInfo); } return infos; }
public ChangeVO updateRow( int windowNo, int AD_Tab_ID, int queryResultID, int relRowNo, Map<String, String> context, boolean force) { if (context == null || context.size() == 0) return new ChangeVO(true, Msg.translate(m_context, "NoContext")); ArrayList<String[]> data = m_results.get(queryResultID); if (data == null || data.size() == 0) return new ChangeVO(true, Msg.translate(m_context, "CachedDataNotFound")); UITab tab = getTab(AD_Tab_ID); if (tab == null) { log.config("Not found AD_Tab_ID=" + AD_Tab_ID); return new ChangeVO(true, Msg.translate(m_context, "@NotFound@ @AD_Tab_ID@=" + AD_Tab_ID)); } CContext ctx = new CContext(m_context.entrySet()); ctx.addWindow(windowNo, context); ChangeVO retValue; if (force) retValue = tab.saveRow(ctx, windowNo, false, null); else retValue = tab.saveRow(ctx, windowNo, false, data.get(relRowNo)); if (retValue.hasError()) return retValue; // Update Results String[] dataRow = retValue.rowData.clone(); data.set(relRowNo, dataRow); postProcessChangeVO(retValue, windowNo, context, dataRow, tab); retValue.trxInfo = GridTab.getTrxInfo(tab.getTableName(), ctx, windowNo, tab.getTabNo()); if (retValue.isRefreshAll()) {} return retValue; }
public static void recSort(ArrayList<Integer> arr, int left, int right) { if (left >= right) return; int mid = (left + right) / 2; recSort(arr, left, mid); recSort(arr, mid + 1, right); // combine ArrayList<Integer> copy = new ArrayList<Integer>(); // MERGE int a = left; int b = mid + 1; while (a <= mid && b <= right) { int cmp; cmp = arr.get(a) - arr.get(b); if (cmp < 0) copy.add(arr.get(a++)); else copy.add(arr.get(b++)); } while (a <= mid) copy.add(arr.get(a++)); while (b <= right) copy.add(arr.get(b++)); // Put back int c = 0; for (int i = left; i <= right; i++) arr.set(i, copy.get(c++)); }
/** if some pages are too old, remove them */ public void removeOldPages() { // the oldest page is in the front of the list, and the most recent page is in the tail of the // list int duration = curTime - pageStartTimes.get(0).start_time; int count = 0; // pay special attention to >=, if ==, still need to go ahead. while (duration >= Configuration.T_period) { count++; if (count >= pageStartTimes.size()) break; duration = curTime - pageStartTimes.get(count).start_time + 1; } // all previous data need to be erased. for (int i = 0; i < count - 1; i++) { m_pStorageManager.deleteByteArray(pageStartTimes.get(i).pageId); } // shifting, move all the data Item to the front of the list for (int j = count - 1; j >= 0 && j < pageStartTimes.size(); j++) { pageStartTimes.set(j - count + 1, pageStartTimes.get(j)); } // erase the data at the tail after shifting for (int i = 0; i < count - 1; i++) { pageStartTimes.remove(pageStartTimes.size() - 1); } }
public void drawOrbits(ArrayList alObjectsArchive) { // println("SIZE:" + alObjectsArchive.size()); // ArrayList alObjectsArchive = timeline.getObjectStateArchive(); ArrayList alPrevPos = new ArrayList(); ArrayList alColors = new ArrayList(); alColors.add(color(255, 0, 0)); alColors.add(color(255, 255, 0)); alColors.add(color(255, 0, 255)); // for (int i = timeline.getTimeIdx(); i >= 0 && i > (timeline.getTimeIdx() - 1 - 100); i--) for (int i = 0; i < alObjectsArchive.size(); i++) { ArrayList objects = (ArrayList) alObjectsArchive.get(i); for (int j = 0; j < objects.size(); j++) { CelestialObject obj = (CelestialObject) objects.get(j); // CelestialObject obj = (CelestialObject)objects.get(1); PVector pos = obj.getPosition(); // stroke(0, 0, 255); stroke((Integer) alColors.get(j)); if (alPrevPos.size() == objects.size()) { PVector prevPos = (PVector) alPrevPos.get(j); line(prevPos.x, prevPos.y, pos.x, pos.y); alPrevPos.set(j, pos); } else alPrevPos.add(pos); } } }
public static void main(String[] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster BufferedReader f = new BufferedReader(new FileReader("badrand.in")); // input file name goes above PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("badrand.out"))); // Use StringTokenizer vs. readLine/split -- lots faster StringTokenizer st = new StringTokenizer(f.readLine()); // Get line, break into tokens int i1 = Integer.parseInt(st.nextToken()); // first integer ArrayList squares = new ArrayList<Integer>(10000); int mark = 0; i1 = middleSquare(i1); while (i1 > 0) { if (squares.contains(i1)) { squares.add(i1); squares.set(squares.indexOf(i1), 10000); mark = i1; i1 = 0; } else { squares.add(i1); i1 = middleSquare(i1); } } squares.add(10000); squares.add(0); out.println(squares.indexOf(mark) + 1); out.close(); // close the output file System.exit(0); // don't omit this! }
public static void madLibber(Scanner inputText) { ArrayList<String> paragraph = new ArrayList<>(); while (inputText.hasNextLine()) { paragraph.add(inputText.nextLine()); } int index1 = 0; int index2 = 0; String word; String userWord; for (int i = 0; i < paragraph.size(); i++) { while (paragraph.get(i).indexOf("[") != -1) { index1 = paragraph.get(i).indexOf("["); index2 = paragraph.get(i).indexOf("]"); word = paragraph.get(i).substring(index1 + 1, index2); System.out.print("Pick a(n) " + word + ":"); userWord = input.next(); paragraph.set( i, paragraph.get(i).substring(0, index1) + userWord + paragraph.get(i).substring(index2 + 1)); } index1 = 0; index2 = 0; } System.out.println("\n---\n"); for (int i = 0; i < paragraph.size(); i++) { System.out.println(paragraph.get(i)); } }
@Override public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { Hashtable<String, Integer> wordCounts = new Hashtable<String, Integer>(); ArrayList docName = new ArrayList<String>(); LinkedList wordName = new LinkedList<String>(); while (values.iterator().hasNext()) { String[] items = values.iterator().next().toString().split("@"); if (!wordName.contains(items[0])) { wordName.add(items[0]); } String[] keys = items[1].split(":|,"); for (int i = 0; i < keys.length; i += 2) { if (!docName.contains(keys[i])) { docName.add(keys[i]); wordCounts.put(keys[i], 0); } int tmp = wordCounts.get(keys[i]); tmp += Integer.parseInt(keys[i + 1]); wordCounts.put(keys[i], tmp); } } for (int i = 0; i < docName.size() - 1; ++i) { for (int j = i + 1; j < docName.size(); ++j) { if (wordCounts.get(docName.get(i)) < wordCounts.get(docName.get(j))) { String stmp = docName.get(i).toString(); docName.set(i, docName.get(j).toString()); docName.set(j, stmp); } } } String retKey = wordName.get(0).toString(); for (int i = 1; i < wordName.size(); ++i) { retKey += "," + wordName.get(i); } String retValue = ""; // ="\n" + docName.get(0).toString() + ":" + // wordCounts.get(docName.get(0).toString()); for (int i = 0; i < docName.size(); ++i) { retValue += "\n" + docName.get(i).toString() + ": " + wordCounts.get(docName.get(i).toString()); } context.write(new Text(retKey), new Text(retValue)); }
// Derives QFunctions for the given value function and simulates the // greedy policy for the given number of trials and steps per trial. // Returns final value of every trial. public ArrayList simulate(int trials, int steps, long rand_seed) { ArrayList values = new ArrayList(); _r = new Random(rand_seed); for (int trial = 1; trial <= trials; trial++) { System.out.println("\n -----------\n Trial " + trial + "\n -----------"); // Initialize state _state = new ArrayList(); _nVars = _mdp._alVars.size(); for (int c = 0; c < (_nVars << 1); c++) { _state.add("-"); } Iterator i = _mdp._alVars.iterator(); _vars = new TreeSet(); while (i.hasNext()) { String s = (String) i.next(); if (!s.endsWith("\'")) { Integer gid = (Integer) _mdp._tmVar2ID.get(s); _vars.add(gid); // Note: assign level (level is gid-1 b/c gids in order) _state.set(gid.intValue() - 1, _r.nextBoolean() ? TRUE : FALSE); } } // System.out.println(_mdp._context.printNode(_mdp._valueDD) + "\n" + _state); double reward = _mdp._context.evaluate(_mdp._rewardDD, _state); System.out.print(" " + PrintState(_state) + " " + MDP._df.format(reward)); // Run steps for (int step = 1; step <= steps; step++) { // Get action Action a; if (_bUseBasis) { a = getBasisAction(); } else { a = getAction(); } // Execute action executeAction(a); // Update reward reward = (_mdp._bdDiscount.doubleValue() * reward) + _mdp._context.evaluate(_mdp._rewardDD, _state); System.out.println(", a=" + a._sName); System.out.print( " " + PrintState(_state) + " " + MDP._df.format(reward) + ": " + "Step " + step); } values.add(new Double(reward)); System.out.println(); } return values; }
/** * Returns the indices of all scopes called by the given one. * * @param node source node index * @return destination node indices * @throws QueryException if a variable directly calls itself */ private int[] adjacentTo(final int node) throws QueryException { int[] adj = adjacent.get(node); if (adj == null) { adj = neighbors(scopes.get(node)); adjacent.set(node, adj); } return adj; }
public ShardIterator preferNodeActiveInitializingShardsIt(String nodeId) { ArrayList<ShardRouting> ordered = new ArrayList<>(activeShards.size() + allInitializingShards.size()); // fill it in a randomized fashion for (ShardRouting shardRouting : shuffler.shuffle(activeShards)) { ordered.add(shardRouting); if (nodeId.equals(shardRouting.currentNodeId())) { // switch, its the matching node id ordered.set(ordered.size() - 1, ordered.get(0)); ordered.set(0, shardRouting); } } if (!allInitializingShards.isEmpty()) { ordered.addAll(allInitializingShards); } return new PlainShardIterator(shardId, ordered); }