本文整理汇总了Java中java.util.Collections.shuffle方法的典型用法代码示例。如果您正苦于以下问题:Java Collections.shuffle方法的具体用法?Java Collections.shuffle怎么用?Java Collections.shuffle使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.Collections
的用法示例。
在下文中一共展示了Collections.shuffle方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: generateUniqueNumbers
import java.util.Collections; //导入方法依赖的package包/类
/**
* Method to generate a set of w unique numbers designed to help agents
* chose random empty tiles
**/
public int[] generateUniqueNumbers(int w)
{
if (w > emptyTiles.size())
{
w = emptyTiles.size();
// print("<<generateUniqueNumbers>> w is " + w + ", but empty Tiles remaining are " +
// emptyTiles.size() + ". w = " + emptyTiles.size());
}
ArrayList<Integer> list = new ArrayList<Integer>();
int[] listOfW = new int[w];
for (int i = 0; i < emptyTiles.size(); i++)
{
list.add(new Integer(i));
}
Collections.shuffle(list, new Random(System.nanoTime()));
for (int i = 0; i < w; i++)
{
listOfW[i] = list.get(i);
}
return listOfW;
}
示例2: createFolds
import java.util.Collections; //导入方法依赖的package包/类
public List<Fold<T>> createFolds(List<T> instances, int numFolds) {
Collections.shuffle(instances, random);
Preconditions.checkArgument(instances.size() >= numFolds * 2, "K-fold cross-validation"
+ " requires at least 2*K instances.");
Iterator<T> iterator = instances.iterator();
List<List<T>> folds = IntStream.range(0, numFolds)
.mapToObj(i -> new ArrayList<T>())
.collect(Collectors.toList());
int index = 0;
while (iterator.hasNext()) {
folds.get(index % numFolds).add(iterator.next());
++index;
}
List<Fold<T>> result = new ArrayList<>();
for (index = 0; index < numFolds; ++index) {
int foldNumber = index;
List<T> train = IntStream.range(0, numFolds)
.filter(fold -> fold != foldNumber)
.mapToObj(folds::get).flatMap(List::stream).collect(Collectors.toList());
result.add(new Fold<>(train, folds.get(foldNumber)));
}
return result;
}
示例3: filterShortcutsAndAssertNumStaticAndDynamic
import java.util.Collections; //导入方法依赖的package包/类
private void filterShortcutsAndAssertNumStaticAndDynamic(
List<ShortcutInfoCompat> shortcuts, int expectedStatic, int expectedDynamic) {
Collections.shuffle(shortcuts);
List<ShortcutInfoCompat> filteredShortcuts = ShortcutFilter.sortAndFilterShortcuts(shortcuts);
assertIsSorted(filteredShortcuts);
int numStatic = 0;
int numDynamic = 0;
for (ShortcutInfoCompat shortcut : filteredShortcuts) {
if (shortcut.isDeclaredInManifest()) {
numStatic++;
}
if (shortcut.isDynamic()) {
numDynamic++;
}
}
assertEquals(expectedStatic, numStatic);
assertEquals(expectedDynamic, numDynamic);
}
示例4: setUp
import java.util.Collections; //导入方法依赖的package包/类
@BeforeExperiment void setUp() {
random = new Random(0xdeadbeef); // fix the seed so results are comparable across runs
int nonAlpha = size / nonAlphaRatio;
int alpha = size - nonAlpha;
List<Character> chars = Lists.newArrayListWithCapacity(size);
for (int i = 0; i < alpha; i++) {
chars.add(randomAlpha());
}
for (int i = 0; i < nonAlpha; i++) {
chars.add(randomNonAlpha());
}
Collections.shuffle(chars, random);
char[] array = Chars.toArray(chars);
this.testString = new String(array);
}
示例5: setUp
import java.util.Collections; //导入方法依赖的package包/类
@BeforeExperiment
@SuppressWarnings("unchecked")
void setUp() throws ClassNotFoundException {
Preconditions.checkArgument(hitRate >= 0 && hitRate <= 1,
"hitRate must be in the range [0,1]");
enumType = (Class<? extends Enum>)
Class.forName(EnumsBenchmark.class.getCanonicalName() + "$" + enumSize + "Enum");
Enum<?>[] allConstants = enumType.getEnumConstants();
List<String> hits = new ArrayList<String>();
for (int i = 0; i < hitRate * 256 / 3; ++i) {
hits.add(allConstants[0].name());
hits.add(allConstants[allConstants.length / 2].name());
hits.add(allConstants[allConstants.length - 1].name());
}
List<String> misses = new ArrayList<String>();
for (int i = 0; i < 256 - hits.size(); ++i) {
misses.add("INVALID");
}
List<String> sampleDataList = new ArrayList<String>();
sampleDataList.addAll(hits);
sampleDataList.addAll(misses);
Collections.shuffle(sampleDataList);
sampleData = sampleDataList.toArray(new String[sampleDataList.size()]);
}
示例6: getHostGroup
import java.util.Collections; //导入方法依赖的package包/类
/**
* 根据host分组
*/
private Map<String,Set<Integer>> getHostGroup(List<HostAndPort> list){
Map<String,Set<Integer>> hosts = new HashMap<String, Set<Integer>>();
Collections.shuffle(list);
for (HostAndPort ipPort : list) {
Set<Integer> ports = hosts.get(ipPort.getHost());
if(ports == null){
ports = new HashSet<Integer>();
}
ports.add(ipPort.getPort());
hosts.put(ipPort.getHost(), ports);
}
return hosts;
}
示例7: testNewResponse
import java.util.Collections; //导入方法依赖的package包/类
public void testNewResponse() {
TestTransportNodesAction action = getTestTransportNodesAction();
TestNodesRequest request = new TestNodesRequest();
List<TestNodeResponse> expectedNodeResponses = mockList(TestNodeResponse::new, randomIntBetween(0, 2));
expectedNodeResponses.add(new TestNodeResponse());
List<BaseNodeResponse> nodeResponses = new ArrayList<>(expectedNodeResponses);
// This should be ignored:
nodeResponses.add(new OtherNodeResponse());
List<FailedNodeException> failures = mockList(
() -> new FailedNodeException(
randomAsciiOfLength(8),
randomAsciiOfLength(8),
new IllegalStateException(randomAsciiOfLength(8))),
randomIntBetween(0, 2));
List<Object> allResponses = new ArrayList<>(expectedNodeResponses);
allResponses.addAll(failures);
Collections.shuffle(allResponses, random());
AtomicReferenceArray<?> atomicArray = new AtomicReferenceArray<>(allResponses.toArray());
TestNodesResponse response = action.newResponse(request, atomicArray);
assertSame(request, response.request);
// note: I shuffled the overall list, so it's not possible to guarantee that it's in the right order
assertTrue(expectedNodeResponses.containsAll(response.getNodes()));
assertTrue(failures.containsAll(response.failures()));
}
示例8: eliminazioneDiretta
import java.util.Collections; //导入方法依赖的package包/类
public void eliminazioneDiretta(String nomeTorneo, List<Squadra> squadre, List<Arbitro> arbitri){
int sizeSquadre = squadre.size();
if((sizeSquadre & (sizeSquadre - 1)) == 0){
int sizeArbitri = arbitri.size();
int k = 1;
Integer[] indexSquadre = new Integer[sizeSquadre];
for (int i = 0; i < indexSquadre.length; i++) {
indexSquadre[i] = i;
}
Integer[] indexArbitri = new Integer[sizeArbitri];
for (int i = 0; i < indexArbitri.length; i++) {
indexArbitri[i] = i;
}
Collections.shuffle(Arrays.asList(indexSquadre));
for(int i = 0; i < sizeSquadre; i += 2){
Collections.shuffle(Arrays.asList(indexArbitri));
int j = 0;
partite.add(new Partita(k, squadre.get(indexSquadre[i]), squadre.get(indexSquadre[i+1]), arbitri.get(indexArbitri[j]), squadre.get(indexSquadre[i]).getCittaProvenienza(), StatoPartita.PROGRAMMATA));
j++;
k++;
partite.add(new Partita(k, squadre.get(indexSquadre[i+1]), squadre.get(indexSquadre[i]), arbitri.get(indexArbitri[j]), squadre.get(indexSquadre[i+1]).getCittaProvenienza(), StatoPartita.PROGRAMMATA));
j++;
k++;
}
//for solo per controllare se funziona
for(int i = 0; i<partite.size(); i++){
System.out.println(partite.get(i).getSquadraCasa().getNome() + " " + partite.get(i).getSquadraOspite().getNome());
}
torneo = new EliminazioneDiretta(nomeTorneo, partite);
tornei.add(torneo);
} else {
System.out.println("Mi dispiace, non è possibile creare un torneo ad eliminazione diretta, serve che il numero delle squadre sia una potenza di due");
}
}
示例9: Shuffled
import java.util.Collections; //导入方法依赖的package包/类
/**
* Ctor.
* @param iterator The original iterator
*/
public Shuffled(final Iterator<T> iterator) {
this.scalar = new UncheckedScalar<>(
new StickyScalar<>(
() -> {
final List<T> items = new LinkedList<>();
while (iterator.hasNext()) {
items.add(iterator.next());
}
Collections.shuffle(items);
return items.iterator();
}
)
);
}
示例10: updateEmploymentStatusBasedOnJobChange
import java.util.Collections; //导入方法依赖的package包/类
/**
*
*/
public static void updateEmploymentStatusBasedOnJobChange(double deltaJob, int iYear) {
double percentLiveInWorkIn = (double)Population.getInitLiveInWorkIn()/((double)Population.getInitLiveInWorkIn() + (double)Population.getInitLiveOutWorkIn());
double percentLiveOutWorkIn = 1 - percentLiveInWorkIn;
if (deltaJob<0) {
int lostJobsLiveInWorkIn = (int)(deltaJob*percentLiveInWorkIn);
int lostJobsLiveOutWorkIn = (int)(deltaJob*percentLiveOutWorkIn);
// updates the number of people commuting into the region for work
int newPeopleLiveOutWorkIn = Math.max(0, Population.getCrnLiveOutWorkIn() + lostJobsLiveOutWorkIn);
Population.setCrnLiveOutWorkIn(newPeopleLiveOutWorkIn);
// gets ID of employed individuals working in the region and shuffle them
ArrayList<Integer> employedIndivID = PopulationAnalytics.getIDIndivs(EmploymentStatus.employed, PlaceOfWork.in);
Collections.shuffle(employedIndivID,HardcodedData.random);
// changes deltaJobsLiveInWorkIn people from employed to unEmployed or nonLabour (if the individual is older than retired age)
for (int i=0; i<=Math.abs(lostJobsLiveInWorkIn)-1; i++) {
Integer selID = employedIndivID.get(i);
if (Population.getIndivPool().get(selID).getAge()>=HardcodedData.retiredAge) {
Population.getIndivPool().get(selID).setEmpStat(EmploymentStatus.nonLabour);
} else {
Population.getIndivPool().get(selID).setEmpStat(EmploymentStatus.unEmployed);
}
// set workplace to null for this individual;
Population.getIndivPool().get(selID).setWorkPlace(null);
}
} else {
//handleNewJobs_v1(deltaJob, percentLiveInWorkIn, percentLiveOutWorkIn, iYear);
handleNewJobs_v2(deltaJob, percentLiveInWorkIn, percentLiveOutWorkIn, iYear);
}
}
示例11: doInBackground
import java.util.Collections; //导入方法依赖的package包/类
@Override protected List<Country> doInBackground(Void... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
return null;
}
List<Country> countries = CountryApi.getCountries();
Collections.shuffle(countries);
return countries;
}
示例12: process
import java.util.Collections; //导入方法依赖的package包/类
@Override
protected void process(ReasonClaimWarrantContainer reasonClaimWarrantContainer)
{
MTurkHITContainerReasonClaimWarrantOriginal.HITReasonClaimWarrantOriginalValidation reasonClaimWarrant
= new MTurkHITContainerReasonClaimWarrantOriginal.HITReasonClaimWarrantOriginalValidation(
reasonClaimWarrantContainer.getDebateMetaData().getTitle(),
reasonClaimWarrantContainer.getDebateMetaData().getDescription(),
reasonClaimWarrantContainer.getReasonClaimWarrantId(),
reasonClaimWarrantContainer.getAnnotatedStance(),
reasonClaimWarrantContainer.getAlternativeWarrant(),
reasonClaimWarrantContainer.getReasonGist());
List<MTurkHITContainerReasonClaimWarrantOriginal.ValidationWarrant> list = new ArrayList<>();
list.add(new MTurkHITContainerReasonClaimWarrantOriginal.ValidationWarrant(0,
reasonClaimWarrantContainer.getAlternativeWarrant()));
list.add(new MTurkHITContainerReasonClaimWarrantOriginal.ValidationWarrant(1,
reasonClaimWarrantContainer.getOriginalWarrant()));
Collections.shuffle(list, random);
list.add(new MTurkHITContainerReasonClaimWarrantOriginal.ValidationWarrant(2,
"neither of them makes sense"));
reasonClaimWarrant.validationWarrants.addAll(list);
this.buffer.add(reasonClaimWarrant);
}
开发者ID:UKPLab,项目名称:argument-reasoning-comprehension-task,代码行数:28,代码来源:Step8aTaskValidationHITCreator.java
示例13: testSortAndDedupByteRefArray
import java.util.Collections; //导入方法依赖的package包/类
public void testSortAndDedupByteRefArray() {
SortedSet<BytesRef> set = new TreeSet<>();
final int numValues = scaledRandomIntBetween(0, 10000);
List<BytesRef> tmpList = new ArrayList<>();
BytesRefArray array = new BytesRefArray(Counter.newCounter());
for (int i = 0; i < numValues; i++) {
String s = randomRealisticUnicodeOfCodepointLengthBetween(1, 100);
set.add(new BytesRef(s));
tmpList.add(new BytesRef(s));
array.append(new BytesRef(s));
}
if (randomBoolean()) {
Collections.shuffle(tmpList, random());
for (BytesRef ref : tmpList) {
array.append(ref);
}
}
int[] indices = new int[array.size()];
for (int i = 0; i < indices.length; i++) {
indices[i] = i;
}
int numUnique = CollectionUtils.sortAndDedup(array, indices);
assertThat(numUnique, equalTo(set.size()));
Iterator<BytesRef> iterator = set.iterator();
BytesRefBuilder spare = new BytesRefBuilder();
for (int i = 0; i < numUnique; i++) {
assertThat(iterator.hasNext(), is(true));
assertThat(array.get(spare, indices[i]), equalTo(iterator.next()));
}
}
示例14: test
import java.util.Collections; //导入方法依赖的package包/类
public void test(int nrTasks, int... nrConcurrent) {
try {
configureLogging();
HibernateUtil.configureHibernate(ApplicationProperties.getProperties());
startServer();
List<Operation> operations = operations();
Collections.shuffle(operations);
for (int c: nrConcurrent) {
run(nrTasks <= 0 || operations.size() <= nrTasks ? operations : operations.subList(0, nrTasks), c);
}
logCounters();
writeReports();
stopServer();
} catch (Exception e) {
sLog.fatal("Test failed: " + e.getMessage(), e);
} finally {
close();
}
}
示例15: processRewardsSimple
import java.util.Collections; //导入方法依赖的package包/类
private static void processRewardsSimple(final List<Integer> returnArray, final int[] list) {
for (int i = 0; i < list.length; i++) {
returnArray.add(list[i]);
}
Collections.shuffle(returnArray);
}