Java Code Examples for java.util.Collections#shuffle()

The following examples show how to use java.util.Collections#shuffle() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HashtagView.java    From hashtag-view with MIT License 6 votes vote down vote up
private void applyDistribution(Collection<ItemData> list) {
    switch (rowDistribution) {
        case DISTRIBUTION_LEFT:
            Collections.sort((List) list);
            break;
        case DISTRIBUTION_MIDDLE:
            SortUtil.symmetricSort((List) list);
            break;
        case DISTRIBUTION_RIGHT:
            Collections.sort((List) list, Collections.reverseOrder());
            break;
        case DISTRIBUTION_RANDOM:
            Collections.shuffle((List) list);
            break;
        case DISTRIBUTION_NONE:
            break;
    }
}
 
Example 2
Source File: OWLServerSimSearchTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected HttpUriRequest createGoodAnnotSufRequest(int n) throws URISyntaxException {
	URIBuilder uriBuilder = new URIBuilder()
		.setScheme("http")
		.setHost("localhost").setPort(9031)
		.setPath("/owlsim/getAnnotationSufficiencyScore/");
		
	List<OWLClass> allClasses = new ArrayList<OWLClass>();
	allClasses.addAll(g.getAllOWLClasses());
	Collections.shuffle(allClasses);
	int i=0;

	for (OWLClass c : allClasses) {
		String id = g.getIdentifier(c);
		uriBuilder.addParameter("a", id);

		i++;
		if (i >= n)
			break;
	}
	uriBuilder.addParameter("limit","5");
	URI uri = uriBuilder.build();
	LOG.info("Getting URL="+uri);
	HttpUriRequest httpUriRequest = new HttpGet(uri);
	LOG.info("Got URL="+uri);
	return httpUriRequest;
}
 
Example 3
Source File: DefaultQueryPlanner.java    From datawave with Apache License 2.0 6 votes vote down vote up
/**
 * Get the list of ivarator cache dirs, randomizing the order (while respecting priority) so that the tservers spread out the disk usage.
 */
private List<IvaratorCacheDirConfig> getShuffledIvaratoCacheDirConfigs(ShardQueryConfiguration config) {
    List<IvaratorCacheDirConfig> shuffledIvaratorCacheDirs = new ArrayList<>();
    
    // group the ivarator cache dirs by their priority
    Map<Integer,List<IvaratorCacheDirConfig>> groupedConfigs = config.getIvaratorCacheDirConfigs().stream()
                    .collect(Collectors.groupingBy(IvaratorCacheDirConfig::getPriority));
    
    // iterate over the sorted priorities, and shuffle the subsets
    for (Integer priority : new TreeSet<>(groupedConfigs.keySet())) {
        List<IvaratorCacheDirConfig> cacheDirs = groupedConfigs.get(priority);
        Collections.shuffle(cacheDirs);
        shuffledIvaratorCacheDirs.addAll(cacheDirs);
    }
    
    return shuffledIvaratorCacheDirs;
}
 
Example 4
Source File: IClustExp.java    From ade with GNU General Public License v3.0 6 votes vote down vote up
public Partition() {
    List<Integer> indices = new ArrayList<Integer>();
    for (int i = 0; i < mNumElements; ++i) {
        indices.add(i);
    }
    Collections.shuffle(indices, mRandom);

    mClusterIndices = new int[mNumElements];

    ArrayList<Integer> members = new ArrayList<Integer>();
    members.ensureCapacity(mNumElements / mClusterNum + 1);
    for (int i = 0; i < mClusterNum; ++i) {
        members.clear();
        for (int j = i; j < mNumElements; j += mClusterNum) {
            members.add(indices.get(j));
        }
        mClusters.add(new Cluster(i, members));
    }

}
 
