List of usage examples for java.util Collections shuffle
public static void shuffle(List<?> list)
From source file:com.addthis.hydra.data.util.TestConcurrentKeyTopper.java
@Test public void multithreadedIncrementWithEviction() { try {/* w w w. j a v a 2 s. c o m*/ List<String> input = new ArrayList<>(); Map<String, Integer> count = new HashMap<>(); // insert 100 elements that appear 100 times each insertElements(input, count, 100, 100); // insert 100 elements that appear 10 times each insertElements(input, count, 100, 10); // insert 100 elements that appear 1 times each insertElements(input, count, 100, 1); Collections.shuffle(input); ConcurrentKeyTopper topper = new ConcurrentKeyTopper(); topper.init(); int numThreads = 8; InsertionThread[] threads = new InsertionThread[numThreads]; for (int i = 0; i < numThreads; i++) { threads[i] = new InsertionThread(topper, input, i, numThreads); } for (int i = 0; i < numThreads; i++) { threads[i].start(); } for (int i = 0; i < numThreads; i++) { threads[i].join(); } // all the elements with a count of 100 must appear in the topper for (Map.Entry<String, Integer> entry : count.entrySet()) { if (entry.getValue() == 100) { assertNotNull(topper.get(entry.getKey())); } } } catch (InterruptedException ingored) { fail(); } }
From source file:net.sourceforge.subsonic.service.sonos.SonosHelper.java
private List<AbstractMedia> forShuffleMusicFolder(List<MusicFolder> musicFolders, int count, String username, HttpServletRequest request) {// w ww .j a va 2 s . c o m List<MediaFile> albums = searchService.getRandomAlbums(40, musicFolders); List<MediaFile> songs = new ArrayList<MediaFile>(); for (MediaFile album : albums) { for (MediaFile file : filterMusic(mediaFileService.getChildrenOf(album, true, false, false))) { songs.add(file); } } Collections.shuffle(songs); songs = songs.subList(0, Math.min(count, songs.size())); return forMediaFiles(songs, username, request); }
From source file:fr.fg.server.contract.NpcHelper.java
/** * Renvoie un prnom masculin alatoire.//from ww w .ja v a 2s. c o m * * @return Un prnom masculin alatoire. */ public static String getRandomMaleFirstName() { String value = maleFirstNames.get(currentMaleFirstName).getName(); currentMaleFirstName++; if (currentMaleFirstName == maleFirstNames.size()) { Collections.shuffle(maleFirstNames); currentMaleFirstName = 0; } return value; }
From source file:com.pinterest.teletraan.worker.SimpleAgentJanitor.java
void processBatch() throws Exception { // First, check those groups associates with certain envs List<String> groups = groupDAO.getAllEnvGroups(); // Manually inject the NULL group groups.add(Constants.NULL_HOST_GROUP); Collections.shuffle(groups); for (String group : groups) { try {//w w w . java 2s . c om LOG.info("AgentJanitor process group: {}", group); processEachGroup(group); } catch (Exception e) { LOG.error("SimpleAgentJanitor failed to process group: {}", group, e); } } // For those hosts do not belong to any host, but still associate with certain envs LOG.info("AgentJanitor process explicite capacity hosts"); processIndividualHosts(); }
From source file:fr.ritaly.dungeonmaster.ai.CreatureManager.java
private EnumSet<Direction> getFreeDirections() { if (creatures != null) { final boolean ne = !creatures.containsKey(Sector.NORTH_EAST); final boolean nw = !creatures.containsKey(Sector.NORTH_WEST); final boolean se = !creatures.containsKey(Sector.SOUTH_EAST); final boolean sw = !creatures.containsKey(Sector.SOUTH_WEST); int count = 0; if (ne) { count++;/*w w w.j ava2 s .c om*/ } if (nw) { count++; } if (se) { count++; } if (sw) { count++; } switch (count) { case 0: case 1: // No free direction return EnumSet.noneOf(Direction.class); case 2: // At most one direction free if (ne && nw) { return EnumSet.of(Direction.NORTH); } else if (se && sw) { return EnumSet.of(Direction.SOUTH); } else if (nw && sw) { return EnumSet.of(Direction.WEST); } else if (ne && se) { return EnumSet.of(Direction.EAST); } else { // No direction free (the sectors are staggered) return EnumSet.noneOf(Direction.class); } case 3: // One for sure, maybe 2 final List<Direction> directions = new ArrayList<Direction>(2); if (ne && nw) { directions.add(Direction.NORTH); } if (se && sw) { directions.add(Direction.SOUTH); } if (nw && sw) { directions.add(Direction.WEST); } if (ne && se) { directions.add(Direction.EAST); } if (directions.size() == 1) { return EnumSet.of(directions.iterator().next()); } else { Collections.shuffle(directions); return EnumSet.of(directions.iterator().next()); } case 4: // 2 are free // Choose a random pair of directions if (RandomUtils.nextBoolean()) { return EnumSet.of(Direction.EAST, Direction.WEST); } else { return EnumSet.of(Direction.NORTH, Direction.SOUTH); } default: throw new RuntimeException("Unexpected count <" + count + ">"); } } // Choose a random pair of directions if (RandomUtils.nextBoolean()) { return EnumSet.of(Direction.EAST, Direction.WEST); } else { return EnumSet.of(Direction.NORTH, Direction.SOUTH); } }
From source file:com.linkedin.pinot.perf.BitmapPerformanceBenchmark.java
public static void benchmarkIntersetionAndUnion(String indexSegmentDir) throws ConfigurationException, IOException, Exception { File[] listFiles = new File(indexSegmentDir).listFiles(); File indexDir = new File(indexSegmentDir); SegmentMetadataImpl segmentMetadata = new SegmentMetadataImpl(indexDir); Map<String, BitmapInvertedIndexReader> bitMapIndexMap = new HashMap<String, BitmapInvertedIndexReader>(); Map<String, Integer> cardinalityMap = new HashMap<String, Integer>(); Map<String, ImmutableDictionaryReader> dictionaryMap = new HashMap<String, ImmutableDictionaryReader>(); for (File file : listFiles) { if (!file.getName().endsWith("bitmap.inv")) { continue; }/*w ww . j ava 2 s .c o m*/ String column = file.getName().replaceAll(".bitmap.inv", ""); ColumnMetadata columnMetadata = segmentMetadata.getColumnMetadataFor(column); int cardinality = columnMetadata.getCardinality(); cardinalityMap.put(column, cardinality); System.out.println(column + "\t\t\t" + cardinality + " \t" + columnMetadata.getDataType()); PinotDataBuffer bitmapDataBuffer = PinotDataBuffer.fromFile(file, ReadMode.mmap, FileChannel.MapMode.READ_ONLY, "testing"); BitmapInvertedIndexReader bitmapInvertedIndex = new BitmapInvertedIndexReader(bitmapDataBuffer, cardinality); File dictionaryFile = new File(indexSegmentDir + "/" + column + ".dict"); SegmentDirectory segmentDirectory = SegmentDirectory.createFromLocalFS(indexDir, segmentMetadata, ReadMode.mmap); SegmentDirectory.Reader segmentReader = segmentDirectory.createReader(); ColumnIndexContainer container = ColumnIndexContainer.init(segmentReader, columnMetadata, null); ImmutableDictionaryReader dictionary = container.getDictionary(); if (columnMetadata.getDataType() == DataType.INT) { System.out.println("BitmapPerformanceBenchmark.main()"); assert dictionary instanceof IntDictionary; } dictionaryMap.put(column, dictionary); // System.out.println(column + ":\t" + MemoryUtil.deepMemoryUsageOf(bitmapInvertedIndex)); bitMapIndexMap.put(column, bitmapInvertedIndex); bitmapDataBuffer.close(); } List<String> dimensionNamesList = segmentMetadata.getSchema().getDimensionNames(); Collections.shuffle(dimensionNamesList); int NUM_TEST = 100; final int MAX_DIMENSIONS_PER_DIMENSION = 1; int MAX_DIMENSIONS_IN_WHERE_CLAUSE = 3; Random random = new Random(); for (int numDimensions = 1; numDimensions <= MAX_DIMENSIONS_IN_WHERE_CLAUSE; numDimensions++) { for (int numValuesPerDimension = 1; numValuesPerDimension <= MAX_DIMENSIONS_PER_DIMENSION; numValuesPerDimension++) { int runCount = 0; while (runCount < NUM_TEST) { Collections.shuffle(dimensionNamesList); List<ImmutableRoaringBitmap> bitMaps = new ArrayList<ImmutableRoaringBitmap>(); List<String> columnNameValuePairs = new ArrayList<String>(); for (int i = 0; i < numDimensions; i++) { String columnName = dimensionNamesList.get(i); InvertedIndexReader bitmapInvertedIndex = bitMapIndexMap.get(columnName); for (int j = 0; j < numValuesPerDimension; j++) { int dictId = random.nextInt(cardinalityMap.get(columnName)); String dictValue = dictionaryMap.get(columnName).getStringValue(dictId); columnNameValuePairs.add(columnName + ":" + dictValue); ImmutableRoaringBitmap immutable = bitmapInvertedIndex.getImmutable(dictId); bitMaps.add(immutable); } } System.out.println("START**********************************"); int[] cardinality = new int[bitMaps.size()]; int[] sizes = new int[bitMaps.size()]; for (int i = 0; i < bitMaps.size(); i++) { ImmutableRoaringBitmap immutableRoaringBitmap = bitMaps.get(i); cardinality[i] = immutableRoaringBitmap.getCardinality(); sizes[i] = immutableRoaringBitmap.getSizeInBytes(); } System.out.println("\t#bitmaps:" + bitMaps.size()); System.out.println("\tinput values:" + columnNameValuePairs); System.out.println("\tinput cardinality:" + Arrays.toString(cardinality)); System.out.println("\tinput sizes:" + Arrays.toString(sizes)); and(bitMaps); or(bitMaps); System.out.println("END**********************************"); runCount = runCount + 1; } } } }
From source file:edu.berkeley.sparrow.examples.FairnessTestingFrontend.java
public List<TTaskSpec> generateJob(int numTasks, int numPreferredNodes, List<String> backends, int benchmarkId, int benchmarkIterations) { // Pack task parameters ByteBuffer message = ByteBuffer.allocate(8); message.putInt(benchmarkId);/*from www .j a va 2 s . c o m*/ message.putInt(benchmarkIterations); List<TTaskSpec> out = new ArrayList<TTaskSpec>(); for (int taskId = 0; taskId < numTasks; taskId++) { TTaskSpec spec = new TTaskSpec(); spec.setTaskId(Integer.toString((new Random().nextInt()))); spec.setMessage(message.array()); if (numPreferredNodes > 0) { Collections.shuffle(backends); TPlacementPreference preference = new TPlacementPreference(); for (int i = 0; i < numPreferredNodes; i++) { preference.addToNodes(backends.get(i)); } spec.setPreference(preference); } out.add(spec); } return out; }
From source file:edu.vt.middleware.ldap.handler.AbstractConnectionHandler.java
/** * Parses the supplied ldap url and splits it into separate URLs if it is * space delimited./*from w w w. j a va 2s .c o m*/ * * @param ldapUrl to parse * @param strategy of ordered array to return * * @return array of ldap URLs */ protected String[] parseLdapUrl(final String ldapUrl, final ConnectionStrategy strategy) { String[] urls = null; if (strategy == ConnectionStrategy.DEFAULT) { urls = new String[] { ldapUrl }; } else if (strategy == ConnectionStrategy.ACTIVE_PASSIVE) { final List<String> l = this.splitLdapUrl(ldapUrl); urls = l.toArray(new String[l.size()]); } else if (strategy == ConnectionStrategy.ROUND_ROBIN) { final List<String> l = this.splitLdapUrl(ldapUrl); for (int i = 0; i < this.connectionCount.getCount() % l.size(); i++) { l.add(l.remove(0)); } urls = l.toArray(new String[l.size()]); } else if (strategy == ConnectionStrategy.RANDOM) { final List<String> l = this.splitLdapUrl(ldapUrl); Collections.shuffle(l); urls = l.toArray(new String[l.size()]); } return urls; }
From source file:edu.umass.cs.reconfiguration.reconfigurationutils.ConsistentReconfigurableNodeConfig.java
/** * This method tries to return a limited number of active replica socket * addresses that to the extent possible have distinct IPs. The socket * addresses are a randomly chosen subset of size up to limit from the set * of all active replicas.//from w w w. ja va 2 s . co m * * @param limit * @return Socket addresses of active replicas. Used by reconfigurator to * respond to broadcast queries. */ public Set<InetSocketAddress> getActiveReplicaSocketAddresses(int limit) { Set<InetSocketAddress> actives = new HashSet<InetSocketAddress>(); Set<Integer> activeIPs = new HashSet<Integer>(); ArrayList<InetSocketAddress> activeNodes = new ArrayList<InetSocketAddress>(); ArrayList<InetSocketAddress> duplicateIPs = new ArrayList<InetSocketAddress>(); /* Create up to limit-sized ArrayList for shuffling. First add socket * addresses corresponding to distinct /24 IP prefixes. */ for (NodeIDType node : this.getActiveReplicas()) { InetSocketAddress sockAddr = this.getNodeSocketAddress(node); if (!activeIPs.contains(RTTEstimator.addrToPrefixInt(sockAddr.getAddress()))) { activeNodes.add(sockAddr); activeIPs.add(RTTEstimator.addrToPrefixInt(sockAddr.getAddress())); } else duplicateIPs.add(sockAddr); if (activeNodes.size() >= limit) break; } /* Then check if we can add back some of the socket addresses with * duplicate /24 prefixes up to limit. */ if (activeNodes.size() < limit) { for (InetSocketAddress duplicate : duplicateIPs) { activeNodes.add(duplicate); if (activeNodes.size() >= limit) break; } } // shuffle to return actives in random order Collections.shuffle(activeNodes); for (InetSocketAddress sockAddr : activeNodes) { actives.add(sockAddr); if (actives.size() >= limit) break; } return actives; }
From source file:com.linkedin.drelephant.math.Statistics.java
public static <T> T[] createSample(Class<T> clazz, T[] objects, int size) { //Skip this process if number of items already smaller than sample size if (objects.length <= size) { return objects; }//from w w w.j a v a2 s.co m @SuppressWarnings("unchecked") T[] result = (T[]) Array.newInstance(clazz, size); //Shuffle a clone copy T[] clone = objects.clone(); Collections.shuffle(Arrays.asList(clone)); //Take the first n items System.arraycopy(clone, 0, result, 0, size); return result; }