List of usage examples for java.util Collections shuffle
@SuppressWarnings({ "rawtypes", "unchecked" }) public static void shuffle(List<?> list, Random rnd)
From source file:de.fosd.jdime.matcher.cost_model.CostModelMatcher.java
/** * Proposes a new set of <code>CMMatching</code>s based on the previous matchings <code>m</code>. * * @param m//from w ww . j ava 2s . c o m * the matchings from the previous iteration * @param preFixed * the matchings between the left and right tree that are fixed * @return the proposed matchings for the next iteration */ private CMMatchings<T> propose(CMMatchings<T> m, CMMatchings<T> preFixed, CMParameters<T> parameters) { CMMatchings<T> mVariable = new CMMatchings<>(m, m.left, m.right); mVariable.removeAll(preFixed); int j; if (parameters.fixRandomPercentage) { int lower = (int) (parameters.fixLower * mVariable.size()); int upper = (int) (parameters.fixUpper * mVariable.size()); Collections.shuffle(mVariable, parameters.rng); // TODO a switch to turn this off j = intFromRange(lower, upper, parameters); } else { //TODO sort by exact cost? mVariable.sort(Comparator.comparing(CMMatching::getExactCost)); j = parameters.rng.nextInt(mVariable.size()); } CMMatchings<T> fixed = new CMMatchings<>(mVariable.subList(0, j), m.left, m.right); log(FINER, m, () -> "Fixing the first " + j + "variable matchings from the last iteration."); log(FINEST, m, () -> "They are: " + fixed); fixed.addAll(preFixed); CMMatchings<T> proposition = complete(fixed, parameters); log(FINER, proposition, () -> "Proposing matchings for the next iteration."); log(FINEST, proposition, () -> "Proposition is: " + proposition); return proposition; }
From source file:com.hichinaschool.flashcards.libanki.Sched.java
private boolean _fillRev() { if (!mRevQueue.isEmpty()) { return true; }//from ww w. j av a2s .c o m if (mRevCount == 0) { return false; } while (mRevDids.size() > 0) { long did = mRevDids.getFirst(); int lim = Math.min(mQueueLimit, _deckRevLimit(did)); Cursor cur = null; if (lim != 0) { mRevQueue.clear(); // fill the queue with the current did try { cur = mCol.getDb().getDatabase().rawQuery("SELECT id FROM cards WHERE did = " + did + " AND queue = 2 AND due <= " + mToday + " LIMIT " + lim, null); while (cur.moveToNext()) { mRevQueue.add(cur.getLong(0)); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } if (!mRevQueue.isEmpty()) { // ordering try { if (mCol.getDecks().get(did).getInt("dyn") != 0) { // dynamic decks need due order preserved // Note: libanki reverses mRevQueue and returns the last element in _getRevCard(). // AnkiDroid differs by leaving the queue intact and returning the *first* element // in _getRevCard(). } else { Random r = new Random(); r.setSeed(mToday); Collections.shuffle(mRevQueue, r); } } catch (JSONException e) { throw new RuntimeException(e); } // is the current did empty? if (mRevQueue.size() < lim) { mRevDids.remove(); } return true; } } // nothing left in the deck; move to next mRevDids.remove(); } if (mRevCount != 0) { // if we didn't get a card but the count is non-zero, // we need to check again for any cards that were // removed from the queue but not buried _resetRev(); return _fillRev(); } return false; }
From source file:de.fosd.jdime.matcher.cost_model.CostModelMatcher.java
/** * Returns the (randomly ordered) complete bipartite graph between the trees rooted in <code>left</code> and * <code>right</code> with the addition of one no-match node (represented by <code>null</code>) each. * * @param left//from w ww . j a v a 2s .c om * the left root * @param right * the right root * @param parameters * the cost model parameters * @return the complete bipartite graph with its edges represented by <code>CMMatching</code>s */ private CMMatchings<T> completeBipartiteGraph(T left, T right, CMParameters<T> parameters) { List<T> leftNodes = Artifacts.bfs(left); List<T> rightNodes = Artifacts.bfs(right); // add the "No Match" node leftNodes.add(null); rightNodes.add(null); CMMatchings<T> bipartiteGraph = new CMMatchings<>(left, right); for (T lNode : leftNodes) { for (T rNode : rightNodes) { if (lNode != null && (rNode == null || lNode.categoryMatches(rNode))) { bipartiteGraph.add(new CMMatching<>(lNode, rNode)); } else if (rNode != null && (lNode == null || rNode.categoryMatches(lNode))) { bipartiteGraph.add(new CMMatching<>(lNode, rNode)); } } } Collections.shuffle(bipartiteGraph, parameters.rng); return bipartiteGraph; }
From source file:forge.game.player.Player.java
public final void shuffle(final SpellAbility sa) { final CardCollection list = new CardCollection(getCardsIn(ZoneType.Library)); if (list.size() <= 1) { return;/*from ww w . j a va 2 s . co m*/ } // overdone but wanted to make sure it was really random final Random random = MyRandom.getRandom(); Collections.shuffle(list, random); Collections.shuffle(list, random); Collections.shuffle(list, random); Collections.shuffle(list, random); Collections.shuffle(list, random); Collections.shuffle(list, random); int s = list.size(); for (int i = 0; i < s; i++) { list.add(random.nextInt(s - 1), list.remove(random.nextInt(s))); } Collections.shuffle(list, random); Collections.shuffle(list, random); Collections.shuffle(list, random); Collections.shuffle(list, random); Collections.shuffle(list, random); Collections.shuffle(list, random); getZone(ZoneType.Library).setCards(getController().cheatShuffle(list)); // Run triggers final HashMap<String, Object> runParams = new HashMap<String, Object>(); runParams.put("Player", this); runParams.put("Source", sa); game.getTriggerHandler().runTrigger(TriggerType.Shuffled, runParams, false); // Play the shuffle sound game.fireEvent(new GameEventShuffle(this)); }
From source file:org.apache.solr.client.solrj.impl.CloudSolrClient.java
protected NamedList<Object> sendRequest(SolrRequest request, String collection) throws SolrServerException, IOException { connect();/*w w w . j a va2s .co m*/ ClusterState clusterState = zkStateReader.getClusterState(); boolean sendToLeaders = false; List<String> replicas = null; if (request instanceof IsUpdateRequest) { if (request instanceof UpdateRequest) { NamedList<Object> response = directUpdate((AbstractUpdateRequest) request, collection, clusterState); if (response != null) { return response; } } sendToLeaders = true; replicas = new ArrayList<>(); } SolrParams reqParams = request.getParams(); if (reqParams == null) { reqParams = new ModifiableSolrParams(); } List<String> theUrlList = new ArrayList<>(); if (ADMIN_PATHS.contains(request.getPath())) { Set<String> liveNodes = clusterState.getLiveNodes(); for (String liveNode : liveNodes) { theUrlList.add(zkStateReader.getBaseUrlForNodeName(liveNode)); } } else { if (collection == null) { throw new SolrServerException( "No collection param specified on request and no default collection has been set."); } Set<String> collectionNames = getCollectionNames(clusterState, collection); if (collectionNames.size() == 0) { throw new SolrException(ErrorCode.BAD_REQUEST, "Could not find collection: " + collection); } String shardKeys = reqParams.get(ShardParams._ROUTE_); // TODO: not a big deal because of the caching, but we could avoid looking // at every shard // when getting leaders if we tweaked some things // Retrieve slices from the cloud state and, for each collection // specified, // add it to the Map of slices. Map<String, Slice> slices = new HashMap<>(); for (String collectionName : collectionNames) { DocCollection col = getDocCollection(clusterState, collectionName, null); Collection<Slice> routeSlices = col.getRouter().getSearchSlices(shardKeys, reqParams, col); ClientUtils.addSlices(slices, collectionName, routeSlices, true); } Set<String> liveNodes = clusterState.getLiveNodes(); List<String> leaderUrlList = null; List<String> urlList = null; List<String> replicasList = null; // build a map of unique nodes // TODO: allow filtering by group, role, etc Map<String, ZkNodeProps> nodes = new HashMap<>(); List<String> urlList2 = new ArrayList<>(); for (Slice slice : slices.values()) { for (ZkNodeProps nodeProps : slice.getReplicasMap().values()) { ZkCoreNodeProps coreNodeProps = new ZkCoreNodeProps(nodeProps); String node = coreNodeProps.getNodeName(); if (!liveNodes.contains(coreNodeProps.getNodeName()) || Replica.State.getState(coreNodeProps.getState()) != Replica.State.ACTIVE) continue; if (nodes.put(node, nodeProps) == null) { if (!sendToLeaders || coreNodeProps.isLeader()) { String url; if (reqParams.get(UpdateParams.COLLECTION) == null) { url = ZkCoreNodeProps.getCoreUrl(nodeProps.getStr(ZkStateReader.BASE_URL_PROP), collection); } else { url = coreNodeProps.getCoreUrl(); } urlList2.add(url); } else { String url; if (reqParams.get(UpdateParams.COLLECTION) == null) { url = ZkCoreNodeProps.getCoreUrl(nodeProps.getStr(ZkStateReader.BASE_URL_PROP), collection); } else { url = coreNodeProps.getCoreUrl(); } replicas.add(url); } } } } if (sendToLeaders) { leaderUrlList = urlList2; replicasList = replicas; } else { urlList = urlList2; } if (sendToLeaders) { theUrlList = new ArrayList<>(leaderUrlList.size()); theUrlList.addAll(leaderUrlList); } else { theUrlList = new ArrayList<>(urlList.size()); theUrlList.addAll(urlList); } Collections.shuffle(theUrlList, rand); if (sendToLeaders) { ArrayList<String> theReplicas = new ArrayList<>(replicasList.size()); theReplicas.addAll(replicasList); Collections.shuffle(theReplicas, rand); theUrlList.addAll(theReplicas); } if (theUrlList.isEmpty()) { for (String s : collectionNames) { if (s != null) collectionStateCache.remove(s); } throw new SolrException(SolrException.ErrorCode.INVALID_STATE, "Could not find a healthy node to handle the request."); } } LBHttpSolrClient.Req req = new LBHttpSolrClient.Req(request, theUrlList); LBHttpSolrClient.Rsp rsp = lbClient.request(req); return rsp.getResponse(); }
From source file:org.elasticsearch.test.ElasticsearchIntegrationTest.java
/** * Indexes the given {@link IndexRequestBuilder} instances randomly. It shuffles the given builders and either * indexes they in a blocking or async fashion. This is very useful to catch problems that relate to internal document * ids or index segment creations. Some features might have bug when a given document is the first or the last in a * segment or if only one document is in a segment etc. This method prevents issues like this by randomizing the index * layout.//from ww w . j a va 2s .c o m * * @param forceRefresh if <tt>true</tt> all involved indices are refreshed once the documents are indexed. * @param dummyDocuments if <tt>true</tt> some empty dummy documents may be randomly inserted into the document list and deleted once * all documents are indexed. This is useful to produce deleted documents on the server side. * @param maybeFlush if <tt>true</tt> this method may randomly execute full flushes after index operations. * @param builders the documents to index. */ public void indexRandom(boolean forceRefresh, boolean dummyDocuments, boolean maybeFlush, List<IndexRequestBuilder> builders) throws InterruptedException, ExecutionException { Random random = getRandom(); Set<String> indicesSet = new HashSet<>(); for (IndexRequestBuilder builder : builders) { indicesSet.add(builder.request().index()); } Set<Tuple<String, String>> bogusIds = new HashSet<>(); if (random.nextBoolean() && !builders.isEmpty() && dummyDocuments) { builders = new ArrayList<>(builders); final String[] indices = indicesSet.toArray(new String[indicesSet.size()]); // inject some bogus docs final int numBogusDocs = scaledRandomIntBetween(1, builders.size() * 2); final int unicodeLen = between(1, 10); for (int i = 0; i < numBogusDocs; i++) { String id = randomRealisticUnicodeOfLength(unicodeLen) + Integer.toString(dummmyDocIdGenerator.incrementAndGet()); String index = RandomPicks.randomFrom(random, indices); bogusIds.add(new Tuple<>(index, id)); builders.add(client().prepareIndex(index, RANDOM_BOGUS_TYPE, id).setSource("{}")); } } final String[] indices = indicesSet.toArray(new String[indicesSet.size()]); Collections.shuffle(builders, random); final CopyOnWriteArrayList<Tuple<IndexRequestBuilder, Throwable>> errors = new CopyOnWriteArrayList<>(); List<CountDownLatch> inFlightAsyncOperations = new ArrayList<>(); // If you are indexing just a few documents then frequently do it one at a time. If many then frequently in bulk. if (builders.size() < FREQUENT_BULK_THRESHOLD ? frequently() : builders.size() < ALWAYS_BULK_THRESHOLD ? rarely() : false) { if (frequently()) { logger.info("Index [{}] docs async: [{}] bulk: [{}]", builders.size(), true, false); for (IndexRequestBuilder indexRequestBuilder : builders) { indexRequestBuilder .execute(new PayloadLatchedActionListener<IndexResponse, IndexRequestBuilder>( indexRequestBuilder, newLatch(inFlightAsyncOperations), errors)); postIndexAsyncActions(indices, inFlightAsyncOperations, maybeFlush); } } else { logger.info("Index [{}] docs async: [{}] bulk: [{}]", builders.size(), false, false); for (IndexRequestBuilder indexRequestBuilder : builders) { indexRequestBuilder.execute().actionGet(); postIndexAsyncActions(indices, inFlightAsyncOperations, maybeFlush); } } } else { List<List<IndexRequestBuilder>> partition = Lists.partition(builders, Math.min(MAX_BULK_INDEX_REQUEST_SIZE, Math.max(1, (int) (builders.size() * randomDouble())))); logger.info("Index [{}] docs async: [{}] bulk: [{}] partitions [{}]", builders.size(), false, true, partition.size()); for (List<IndexRequestBuilder> segmented : partition) { BulkRequestBuilder bulkBuilder = client().prepareBulk(); for (IndexRequestBuilder indexRequestBuilder : segmented) { bulkBuilder.add(indexRequestBuilder); } BulkResponse actionGet = bulkBuilder.execute().actionGet(); assertThat(actionGet.hasFailures() ? actionGet.buildFailureMessage() : "", actionGet.hasFailures(), equalTo(false)); } } for (CountDownLatch operation : inFlightAsyncOperations) { operation.await(); } final List<Throwable> actualErrors = new ArrayList<>(); for (Tuple<IndexRequestBuilder, Throwable> tuple : errors) { if (ExceptionsHelper.unwrapCause(tuple.v2()) instanceof EsRejectedExecutionException) { tuple.v1().execute().actionGet(); // re-index if rejected } else { actualErrors.add(tuple.v2()); } } assertThat(actualErrors, emptyIterable()); if (!bogusIds.isEmpty()) { // delete the bogus types again - it might trigger merges or at least holes in the segments and enforces deleted docs! for (Tuple<String, String> doc : bogusIds) { // see https://github.com/elasticsearch/elasticsearch/issues/8706 final DeleteResponse deleteResponse = client().prepareDelete(doc.v1(), RANDOM_BOGUS_TYPE, doc.v2()) .get(); if (deleteResponse.isFound() == false) { logger.warn("failed to delete a dummy doc [{}][{}]", doc.v1(), doc.v2()); } } } if (forceRefresh) { assertNoFailures(client().admin().indices().prepareRefresh(indices) .setIndicesOptions(IndicesOptions.lenientExpandOpen()).execute().get()); } }
From source file:com.adityarathi.muo.services.AudioPlaybackService.java
/** * Toggles shuffle mode and returns whether shuffle is now on or off. *///w w w.j a v a2 s.c o m public boolean toggleShuffleMode() { if (isShuffleOn()) { //Set shuffle off. mApp.getSharedPreferences().edit().putBoolean(Common.SHUFFLE_ON, false).commit(); //Save the element at the current index. int currentElement = getPlaybackIndecesList().get(getCurrentSongIndex()); //Reset the cursor pointers list. Collections.sort(getPlaybackIndecesList()); //Reset the current index to the index of the old element. setCurrentSongIndex(getPlaybackIndecesList().indexOf(currentElement)); } else { //Set shuffle on. mApp.getSharedPreferences().edit().putBoolean(Common.SHUFFLE_ON, true).commit(); //Build a new list that doesn't include the current song index. ArrayList<Integer> newList = new ArrayList<Integer>(getPlaybackIndecesList()); newList.remove(getCurrentSongIndex()); //Shuffle the new list. Collections.shuffle(newList, new Random(System.nanoTime())); //Plug in the current song index back into the new list. newList.add(getCurrentSongIndex(), getCurrentSongIndex()); mPlaybackIndecesList = newList; //Collections.shuffle(getPlaybackIndecesList().subList(0, getCurrentSongIndex())); //Collections.shuffle(getPlaybackIndecesList().subList(getCurrentSongIndex()+1, getPlaybackIndecesList().size())); } /* Since the queue changed, we're gonna have to update the * next MediaPlayer object with the new song info. */ prepareAlternateMediaPlayer(); //Update all UI elements with the new queue order. mApp.broadcastUpdateUICommand(new String[] { Common.NEW_QUEUE_ORDER }, new String[] { "" }); return isShuffleOn(); }