Example 5
Source File: RawQueryTestCase.java    From SQLite-Performance with The Unlicense 6 votes vote down vote up
@Override
public Metrics runCase() {
    mDbHelper = new DbHelper(App.getInstance(), getClass().getSimpleName(), mFileSize, mFiles);
    Metrics result = new Metrics(getClass().getSimpleName()+" ("+mFileSize+" blob size, "+mFiles+" blobs)", mTestSizeIndex);
    SQLiteDatabase db = mDbHelper.getReadableDatabase();

    String[] fileNames = Arrays.copyOf(mDbHelper.getFileNames(), mDbHelper.getFileNames().length);
    List<String> fileList = Arrays.asList(fileNames);
    Collections.shuffle(fileList, new Random());
    fileNames = fileList.toArray(fileNames);

    result.started();
    String[] selectionArgs = new String[1];
    for (int i = 0; i < mFiles; i++) {
        selectionArgs[0] = fileNames[i];
        Cursor c = db.rawQuery("SELECT data FROM files WHERE filename = ?", selectionArgs);
        try {
            c.moveToNext();
            byte[] data = c.getBlob(0);
        } finally {
            c.close();
        }
    }
    result.finished();
    return result;
}
 
Example 6
Source File: BcryptMicroBenchmark.java    From armadillo with Apache License 2.0 5 votes vote down vote up
private void warmup(List<AbstractBcrypt> contender) {
    byte[][] cache = new byte[25][];
    for (int i = 0; i < 100; i++) {
        Collections.shuffle(contender);
        for (AbstractBcrypt abstractBcrypt : contender) {
            byte[] out = abstractBcrypt.bcrypt(rnd.nextInt(3) + 4, Bytes.random(20).array());
            cache[rnd.nextInt(cache.length)] = out;
        }
    }

    for (byte[] bytes : cache) {
        System.out.print(Bytes.wrapNullSafe(bytes).encodeBase64());
    }
}
 
Example 7
Source File: AbstractStatisticsBuilderTest.java    From presto with Apache License 2.0 5 votes vote down vote up
public void assertValues(T expectedMin, T expectedMax, List<T> values)
{
    assertValuesInternal(expectedMin, expectedMax, values);
    assertValuesInternal(expectedMin, expectedMax, ImmutableList.copyOf(values).reverse());

    List<T> randomOrder = new ArrayList<>(values);
    Collections.shuffle(randomOrder, new Random(42));
    assertValuesInternal(expectedMin, expectedMax, randomOrder);
}
 
Example 8
Source File: BaseTestMap.java    From oopsla15-artifact with Eclipse Public License 1.0 5 votes vote down vote up
protected void setUp(IValueFactory factory) throws Exception {
	vf = factory;
	a = tf.abstractDataType(ts, "A");
	b = tf.abstractDataType(ts, "B");
	testValues = new TestValue[]{
			new TestValue(this, "Bergen", "Amsterdam", "from", "to"),
			new TestValue(this, "New York", "London", null, null),
			new TestValue(this, "Banana", "Fruit", "key", "value"),
	};
	
	testMaps = new IMap[] {
			vf.map(fromToMapType),
			vf.map(keyValueMapType),
			vf.map(unlabeledMapType),
			vf.map(fromToMapType).put(vf.string("Bergen"), vf.string("Amsterdam")),
			vf.map(fromToValueMapType).put(vf.string("Bergen"), vf.string("Amsterdam")).put(vf.string("Mango"), vf.string("Yummy")),
			vf.map(fromToMapType).put(vf.string("Bergen"), vf.string("Amsterdam")).put(vf.string("Amsterdam"), vf.string("Frankfurt")),
			vf.map(fromToMapType).put(vf.string("Bergen"), vf.string("Amsterdam")).put(vf.string("Amsterdam"), vf.string("Frankfurt")).put(vf.string("Frankfurt"), vf.string("Moscow")),
			vf.map(keyValueMapType).put(vf.string("Bergen"), vf.string("Rainy")).put(vf.string("Helsinki"), vf.string("Cold")),
			vf.map(unlabeledMapType).put(vf.string("Mango"), vf.string("Sweet")).put(vf.string("Banana"), vf.string("Yummy")),
	};
	
	String[] strings = new String[] { "Bergen", "Amsterdam", "Frankfurt", "Helsinki", "Moscow", "Rainy", "Cold", "Mango", "Banana", "Sweet", "Yummy" };
	List<String> list1 = Arrays.asList(strings);
	List<String> list2 = Arrays.asList(strings);
	Collections.shuffle(list1);
	Collections.shuffle(list2);
	keyValues = new StringPair[strings.length];
	for(int i = 0; i < strings.length; i++) {
		keyValues[i] = new StringPair(vf.string(list1.get(i)), vf.string(list2.get(i)));
	}
}
 
