List of usage examples for java.util Collections shuffle
public static void shuffle(List<?> list)
From source file:com.graphaware.neo4j.webexpo.database.DataGenerator.java
private void doGenerateAttendanceHalfWayThrough() { List<String> fridayTalks = findTalksOnDay("Friday"); List<String> saturdayTalks = findTalksOnDay("Saturday"); for (String attendee : findAllAttendees()) { Collections.shuffle(fridayTalks); Collections.shuffle(saturdayTalks); for (int i = 0; i < ATTENDED_TALKS_PER_DAY; i++) { TalkEvaluation evaluation = randomEvaluation(); System.out.println(attendee + " evaluating " + fridayTalks.get(i) + " as " + evaluation); attendeeService.evaluateTalk(attendee, fridayTalks.get(i), evaluation); }/*from w w w .j a v a2 s . c om*/ System.out.println(attendee + " planning to attend " + saturdayTalks.get(0) + " next"); attendeeService.reportNextTalk(attendee, saturdayTalks.get(0)); } }
From source file:hms.hwestra.interactionrebuttal.InteractionRebuttal.java
public void iterativelyBuildProxiesAndCorrelate(String expressionfile, String gte, String outputdir, String probefile, int permutations, String proxy, Integer numProbesMax, boolean justcorrelate) throws IOException { Set<String> samplesToUse = null; if (gte != null) { TextFile tfq = new TextFile(gte, TextFile.R); samplesToUse = tfq.readAsSet(1, TextFile.tab); tfq.close();/*from ww w . j a va 2s .c o m*/ } DoubleMatrixDataset<String, String> rawExpressionDataset = new DoubleMatrixDataset<String, String>( expressionfile, null, samplesToUse); int numTotalIter = 0; ArrayList<String> probes = null; if (probefile != null) { TextFile tf = new TextFile(probefile, TextFile.R); probes = tf.readAsArrayList(); tf.close(); numProbesMax = probes.size(); } else { System.out.println("Selecting random probes"); List<String> rows = rawExpressionDataset.rowObjects; probes = new ArrayList<String>(rows); } outputdir = Gpio.formatAsDirectory(outputdir); Gpio.createDir(outputdir); int iter = 5; System.out.println(probes.size() + " probes availables"); int remainder = numProbesMax % iter; int numProbesMaxIter = numProbesMax + (iter - remainder); if (!justcorrelate) { for (int num = 0; num < numProbesMaxIter + 1; num += iter) { int probesToSelect = num; if (num == 0) { probesToSelect = 1; } if (num > numProbesMax) { probesToSelect = numProbesMax; } System.out.println("Selecting: " + probesToSelect + " probes"); for (int permutation = 0; permutation < permutations; permutation++) { Collections.shuffle(probes); List<String> subsample = probes.subList(0, probesToSelect); // create output dir String outputdirPerm = outputdir + probesToSelect + "-Probes/Permutation-" + permutation + "/"; outputdirPerm = Gpio.formatAsDirectory(outputdirPerm); Gpio.createDir(outputdirPerm); String subset = outputdirPerm + "probes.txt"; TextFile probeout = new TextFile(subset, TextFile.W); probeout.writeList(subsample); probeout.close(); // run normalizer prepareDataForCelltypeSpecificEQTLMapping(rawExpressionDataset, expressionfile, outputdirPerm, Double.NaN, subset, null, null, null, 4); // remove superfluous files // correlate with cell count } numTotalIter++; } } DoubleMatrixDataset<String, String> ds = new DoubleMatrixDataset<String, String>(proxy); // samples on the rows... ds.transposeDataset(); // samples on the columns for (int row = 0; row < ds.nrRows; row++) { String pheno = ds.rowObjects.get(row); double[] x = ds.rawData[row]; System.out.println("x length: " + x.length); TextFile statsout = new TextFile(outputdir + pheno + ".txt", TextFile.W); statsout.writeln("Num\tMeanPearson\tsdPearson\tMeanSpearman\tsdSpearman"); SpearmansCorrelation sp = new SpearmansCorrelation(); for (int num = 0; num < numProbesMaxIter + 1; num += iter) { int probesToSelect = num; if (num == 0) { probesToSelect = 1; } if (num > numProbesMax) { probesToSelect = numProbesMax; } double[] allCorrelations = new double[permutations]; double[] allCorrelationSpearman = new double[permutations]; for (int permutation = 0; permutation < permutations; permutation++) { String inputdirPerm = outputdir + probesToSelect + "-Probes/Permutation-" + permutation + "/CellTypeProxyFile.txt"; DoubleMatrixDataset<String, String> ds2 = new DoubleMatrixDataset<String, String>(inputdirPerm); ds2.transposeDataset(); // samples on the column double[] y = new double[x.length]; System.out.println("y: " + y.length); double[] ytmp = ds2.rawData[0]; // if (ytmp.length != x.length) { // System.err.println("Error: " + y.length); // System.exit(-1); // } else { for (int col = 0; col < ds.nrCols; col++) { int otherCol = ds2.hashCols.get(ds.colObjects.get(col)); y[col] = ytmp[otherCol]; } double corr = JSci.maths.ArrayMath.correlation(x, y); System.out.println(num + "\t" + permutation + "\t" + corr); double spearman = sp.correlation(x, y); allCorrelations[permutation] = corr; allCorrelationSpearman[permutation] = spearman; // } } // doe double meanP = JSci.maths.ArrayMath.mean(allCorrelations); double sdP = JSci.maths.ArrayMath.standardDeviation(allCorrelations); double meanSP = JSci.maths.ArrayMath.mean(allCorrelationSpearman); double sdSP = JSci.maths.ArrayMath.standardDeviation(allCorrelationSpearman); statsout.writeln(num + "\t" + meanP + "\t" + sdP + "\t" + meanSP + "\t" + sdSP); } statsout.close(); } }
From source file:edu.pitt.csb.stability.StabilityUtils.java
public static int[][] subSampleNoReplacement(int sampSize, int subSize, int numSub) { if (subSize < 1) { throw new IllegalArgumentException("Sample size must be > 0."); }//w w w . j a v a 2 s . co m List<Integer> indices = new ArrayList<Integer>(sampSize); for (int i = 0; i < sampSize; i++) { indices.add(i); } int[][] sampMat = new int[numSub][subSize]; for (int i = 0; i < numSub; i++) { Collections.shuffle(indices); int[] curSamp; SAMP: while (true) { curSamp = subSampleIndices(sampSize, subSize); for (int j = 0; j < i; j++) { if (Arrays.equals(curSamp, sampMat[j])) { continue SAMP; } } break; } sampMat[i] = curSamp; } return sampMat; }
From source file:com.hackday.andy.jztv.VideoDetailsFragment.java
private void setupMovieListRow() { String subcategories[] = { getString(R.string.related_movies) }; List<Movie> list = MovieList.list; Collections.shuffle(list); ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(new CardPresenter()); for (int j = 0; j < NUM_COLS; j++) { listRowAdapter.add(list.get(j % 1)); }//ww w . j a v a 2 s . c om HeaderItem header = new HeaderItem(0, subcategories[0]); mAdapter.add(new ListRow(header, listRowAdapter)); }
From source file:com.bittorrent.mpetazzoni.tracker.TrackedTorrent.java
/** * Get a list of peers we can return in an announce response for this * torrent.//from w ww. j ava 2 s.c o m * * @param peer The peer making the request, so we can exclude it from the * list of returned peers. * @return A list of peers we can include in an announce response. */ public List<Peer> getSomePeers(TrackedPeer peer) { List<Peer> peers = new LinkedList<Peer>(); // Extract answerPeers random peers List<TrackedPeer> candidates = new LinkedList<TrackedPeer>(this.peers.values()); Collections.shuffle(candidates); int count = 0; for (TrackedPeer candidate : candidates) { // Collect unfresh peers, and obviously don't serve them as well. if (!candidate.isFresh() || (candidate.looksLike(peer) && !candidate.equals(peer))) { logger.debug("Collecting stale peer {}...", candidate); this.peers.remove(candidate.getHexPeerId()); continue; } // Don't include the requesting peer in the answer. if (peer.looksLike(candidate)) { continue; } // Collect unfresh peers, and obviously don't serve them as well. if (!candidate.isFresh()) { logger.debug("Collecting stale peer {}...", candidate.getHexPeerId()); this.peers.remove(candidate.getHexPeerId()); continue; } // Only serve at most ANSWER_NUM_PEERS peers if (count++ > this.answerPeers) { break; } peers.add(candidate); } return peers; }
From source file:jCloisterZone.CarcassonneEnvironment.java
public static void main(String[] args) { int repetitions = 100; double[] scores = new double[repetitions]; RRLJCloisterClient client = new LocalCarcassonneClient("config.ini"); ServerIF server = null;//w w w.ja v a 2 s .c om Game game = client.getGame(); Player firstPlayer = null; ArrayList<PlayerSlot> slots = new ArrayList<PlayerSlot>(); for (int r = 0; r < repetitions; r++) { client.createGame(); if (game == null) { server = new LocalCarcassonneServer(client.getGame()); PlayerSlot slot = new PlayerSlot(0, PlayerSlot.SlotType.AI, "RANDOM" + 0, client.getClientId()); slot.setAiClassName(RandomAIPlayer.class.getName()); slots.add(slot); for (int j = 1; j < Integer.parseInt(args[0]); j++) { slot = new PlayerSlot(j, PlayerSlot.SlotType.AI, "AI" + j, client.getClientId()); slot.setAiClassName(LegacyAiPlayer.class.getName()); slots.add(slot); } game = client.getGame(); } else { // Reset the UIs server.stopGame(); game.clearUserInterface(); // Clear the slots and re-add them. for (int i = 0; i < PlayerSlot.COUNT; i++) { server.updateSlot(new PlayerSlot(i), null); } } Collections.shuffle(slots); for (int i = 0; i < slots.size(); i++) { PlayerSlot slot = slots.get(i); PlayerSlot cloneSlot = new PlayerSlot(i, slot.getType(), slot.getNick(), slot.getOwner()); cloneSlot.setAiClassName(slot.getAiClassName()); server.updateSlot(cloneSlot, LegacyAiPlayer.supportedExpansions()); } server.startGame(); Phase phase = game.getPhase(); // Cycle through (probably only once) to keep the game moving. while (phase != null && !phase.isEntered()) { // Modifying phases to proxyless versions if (phase.getClass().equals(CreateGamePhase.class)) phase = game.getPhases().get(ProxylessCreateGamePhase.class); if (phase.getClass().equals(DrawPhase.class)) phase = game.getPhases().get(ProxylessDrawPhase.class); phase.setEntered(true); phase.enter(); phase = game.getPhase(); if (game.getTurnPlayer().getNick().equals("RANDOM0")) firstPlayer = game.getTurnPlayer(); } int score = firstPlayer.getPoints(); scores[r] = score; System.out.println(score); } Mean m = new Mean(); StandardDeviation sd = new StandardDeviation(); System.out.println("Mean: " + m.evaluate(scores) + ", SD: " + sd.evaluate(scores)); }
From source file:net.sourceforge.subsonic.service.sonos.SonosHelper.java
public List<AbstractMedia> forRadioArtist(int mediaFileId, int count, String username, HttpServletRequest request) {//from www. ja va 2s. co m MediaFile artist = mediaFileService.getMediaFile(mediaFileId); List<MusicFolder> musicFolders = settingsService.getMusicFoldersForUser(username); List<MediaFile> songs = filterMusic(lastFmService.getSimilarSongs(artist, count, musicFolders)); Collections.shuffle(songs); songs = songs.subList(0, Math.min(count, songs.size())); return forMediaFiles(songs, username, request); }
From source file:com.eightmins.eightminutes.VideoDetailsFragment.java
private void setupMovieListRow() { String subcategories[] = { getString(string.related_movies) }; List<Movie> list = MovieList.list; Collections.shuffle(list); ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(new CardPresenter()); for (int j = 0; j < VideoDetailsFragment.NUM_COLS; j++) { listRowAdapter.add(list.get(j % 5)); }// w ww . ja v a2 s . co m HeaderItem header = new HeaderItem(0, subcategories[0]); mAdapter.add(new ListRow(header, listRowAdapter)); }
From source file:com.mycompany.wolf.Room.java
/** * // w w w . j av a 2s . c o m */ private void assignRoles() { Multiset<String> roleCounts = HashMultiset.create(roleCounts()); Map<String, String> roleMap = new HashMap(); competeRoles.values().stream().filter(c -> roleCounts.remove(c.role)).forEach(c -> { roleMap.put(c.playerId, c.role); }); List<String> restPlayerId = sessions.stream().map(s -> getPlayerId(s)).filter(s -> !roleMap.containsKey(s)) .collect(Collectors.toList()); Collections.shuffle(restPlayerId); Iterator<String> restRoleIt = roleCounts.iterator(); Iterator<String> restPlayerIdIt = restPlayerId.iterator(); for (; restRoleIt.hasNext();) { String role = restRoleIt.next(); String playerId = restPlayerIdIt.next(); roleMap.put(playerId, role); } sessions.stream().forEach(s -> { s.getUserProperties().put("role", roleMap.get(getPlayerId(s))); }); List<ImmutableMap<String, String>> assignedRoles = roleMap.entrySet().stream() .map(entry -> ImmutableMap.of("playerId", entry.getKey(), "role", entry.getValue())) .collect(Collectors.toCollection(LinkedList::new)); Map<String, Object> assignRoles = ImmutableMap.of("code", "assignRoles", "properties", assignedRoles); String jsonText = JsonUtils.toString(assignRoles); sessions.stream().forEach(s -> { s.getAsyncRemote().sendText(jsonText); }); }
From source file:edu.ucuenca.authorsdisambiguation.nwd.NWD.java
public List<String> TopT(List<String> m, int n) throws IOException, SQLException { n = (n <= 0) ? 1 : n;/*w w w . java 2s .c o m*/ if (m.size() == 1) { m.add(m.get(0)); } if (Cache.getInstance().config.get("stochastic").getAsBoolean().value()) { Collections.shuffle(m); if (2 * n < m.size()) { m = m.subList(0, 2 * n); } } Map<String, Double> Mapa = new HashMap(); for (int i = 0; i < m.size(); i++) { for (int j = i + 1; j < m.size(); j++) { double v = NGD(m.get(i), m.get(j)); //System.out.println(m.get(i) + "," + m.get(j) + "=" + v); if (Mapa.containsKey(m.get(i))) { Mapa.put(m.get(i), Mapa.get(m.get(i)) + v); } else { Mapa.put(m.get(i), v); } if (Mapa.containsKey(m.get(j))) { Mapa.put(m.get(j), Mapa.get(m.get(j)) + v); } else { Mapa.put(m.get(j), v); } } } Map<String, Double> sortByValue = sortByValue(Mapa); List<String> ls = new ArrayList<>(); ArrayList<String> arrayList = new ArrayList(sortByValue.keySet()); ArrayList<Double> arrayList2 = new ArrayList(sortByValue.values()); for (int i = 0; i < n; i++) { if (i < sortByValue.size()) { ls.add(arrayList.get(i)); } } return ls; }