List of usage examples for java.util Collections shuffle
public static void shuffle(List<?> list)
From source file:com.netflix.discovery.shared.Applications.java
/** * Shuffle the instances and filter for only {@link InstanceStatus#UP} if * required.//from w ww . java2 s .c om * */ private void shuffleAndFilterInstances(Map<String, AbstractQueue<InstanceInfo>> srcMap, Map<String, AtomicReference<List<InstanceInfo>>> destMap, Map<String, AtomicLong> vipIndexMap, boolean filterUpInstances) { for (Map.Entry<String, AbstractQueue<InstanceInfo>> entries : srcMap.entrySet()) { AbstractQueue<InstanceInfo> instanceInfoQueue = entries.getValue(); List<InstanceInfo> l = new ArrayList<InstanceInfo>(instanceInfoQueue); if (filterUpInstances) { Iterator<InstanceInfo> it = l.iterator(); while (it.hasNext()) { InstanceInfo instanceInfo = it.next(); if (!InstanceStatus.UP.equals(instanceInfo.getStatus())) { it.remove(); } } } Collections.shuffle(l); AtomicReference<List<InstanceInfo>> instanceInfoList = destMap.get(entries.getKey()); if (instanceInfoList == null) { instanceInfoList = new AtomicReference<List<InstanceInfo>>(l); destMap.put(entries.getKey(), instanceInfoList); } instanceInfoList.set(l); vipIndexMap.put(entries.getKey(), new AtomicLong(0)); } // finally remove all vips that are completed deleted (i.e. missing) from the srcSet Set<String> srcVips = srcMap.keySet(); Set<String> destVips = destMap.keySet(); destVips.retainAll(srcVips); }
From source file:edu.cmu.tetrad.search.IndTestMultiFisherZ2.java
private int countGreater(List<Node> aa, List<Node> bb, List<Node> cc, int perm, int obs) { Node x = new ContinuousVariable("X"); Node y = new ContinuousVariable("Y"); Node z = new ContinuousVariable("Z"); int count = 0; int numPermutations = perm; double[] k_ = new double[numPermutations]; for (int c = 0; c < numPermutations; c++) { List<Integer> indices = new ArrayList<Integer>(); for (int j = 0; j < cov.getDimension(); j++) { indices.add(j);/*w w w . j a v a 2s. co m*/ } Collections.shuffle(indices); Map<Node, List<Node>> nodeMap = new HashMap<Node, List<Node>>(); List<Node> _nodes = cov.getVariables(); int _count = 0; List<Node> nx = new ArrayList<Node>(); for (int k = 0; k < aa.size(); k++) { nx.add(_nodes.get(indices.get(_count++))); } nodeMap.put(x, nx); List<Node> ny = new ArrayList<Node>(); for (int k = 0; k < bb.size(); k++) { ny.add(_nodes.get(indices.get(_count++))); } nodeMap.put(y, ny); List<Node> nz = new ArrayList<Node>(); for (int k = 0; k < cc.size(); k++) { nz.add(_nodes.get(indices.get(_count++))); } nodeMap.put(z, nz); IndTestMultiFisherZ2 test = new IndTestMultiFisherZ2(nodeMap, cov, alpha); test.setVerbose(true); TetradMatrix submatrix = subMatrix(cov, nx, ny, nz); TetradMatrix inverse; try { inverse = submatrix.inverse(); } catch (Exception e) { System.out.println("Couldn't invert " + submatrix.columns()); throw new IllegalArgumentException(); } List<Double> pValues = new ArrayList<Double>(); for (int i = 0; i < nx.size(); i++) { for (int m = 0; m < ny.size(); m++) { int j = nx.size() + m; double a = -1.0 * inverse.get(i, j); double v0 = inverse.get(i, i); double v1 = inverse.get(j, j); double b = Math.sqrt(v0 * v1); double r = a / b; int dof = cov.getSampleSize() - 1 - inverse.columns(); if (dof < 0) { System.out.println("Negative dof: " + dof + " n = " + cov.getSampleSize() + " cols = " + inverse.columns()); dof = 0; } double _z = Math.sqrt(dof) * 0.5 * (Math.log(1.0 + r) - Math.log(1.0 - r)); double p = 2.0 * (1.0 - RandomUtil.getInstance().normalCdf(0, 1, abs(_z))); pValues.add(p); } } int k = 0; // double alpha = 0.2; for (double p : pValues) { if (p < alpha) k++; } k_[c] = k; // System.out.println("k_[c] = " + k_[c] + " obs = " + obs); if (k_[c] > obs) { count++; } } double mean = StatUtils.mean(k_); double sd = StatUtils.sd(k_); List<Double> ret = new ArrayList<Double>(); ret.add(mean); ret.add(sd); return count; }
From source file:es.bsc.autonomic.powermodeller.DataSet.java
public DataSet getSubSampleRandom(int N) { //Calculate indexes of samples to be retrieved List<Integer> indexList = new ArrayList<Integer>(); for (int i = 0; i < this.getSize(); i++) { indexList.add(i);/*from w ww . j a v a 2 s. c om*/ } Collections.shuffle(indexList); return getSubSample(indexList.subList(0, N)); }
From source file:com.amazonaws.services.kinesis.leases.impl.LeaseTaker.java
/** * Choose leases to steal by randomly selecting one or more (up to max) from the most loaded worker. * Stealing rules:/*from w w w . j av a2s . co m*/ * * Steal up to maxLeasesToStealAtOneTime leases from the most loaded worker if * a) he has > target leases and I need >= 1 leases : steal min(leases needed, maxLeasesToStealAtOneTime) * b) he has == target leases and I need > 1 leases : steal 1 * * @param leaseCounts map of workerIdentifier to lease count * @param needed # of leases needed to reach the target leases for the worker * @param target target # of leases per worker * @return Leases to steal, or empty list if we should not steal */ private List<T> chooseLeasesToSteal(Map<String, Integer> leaseCounts, int needed, int target) { List<T> leasesToSteal = new ArrayList<>(); Entry<String, Integer> mostLoadedWorker = null; // Find the most loaded worker for (Entry<String, Integer> worker : leaseCounts.entrySet()) { if (mostLoadedWorker == null || mostLoadedWorker.getValue() < worker.getValue()) { mostLoadedWorker = worker; } } int numLeasesToSteal = 0; if ((mostLoadedWorker.getValue() >= target) && (needed > 0)) { int leasesOverTarget = mostLoadedWorker.getValue() - target; numLeasesToSteal = Math.min(needed, leasesOverTarget); // steal 1 if we need > 1 and max loaded worker has target leases. if ((needed > 1) && (numLeasesToSteal == 0)) { numLeasesToSteal = 1; } numLeasesToSteal = Math.min(numLeasesToSteal, maxLeasesToStealAtOneTime); } if (numLeasesToSteal <= 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format( "Worker %s not stealing from most loaded worker %s. He has %d," + " target is %d, and I need %d", workerIdentifier, mostLoadedWorker.getKey(), mostLoadedWorker.getValue(), target, needed)); } return leasesToSteal; } else { if (LOG.isDebugEnabled()) { LOG.debug(String.format( "Worker %s will attempt to steal %d leases from most loaded worker %s. " + " He has %d leases, target is %d, I need %d, maxLeasesToSteatAtOneTime is %d.", workerIdentifier, numLeasesToSteal, mostLoadedWorker.getKey(), mostLoadedWorker.getValue(), target, needed, maxLeasesToStealAtOneTime)); } } String mostLoadedWorkerIdentifier = mostLoadedWorker.getKey(); List<T> candidates = new ArrayList<T>(); // Collect leases belonging to that worker for (T lease : allLeases.values()) { if (mostLoadedWorkerIdentifier.equals(lease.getLeaseOwner())) { candidates.add(lease); } } // Return random ones Collections.shuffle(candidates); int toIndex = Math.min(candidates.size(), numLeasesToSteal); leasesToSteal.addAll(candidates.subList(0, toIndex)); return leasesToSteal; }
From source file:com.aengbee.android.leanback.ui.VideoDetailsFragment.java
public String chooseVideo(String durationSong) { int intDurationSong = Integer.parseInt(durationSong); List<String> fileList = getListFiles( new File(Environment.getExternalStorageDirectory().getPath() + "/" + Environment.DIRECTORY_MOVIES), "mp4"); List<String> possibleList = new ArrayList<String>(); if (fileList.size() > 0) { for (String file : fileList) { int length = file.contains("mp4") ? 900 : getDurationVideo(new File(file)); if (length > intDurationSong) possibleList.add(file);/*w w w . jav a 2 s. c om*/ } } String result = ""; if (fileList == null || fileList.size() == 0 || possibleList == null || possibleList.size() < 1) { result = Environment.getExternalStorageDirectory().getPath() + "/" + Environment.DIRECTORY_MOVIES + "/source.mp4"; } else { if (possibleList.size() > 1) Collections.shuffle(possibleList); result = String.format(getExternalStoragePublicDirectory(DIRECTORY_MOVIES).toString() + "/%s", possibleList.get(0)); } return result; }
From source file:com.examples.abelanav2.datastore.DbClient.java
/** * Gets the photo list stream.//from w w w. j a v a 2s .c o m * @param startCursor the page cursor. * @return the photo and cursor list. * @throws DatastoreException if there is a datastore error. */ private EntityListAndCursorResult getPhotoListStream(final ByteString startCursor) throws DatastoreException { Query.Builder query = Query.newBuilder(); query.addKindBuilder().setName(PHOTO_ENTITY); query.addOrder(makeOrder("upperTruePopularity", PropertyOrder.Direction.DESCENDING)); Filter availableFilter = makeFilter("available", PropertyFilter.Operator.EQUAL, makeValue(true)).build(); query.setFilter(makeFilter(availableFilter)); if (startCursor != null) { query.setStartCursor(startCursor); query.setLimit(BackendConstants.PHOTOS_PER_PAGE); } else { // If on the first page, let's add recent photos too query.setLimit(BackendConstants.PHOTOS_PER_PAGE); } RunQueryRequest request = RunQueryRequest.newBuilder().setQuery(query).build(); RunQueryResponse response = datastore.runQuery(request); List<Entity> entityList = new ArrayList<>(); for (EntityResult result : response.getBatch().getEntityResultList()) { entityList.add(result.getEntity()); } ByteString cursor = null; if (response.getBatch().hasMoreResults()) { cursor = response.getBatch().getEndCursor(); } // Randomize Collections.shuffle(entityList); return new EntityListAndCursorResult(ImmutableList.copyOf(entityList), cursor); }
From source file:forge.quest.QuestUtilCards.java
private void generateBoosterBoxesInShop(final int count) { if (count == 0) { return;/* w w w . j a va 2s . c o m*/ } Predicate<CardEdition> formatFilter = CardEdition.Predicates.HAS_BOOSTER_BOX; if (qc.getFormat() != null) { formatFilter = Predicates.and(formatFilter, isLegalInQuestFormat(qc.getFormat())); } Iterable<CardEdition> rightEditions = Iterables.filter(FModel.getMagicDb().getEditions(), formatFilter); List<CardEdition> editions = new ArrayList<>(); for (CardEdition e : rightEditions) { editions.add(e); } Collections.shuffle(editions); int numberOfBoxes = Math.min(Math.max(count / 2, 1), editions.size()); if (numberOfBoxes == 0) { return; } editions = editions.subList(0, numberOfBoxes); List<BoosterBox> output = new ArrayList<>(); for (CardEdition e : editions) { output.add(BoosterBox.FN_FROM_SET.apply(e)); } this.qa.getShopList().addAllFlat(output); }
From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java
private Optional<MemberId> pickRandomActivePeer() { List<MemberId> activePeers = peersSupplier.get(); Collections.shuffle(activePeers); return activePeers.stream().findFirst(); }
From source file:com.cloud.storage.StorageManagerImpl.java
public Long chooseHostForStoragePool(StoragePoolVO poolVO, List<Long> avoidHosts, boolean sendToVmResidesOn, Long vmId) {/*from ww w .j av a 2s . com*/ if (sendToVmResidesOn) { if (vmId != null) { VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId); if (vmInstance != null) { Long hostId = vmInstance.getHostId(); if (hostId != null && !avoidHosts.contains(vmInstance.getHostId())) { return hostId; } } } /* * Can't find the vm where host resides on(vm is destroyed? or * volume is detached from vm), randomly choose a host to send the * cmd */ } List<StoragePoolHostVO> poolHosts = _storagePoolHostDao.listByHostStatus(poolVO.getId(), Status.Up); Collections.shuffle(poolHosts); if (poolHosts != null && poolHosts.size() > 0) { for (StoragePoolHostVO sphvo : poolHosts) { if (!avoidHosts.contains(sphvo.getHostId())) { return sphvo.getHostId(); } } } return null; }
From source file:fr.ritaly.dungeonmaster.ai.CreatureManager.java
public Place addCreature(Creature creature) { Validate.notNull(creature, "The given creature is null"); if (!element.isTraversable(creature)) { throw new UnsupportedOperationException("The creature " + creature + " can't step on " + position); }/*from w w w . j av a2 s . c om*/ switch (creature.getSize()) { case ONE: final List<Sector> sectors = new ArrayList<Sector>(getFreeSectors()); if (sectors.size() > 1) { Collections.shuffle(sectors); } final Sector sector = sectors.iterator().next(); addCreature(creature, sector); return sector; case TWO: final List<Direction> directions = new ArrayList<Direction>(getFreeDirections()); if (directions.size() > 1) { Collections.shuffle(directions); } final Direction direction = directions.iterator().next(); addCreature(creature, direction); return direction; case FOUR: addCreature(creature, null); return null; default: throw new UnsupportedOperationException("Unsupported creature size <" + creature.getSize() + ">"); } }