Example 9
Source File: ImageActivity.java    From android-slideshow with MIT License 5 votes vote down vote up
/**
 * Show the next image.
 */
private void nextImage(boolean forwards, boolean preload){
	if (preload && !PRELOAD_IMAGES){
		// Stop
		return;
	}

	int current = imagePosition;
	int newPosition = imagePosition;
	if (REFRESH_FOLDER && newPosition == 0) { // Time to reload, easy base case
		fileList = new FileItemHelper(this).getFileList(currentPath, false, getIntent().getStringExtra("imagePath") == null);
		if (RANDOM_ORDER){
			Collections.shuffle(fileList);
		}
	}

	do {
		newPosition += forwards ? 1 : -1;
		if (newPosition < 0){
			newPosition = fileList.size() - 1;
		}
		if (newPosition >= fileList.size()){
			newPosition = 0;
		}
		if (newPosition == current){
			// Looped. Exit
			onBackPressed();
			return;
		}
	} while (!testPositionIsImage(newPosition));
	if (!preload){
		imagePosition = newPosition;
	}
	loadImage(newPosition, preload);
}
 
Example 10
Source File: TransmutingCompositionManglerSystem.java    From entity-system-benchmarks with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public TransmutingCompositionManglerSystem(long seed, int entityCount) {
	rng = new Random(seed);
	ENTITY_COUNT = entityCount;
	RENEW = ENTITY_COUNT / 4;

	ArrayList<Integer> idsList = new ArrayList<Integer>();
	for (int i = 0; ENTITY_COUNT > i; i++)
		idsList.add(i);
	Collections.shuffle(idsList);
	
	ids = new int[ENTITY_COUNT];
	for (int i = 0; ids.length > i; i++)
		ids[i] = idsList.get(i);
}
 
Example 11
Source File: ReptilesActivity.java    From AdapterDelegates with Apache License 2.0 5 votes vote down vote up
private List<DisplayableItem> getAnimals() {
    List<DisplayableItem> animals = new ArrayList<>();

    animals.add(new Snake("Mub Adder", "Adder"));
    animals.add(new Snake("Texas Blind Snake", "Blind snake"));
    animals.add(new Snake("Tree Boa", "Boa"));
    animals.add(new Gecko("Fat-tailed", "Hemitheconyx"));
    animals.add(new Gecko("Stenodactylus", "Dune Gecko"));
    animals.add(new Gecko("Leopard Gecko", "Eublepharis"));
    animals.add(new Gecko("Madagascar Gecko", "Phelsuma"));
    animals.add(new UnknownReptile());

    animals.add(new Snake("Mub Adder", "Adder"));
    animals.add(new Snake("Texas Blind Snake", "Blind snake"));
    animals.add(new Snake("Tree Boa", "Boa"));
    animals.add(new Gecko("Fat-tailed", "Hemitheconyx"));
    animals.add(new Gecko("Stenodactylus", "Dune Gecko"));
    animals.add(new Gecko("Leopard Gecko", "Eublepharis"));
    animals.add(new Gecko("Madagascar Gecko", "Phelsuma"));

    animals.add(new Snake("Mub Adder", "Adder"));
    animals.add(new Snake("Texas Blind Snake", "Blind snake"));
    animals.add(new Snake("Tree Boa", "Boa"));
    animals.add(new Gecko("Fat-tailed", "Hemitheconyx"));
    animals.add(new Gecko("Stenodactylus", "Dune Gecko"));
    animals.add(new Gecko("Leopard Gecko", "Eublepharis"));
    animals.add(new Gecko("Madagascar Gecko", "Phelsuma"));

    Collections.shuffle(animals);
    return animals;
}
 
Example 12
Source File: DynamoDBStoreManager.java    From dynamodb-janusgraph-storage-backend with Apache License 2.0 5 votes vote down vote up
@Override
public void mutateMany(final Map<String, Map<StaticBuffer, KCVMutation>> mutations, final StoreTransaction txh) throws BackendException {
    //this method can be called by janusgraph-core, which is not aware of our backend implementation.
    //that means the keys of mutations map are the logical store names.
    final Timer.Context ctxt = client.getDelegate().getTimerContext(this.prefixAndMutateMany, null /*tableName*/);
    try {
        final DynamoDbStoreTransaction tx = DynamoDbStoreTransaction.getTx(txh);

        final List<MutateWorker> mutationWorkers = Lists.newLinkedList();

        // one pass to create tasks
        long updateOrDeleteItemCalls = 0;
        long keys = 0;
        for (Map.Entry<String, Map<StaticBuffer, KCVMutation>> mutationMapEntry : mutations.entrySet()) {
            final AwsStore store = openDatabase(mutationMapEntry.getKey());

            final Map<StaticBuffer, KCVMutation> storeMutations = mutationMapEntry.getValue();
            keys += storeMutations.size();
            final Collection<MutateWorker> storeWorkers = store.createMutationWorkers(storeMutations, tx);
            updateOrDeleteItemCalls += storeWorkers.size();

            mutationWorkers.addAll(storeWorkers);
        }

        // shuffle the list of MutationWorkers so writes to edgestore and graphindex happen in parallel
        Collections.shuffle(mutationWorkers);

        client.getDelegate().getMeter(client.getDelegate().getMeterName(this.prefixAndMutateManyKeys, null /*tableName*/))
            .mark(keys);
        client.getDelegate().getMeter(client.getDelegate().getMeterName(this.prefixAndMutateManyUpdateOrDeleteItemCalls, null /*tableName*/))
            .mark(updateOrDeleteItemCalls);
        client.getDelegate().getMeter(client.getDelegate().getMeterName(this.prefixAndMutateManyStores, null /*tableName*/))
            .mark(mutations.size());
        client.getDelegate().parallelMutate(mutationWorkers);
    } finally {
        ctxt.stop();
    }
}
 
Example 13
Source File: DomBoard.java    From DominionSim with MIT License 5 votes vote down vote up
private void createBlackMarketDeck() {
   	blackMarketDeck = new ArrayList<DomCard>();
   	for (DomCardName theCardName : DomCardName.values()) {
   	  if (get(theCardName)==null) {
	    if ( theCardName!=DomCardName.Treasure_Map
	    && theCardName.hasCardType(DomCardType.Kingdom)
	    && (theCardName.getPotionCost()==0 || get(DomCardName.Potion)!=null)){
   		  DomCard theCard = theCardName.createNewCardInstance();
   		  theCard.setFromBlackMarket(true);
   		  blackMarketDeck.add(theCard);
  		    }
   	  }
   	}
   	Collections.shuffle(blackMarketDeck);
}
 
Example 14
Source File: ObjectBoxDB.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
private static long[] shuffleRandomSortId(Query<Content> query) {
    LazyList<Content> lazyList = query.findLazy();
    List<Integer> order = new ArrayList<>();
    for (int i = 0; i < lazyList.size(); i++) order.add(i);
    Collections.shuffle(order, new Random(RandomSeedSingleton.getInstance().getSeed()));

    List<Long> result = new ArrayList<>();
    for (int i = 0; i < order.size(); i++) {
        result.add(lazyList.get(order.get(i)).getId());
    }
    return Helper.getPrimitiveLongArrayFromList(result);
}
 
Example 15
Source File: StorageSystemDataMotionStrategy.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private HostVO getHost(Long zoneId, HypervisorType hypervisorType, boolean computeClusterMustSupportResign) {
    Preconditions.checkArgument(zoneId != null, "Zone ID cannot be null.");
    Preconditions.checkArgument(hypervisorType != null, "Hypervisor type cannot be null.");

    List<HostVO> hosts = _hostDao.listByDataCenterIdAndHypervisorType(zoneId, hypervisorType);

    if (hosts == null) {
        return null;
    }

    List<Long> clustersToSkip = new ArrayList<>();

    Collections.shuffle(hosts, RANDOM);

    for (HostVO host : hosts) {
        if (!ResourceState.Enabled.equals(host.getResourceState())) {
            continue;
        }

        if (computeClusterMustSupportResign) {
            long clusterId = host.getClusterId();

            if (clustersToSkip.contains(clusterId)) {
                continue;
            }

            if (clusterDao.getSupportsResigning(clusterId)) {
                return host;
            }
            else {
                clustersToSkip.add(clusterId);
            }
        }
        else {
            return host;
        }
    }

    return null;
}
 
Example 16
Source File: RetrieveConnectionStatusResponseTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void mergeMultipleStatuses() {
    final RetrieveConnectionStatusResponse expected =
            RetrieveConnectionStatusResponse.getBuilder(TestConstants.ID, DittoHeaders.empty())
                    .connectionStatus(ConnectivityStatus.OPEN)
                    .liveStatus(ConnectivityStatus.CLOSED)
                    .connectedSince(IN_CONNECTION_STATUS_SINCE)
                    .clientStatus(clientStatus)
                    .sourceStatus(sourceStatus)
                    .targetStatus(targetStatus)
                    .build();

    final List<ResourceStatus> statuses = Stream.of(clientStatus, sourceStatus, targetStatus)
            .flatMap(Collection::stream)
            .collect(Collectors.toList());
    // merge in random order
    Collections.shuffle(statuses);

    RetrieveConnectionStatusResponse.Builder builder =
            RetrieveConnectionStatusResponse.getBuilder(TestConstants.ID, DittoHeaders.empty())
                    .connectionStatus(ConnectivityStatus.OPEN)
                    .liveStatus(ConnectivityStatus.CLOSED)
                    .connectedSince(IN_CONNECTION_STATUS_SINCE)
                    .clientStatus(Collections.emptyList())
                    .sourceStatus(Collections.emptyList())
                    .targetStatus(Collections.emptyList());
    for (final ResourceStatus resourceStatus : statuses) {
        builder = builder.withAddressStatus(resourceStatus);
    }

    final RetrieveConnectionStatusResponse actual = builder.build();

    assertThat((Object) actual.getConnectionStatus()).isEqualTo(expected.getConnectionStatus());
    assertThat(actual.getClientStatus()).containsAll(expected.getClientStatus());
    assertThat(actual.getSourceStatus()).containsAll(expected.getSourceStatus());
    assertThat(actual.getTargetStatus()).containsAll(expected.getTargetStatus());
}
 
Example 17
Source File: Shuffled.java    From prayer-times-android with Apache License 2.0 5 votes vote down vote up
@NonNull
public static Collection<Integer> getList() {
    if (list.isEmpty()) {
        int c = SqliteHelper.get().getCount();
        for (int i = 1; i <= (c + 1); i++) {
            list.add(i);
        }

        Collections.shuffle(list, random);
        list.remove((Integer) list.size());
    }

    return list;
}
 
Example 18
Source File: TestHStoreFile.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Assert that the given comparator orders the given storefiles in the same way that they're
 * passed.
 */
private void assertOrdering(Comparator<? super HStoreFile> comparator, HStoreFile... sfs) {
  ArrayList<HStoreFile> sorted = Lists.newArrayList(sfs);
  Collections.shuffle(sorted);
  Collections.sort(sorted, comparator);
  LOG.debug("sfs: " + Joiner.on(",").join(sfs));
  LOG.debug("sorted: " + Joiner.on(",").join(sorted));
  assertTrue(Iterables.elementsEqual(Arrays.asList(sfs), sorted));
}
 
Example 19
Source File: JSR166TestCase.java    From streamsupport with GNU General Public License v2.0 4 votes vote down vote up
static <T> void shuffle(T[] array) {
    Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
}
 
Example 20
Source File: NSlackSVMLearner.java    From murphy with Apache License 2.0 4 votes vote down vote up
/**
 * @param start
 * @param end
 * @return
 */
private List<Integer> shuffle(int start, int end) {
	List<Integer> result = a.toList(a.enumerate(start, end));
	Collections.shuffle(result);
	return result;
}