List of usage examples for java.util Collections shuffle
public static void shuffle(List<?> list)
From source file:com.linkedin.pinot.routing.builder.BalancedRandomRoutingTableBuilder.java
@Override public synchronized List<ServerToSegmentSetMap> computeRoutingTableFromExternalView(String tableName, ExternalView externalView, List<InstanceConfig> instanceConfigList) { RoutingTableInstancePruner pruner = new RoutingTableInstancePruner(instanceConfigList); List<Map<String, Set<String>>> routingTables = new ArrayList<Map<String, Set<String>>>(); for (int i = 0; i < _numberOfRoutingTables; ++i) { routingTables.add(new HashMap<String, Set<String>>()); }/*from ww w.jav a 2 s . c om*/ String[] segmentSet = externalView.getPartitionSet().toArray(new String[0]); for (String segment : segmentSet) { Map<String, String> instanceToStateMap = externalView.getStateMap(segment); for (String instance : instanceToStateMap.keySet().toArray(new String[0])) { if (!instanceToStateMap.get(instance).equals("ONLINE") || pruner.isInactive(instance)) { LOGGER.info("Removing offline/inactive instance '{}' from routing table computation", instance); instanceToStateMap.remove(instance); } } if (instanceToStateMap.size() > 0) { List<String> instanceList = new ArrayList<String>(instanceToStateMap.keySet()); for (int i = 0; i < _numberOfRoutingTables; ++i) { Collections.shuffle(instanceList); String[] instances = instanceList.toArray(new String[instanceList.size()]); int minInstances = Integer.MAX_VALUE; int minIdx = -1; int base = 2; for (int k = 0; k < instances.length; ++k) { int sizeOfCurrentInstance = 0; if (routingTables.get(i).containsKey(instances[k])) { sizeOfCurrentInstance = routingTables.get(i).get(instances[k]).size(); } if (sizeOfCurrentInstance < minInstances) { minInstances = sizeOfCurrentInstance; minIdx = k; base = 2; } if (sizeOfCurrentInstance == minInstances && (System.currentTimeMillis() % base == 0)) { minIdx = k; base = 2; } else { base++; } } if (routingTables.get(i).containsKey(instances[minIdx])) { routingTables.get(i).get(instances[minIdx]).add(segment); } else { Set<String> instanceSegmentSet = new HashSet<String>(); instanceSegmentSet.add(segment); routingTables.get(i).put(instances[minIdx], instanceSegmentSet); } } } } List<ServerToSegmentSetMap> resultRoutingTableList = new ArrayList<ServerToSegmentSetMap>(); for (int i = 0; i < _numberOfRoutingTables; ++i) { resultRoutingTableList.add(new ServerToSegmentSetMap(routingTables.get(i))); } return resultRoutingTableList; }
From source file:com.splicemachine.stream.StreamableRDDTest.java
@Test public void testOrder() throws Exception { StreamListener<ExecRow> sl = new StreamListener<>(); HostAndPort hostAndPort = server.getHostAndPort(); server.register(sl);/*from w w w.j a v a 2 s . c o m*/ List<Tuple2<ExecRow, ExecRow>> shuffledRows = new ArrayList<>(tenRows); Collections.shuffle(shuffledRows); JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContext().parallelizePairs(shuffledRows, 10); JavaRDD<ExecRow> sorted = rdd.values().sortBy(new Function<ExecRow, Integer>() { @Override public Integer call(ExecRow execRow) throws Exception { return execRow.getColumn(1).getInt(); } }, true, 4); StreamableRDD srdd = new StreamableRDD(sorted, sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort()); srdd.submit(); Iterator<ExecRow> it = sl.getIterator(); int count = 0; int last = -1; while (it.hasNext()) { ExecRow execRow = it.next(); LOG.trace(execRow); count++; assertNotNull(execRow); int value = execRow.getColumn(1).getInt(); assertTrue("Results not in order", value > last); last = value; } assertEquals(10, count); }
From source file:MSUmpire.SeqUtility.ShuffledSeqGen.java
private String shuffle(String s) { ArrayList<Character> list = new ArrayList<>(); ArrayList<Integer> KRP = new ArrayList<>(); for (int i = 0; i < s.length(); i++) { // if(i>0 && s.charAt(i) == 'P' &&(s.charAt(i-1) == 'K' || s.charAt(i-1) == 'R')){ // KRP.add(i); // } if (s.charAt(i) == 'K' || s.charAt(i) == 'R' || s.charAt(i) == 'P') { KRP.add(i);/*from w w w .j a va2 s. co m*/ } else { list.add(s.charAt(i)); } } Collections.shuffle(list); String shuffledSeq = ""; int offset = 0; for (int i = 0; i < s.length(); i++) { if (KRP.contains(i)) { shuffledSeq += String.valueOf(s.charAt(i)); offset++; } else { shuffledSeq += String.valueOf(list.get(i - offset)); } } return shuffledSeq; }
From source file:com.tealcube.minecraft.bukkit.mythicdrops.tiers.TierMap.java
public Tier getRandomWithIdentifyChance() { double totalWeight = 0; List<Tier> v = new ArrayList<>(values()); Collections.shuffle(v); for (Tier t : v) { totalWeight += t.getIdentifyChance(); }/*w w w .j a va2 s.c o m*/ double chosenWeight = MythicDropsPlugin.getInstance().getRandom().nextDouble() * totalWeight; double currentWeight = 0; for (Tier t : v) { currentWeight += t.getIdentifyChance(); if (currentWeight >= chosenWeight) { return t; } } return null; }
From source file:com.classiqo.nativeandroid_32bitz.model.MusicProvider.java
public Iterable<MediaMetadataCompat> getShuffledMusic() { if (mCurrentState != State.INITIALIZED) { return Collections.emptyList(); }/*from ww w.ja v a2s . c o m*/ List<MediaMetadataCompat> shuffled = new ArrayList<>(mMusicListById.size()); for (MutableMediaMetadata mutableMediaMetadata : mMusicListById.values()) { shuffled.add(mutableMediaMetadata.metadata); } Collections.shuffle(shuffled); return shuffled; }
From source file:eu.ggnet.dwoss.rights.assist.gen.RightsGeneratorOperation.java
private static List<AtomicRight> getRandomRights() { List<AtomicRight> rights = Arrays.asList(AtomicRight.values()); Collections.shuffle(rights); int till = (int) (Math.random() * rights.size() - 1) + 1; rights = rights.subList(0, till);/*from w w w .j av a 2s. c o m*/ return rights; }
From source file:de.tor.tribes.util.algo.BruteForce.java
@Override public List<TroopMovement> calculateAttacks(HashMap<UnitHolder, List<Village>> pSources, HashMap<UnitHolder, List<Village>> pFakes, List<Village> pTargets, List<Village> pFakeTargets, HashMap<Village, Integer> pMaxAttacksTable, TimeFrame pTimeFrame, boolean pFakeOffTargets) { List<Village> allTargets = Arrays.asList(pTargets.toArray(new Village[pTargets.size()])); List<Village> allFakeTargets = Arrays.asList(pFakeTargets.toArray(new Village[pFakeTargets.size()])); HashMap<Village, HashMap<UnitHolder, List<Village>>> attacks = new HashMap<>(); logger.debug("Assigning offs"); logText("Starte zufllige Berechnung"); int maxStatus = allTargets.size() + allFakeTargets.size(); int currentStatus = 0; // <editor-fold defaultstate="collapsed" desc=" Assign Offs"> logInfo(" Starte Berechnung fr Offs"); for (UnitHolder unit : pSources.keySet()) { logInfo(" - Starte Berechnung fr Einheit '" + unit.getName() + "'"); List<Village> sources = pSources.get(unit); if (sources != null) { logInfo(" - Verwende " + sources.size() + " Herkunftsdrfer"); for (Village source : sources) { //time when the attacks should arrive Village vTarget = null;/*from w ww . j a v a2s . co m*/ //distribute targets randomly Collections.shuffle(pTargets); currentStatus = allTargets.size() - pTargets.size(); updateStatus(currentStatus, maxStatus); //search all targets logInfo(" - Teste " + pTargets.size() + " mgliche Ziele"); for (Village v : pTargets.toArray(new Village[pTargets.size()])) { if (isAborted()) { return new LinkedList<>(); } int maxAttacksPerVillage = pMaxAttacksTable.get(v); double time = DSCalculator.calculateMoveTimeInSeconds(source, v, unit.getSpeed()); if (unit.getPlainName().equals("snob")) { if (DSCalculator.calculateDistance(source, v) > ServerSettings.getSingleton() .getSnobRange()) { //continue with the next destination Village continue; } } long runtime = (long) time * 1000; //check if attack is somehow possible if (pTimeFrame.isMovementPossible(runtime)) { //only calculate if time is in time frame //get list of source villages for current target HashMap<UnitHolder, List<Village>> attacksForVillage = attacks.get(v); if (attacksForVillage == null) { //create new table of attacks attacksForVillage = new HashMap<>(); List<Village> sourceList = new LinkedList<>(); logInfo(" * Neue Truppenbewegung: " + source + " -> " + v); sourceList.add(source); attacksForVillage.put(unit, sourceList); attacks.put(v, attacksForVillage); vTarget = v; } else { int currentAttacks = 0; for (List<Village> l : attacksForVillage.values()) { currentAttacks += l.size(); } //there are already attacks on this village if (currentAttacks < maxAttacksPerVillage) { //more attacks on this village are allowed boolean added = false; //max number of attacks neither for villages nor for player reached List<Village> attsPerUnit = attacksForVillage.get(unit); if (attsPerUnit != null) { if (!attsPerUnit.contains(source) || (unit .equals(DataHolder.getSingleton().getUnitByPlainName("snob")) && multipleSameSnobsAllowed())) { //only add source if it does not attack current target yet added = true; logInfo(" * Neue Truppenbewegung: " + source + " -> " + v); attsPerUnit.add(source); } } else { attsPerUnit = new LinkedList<>(); //only add source if it does not attack current target yet added = true; logInfo(" * Neue Truppenbewegung: " + source + " -> " + v); attsPerUnit.add(source); attacksForVillage.put(unit, attsPerUnit); } if (added) { //only increment attack count if source was added vTarget = v; //check if last missing attack was added. if (currentAttacks + 1 == maxAttacksPerVillage) { logInfo(" * Entferne vollstndiges Ziel " + v); pTargets.remove(v); } } else { vTarget = null; } } else { //max number of attacks per village reached, continue search logInfo(" * Entferne vollstndiges Ziel " + v); pTargets.remove(v); vTarget = null; } } } if (vTarget != null) { break; } } if (vTarget == null) { logInfo(" - Keine Ziele fr Herkunftsdorf " + source + " gefunden"); } } } else { logInfo(" - Keine Herkunftsdrfer fr aktuelle Einheit"); } } // </editor-fold> if (pFakeOffTargets) { /* * why would we do this? We should allow one fake for each missing off, so we can simply use pTargets as is? * logger.debug("Removing assigned off targets from fake list"); Enumeration<Village> targets = attacks.keys(); while (targets.hasMoreElements()) { Village target = targets.nextElement(); pTargets.remove(target); }*/ logger.debug("Keeping remaining Off targets for fake search"); } else { //clear target list pTargets.clear(); } //adding fake targets for (Village fakeTarget : pFakeTargets) { pTargets.add(fakeTarget); } logger.debug("Assigning fakes"); logText(" Starte Berechnung fr Fakes."); // <editor-fold defaultstate="collapsed" desc=" Assign fakes"> HashMap<Village, HashMap<UnitHolder, List<Village>>> fakes = new HashMap<>(); for (UnitHolder unit : pFakes.keySet()) { logInfo(" - Starte Berechnung fr Einheit '" + unit.getName() + "'"); List<Village> sources = pFakes.get(unit); if (sources != null) { logInfo(" - Verwende " + sources.size() + " Herkunftsdrfer"); for (Village source : sources) { //time when the attacks should arrive Village vTarget = null; //distribute targets randomly Collections.shuffle(pTargets); currentStatus = allTargets.size() + allFakeTargets.size() - pTargets.size(); updateStatus(currentStatus, maxStatus); //search all targets logInfo(" - Teste " + pTargets.size() + " mgliche Ziele"); for (Village v : pTargets.toArray(new Village[pTargets.size()])) { if (isAborted()) { return new LinkedList<>(); } int maxAttacksPerVillage = pMaxAttacksTable.get(v); double time = DSCalculator.calculateMoveTimeInSeconds(source, v, unit.getSpeed()); if (unit.getPlainName().equals("snob")) { if (DSCalculator.calculateDistance(source, v) > ServerSettings.getSingleton() .getSnobRange()) { //continue with the next destination Village continue; } } long runtime = (long) time * 1000; //check if attack is somehow possible if (pTimeFrame.isMovementPossible(runtime)) { //only calculate if time is in time frame //get list of source villages for current target HashMap<UnitHolder, List<Village>> attacksForVillage = attacks.get(v); HashMap<UnitHolder, List<Village>> fakesForVillage = fakes.get(v); if (attacksForVillage == null) { //create empty table of attacks (will stay empty, but is used for maxAttacks calculation) attacksForVillage = new HashMap<>(); List<Village> sourceList = new LinkedList<>(); attacksForVillage.put(unit, sourceList); } if (fakesForVillage == null) { //create new table of fakes fakesForVillage = new HashMap<>(); List<Village> sourceList = new LinkedList<>(); logInfo(" * Neue Truppenbewegung: " + source + " -> " + v); sourceList.add(source); fakesForVillage.put(unit, sourceList); fakes.put(v, fakesForVillage); vTarget = v; } else { int currentAttacks = 0; for (List<Village> listV : attacksForVillage.values()) { currentAttacks += listV.size(); } int currentFakes = 0; for (List<Village> listV : fakesForVillage.values()) { currentFakes += listV.size(); } //there are already attacks or fakes on this village if (currentAttacks + currentFakes < maxAttacksPerVillage) { //more attacks on this village are allowed boolean added = false; //max number of attacks neither for villages nor for player reached List<Village> attsPerUnit = attacksForVillage.get(unit); List<Village> fakesPerUnit = fakesForVillage.get(unit); if (fakesPerUnit != null) { if (!attsPerUnit.contains(source) && (attsPerUnit == null || !attsPerUnit.contains(source))) { //only add source if it does not attack current target yet added = true; logInfo(" * Neue Truppenbewegung: " + source + " -> " + v); fakesPerUnit.add(source); } } else { fakesPerUnit = new LinkedList<>(); //only add source if it does not attack current target yet added = true; logInfo(" * Neue Truppenbewegung: " + source + " -> " + v); fakesPerUnit.add(source); fakesForVillage.put(unit, attsPerUnit); } if (added) { //only increment attack count if source was added vTarget = v; //check if last missing attack was added. if (currentAttacks + currentFakes + 1 == maxAttacksPerVillage) { logInfo(" * Entferne vollstndiges Ziel " + v); pTargets.remove(v); } } else { vTarget = null; } } else { //max number of attacks per village reached, continue search logInfo(" * Entferne vollstndiges Ziel " + v); pTargets.remove(v); vTarget = null; } } } if (vTarget != null) { break; } } if (vTarget == null) { logInfo(" - Keine Ziele fr Herkunftsdorf " + source + " gefunden"); } } } else { logInfo(" - Keine Herkunftsdrfer fr aktuelle Einheit"); } } updateStatus(maxStatus, maxStatus); // </editor-fold> logText(" - Erstelle Ergebnisliste"); //convert to result list List<TroopMovement> movements = new LinkedList<>(); logger.debug(" - adding offs"); logText(String.format(" %d Offs berechnet", attacks.size())); for (Village target : allTargets) { HashMap<UnitHolder, List<Village>> sourcesForTarget = attacks.get(target); TroopMovement f = new TroopMovement(target, pMaxAttacksTable.get(target), Attack.CLEAN_TYPE); if (sourcesForTarget != null) { for (UnitHolder sourceUnit : sourcesForTarget.keySet()) { List<Village> unitVillages = attacks.get(target).get(sourceUnit); for (Village source : unitVillages) { f.addOff(sourceUnit, source); } } } if (sourcesForTarget == null && fakes.get(target) != null) { //ignore Off targets, when there are Fakes assigned and no Offs continue; } movements.add(f); } logger.debug(" - adding fakes"); logText(String.format(" %d Fakes berechnet", fakes.size())); for (Village target : (List<Village>) ListUtils.union(allFakeTargets, allTargets)) { HashMap<UnitHolder, List<Village>> sourcesForTarget = fakes.get(target); TroopMovement f = new TroopMovement(target, pMaxAttacksTable.get(target), Attack.FAKE_TYPE); if (sourcesForTarget != null) { for (UnitHolder sourceUnit : sourcesForTarget.keySet()) { List<Village> unitVillages = fakes.get(target).get(sourceUnit); for (Village source : unitVillages) { f.addOff(sourceUnit, source); } } } if (sourcesForTarget == null && allTargets.contains(target)) { //ignore Off targets, where no Fakes were assigned continue; } movements.add(f); } logText("Berechnung abgeschlossen."); return movements; }
From source file:com.hyphenated.card.service.GameServiceImpl.java
@Override @Transactional// ww w . j a va 2 s . co m @GameAction public Game startGame(Game game) { game = gameDao.merge(game); if (game.getPlayers().size() < 2) { throw new IllegalStateException("Not Enough Players"); } if (game.getPlayers().size() > 10) { throw new IllegalStateException("Too Many Players"); } if (game.isStarted()) { throw new IllegalStateException("Game already started"); } //Set started flag game.setStarted(true); //Start at the first blind level for the game GameStructure gs = game.getGameStructure(); List<BlindLevel> blinds = gs.getBlindLevels(); Collections.sort(blinds); gs.setCurrentBlindLevel(blinds.get(0)); //Get all players associated with the game. //Assign random position. Save the player. List<Player> players = new ArrayList<Player>(); players.addAll(game.getPlayers()); Collections.shuffle(players); for (int i = 0; i < players.size(); i++) { Player p = players.get(i); p.setGamePosition(i + 1); playerDao.save(p); } //Set Button and Big Blind. Button is position 1 (index 0) Collections.sort(players); game.setPlayerInBTN(players.get(0)); //Save and return the updated game return gameDao.merge(game); }
From source file:net.sf.gazpachoquest.questionnaire.resolver.QuestionByQuestionResolver.java
@Override protected List<QuestionBreadcrumb> makeBreadcrumbs(QuestionnaireDefinition questionnaireDefinition, Questionnaire questionnaire) {/*from w w w. j a v a2s .co m*/ List<QuestionBreadcrumb> breadcrumbs = new ArrayList<>(); QuestionBreadcrumb breadcrumb = null; Integer questionnairDefinitionId = questionnaireDefinition.getId(); RandomizationStrategy randomizationStrategy = questionnaireDefinition.getRandomizationStrategy(); Integer questionNumberCounter = QUESTION_NUMBER_START_COUNTER; if (RandomizationStrategy.SECTIONS_RANDOMIZATION.equals(randomizationStrategy)) { List<Section> sections = sectionService.findByExample( Section.with() .questionnaireDefinition( QuestionnaireDefinition.with().id(questionnairDefinitionId).build()) .build(), new SearchParameters()); Collections.shuffle(sections); for (Section section : sections) { List<Question> questions = findQuestions(section); for (Question question : questions) { breadcrumb = QuestionBreadcrumb.with().questionnaire(questionnaire).last(Boolean.FALSE) .question(question).renderingMode(RenderingMode.QUESTION_BY_QUESTION) .questionNumber(questionNumberCounter++).build(); breadcrumbs.add(breadcrumb); } } } else if (RandomizationStrategy.QUESTIONS_RANDOMIZATION.equals(randomizationStrategy)) { List<Question> questions = questionnaireDefinitionService.getQuestions(questionnairDefinitionId); Collections.shuffle(questions); for (Question question : questions) { breadcrumb = QuestionBreadcrumb.with().questionnaire(questionnaire).last(Boolean.FALSE) .question(question).renderingMode(RenderingMode.QUESTION_BY_QUESTION) .questionNumber(questionNumberCounter++).build(); breadcrumbs.add(breadcrumb); } } else { Question question = findFirstQuestion(questionnairDefinitionId); breadcrumb = QuestionBreadcrumb.with().questionnaire(questionnaire).last(Boolean.FALSE) .renderingMode(RenderingMode.QUESTION_BY_QUESTION).question(question) .questionNumber(questionNumberCounter).build(); breadcrumbs.add(breadcrumb); } breadcrumbs.get(0).setLast(Boolean.TRUE); return breadcrumbs; }
From source file:modelcreation.ModelCreation.java
public static double apply10FoldCrossValidation(double[][] x, double[] y) { int subSize = y.length / 10; ArrayList<Integer> indeces = new ArrayList(); for (int i = 0; i < y.length; i++) { indeces.add(i);/*ww w. j a va 2 s.c o m*/ } Collections.shuffle(indeces); double[] meanSquaredErrors = new double[10]; int count = 0; for (int i = 0; i < 10; i++) { System.out.println("-------------Fold " + i + "--------------"); double[][] subXTest = new double[subSize][2]; double[] subYTest = new double[subSize]; double[][] subXTraining = new double[y.length - subSize][2]; double[] subYTraining = new double[y.length - subSize]; for (int j = 0; j < i * subSize; j++) { int index = indeces.get(count); count++; subXTraining[j][0] = x[index][0]; subXTraining[j][1] = x[index][1]; subYTraining[j] = y[index]; } for (int j = 0; j < subSize; j++) { int index = indeces.get(count); count++; subXTest[j][0] = x[index][0]; subXTest[j][1] = x[index][1]; subYTest[j] = y[index]; } for (int j = i * subSize; j < y.length - subSize; j++) { int index = indeces.get(count); count++; subXTraining[j][0] = x[index][0]; subXTraining[j][1] = x[index][1]; subYTraining[j] = y[index]; } count = 0; OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression(); regression.newSampleData(subYTraining, subXTraining); regression.setNoIntercept(true); meanSquaredErrors[i] = evaluateModel(regression, subXTest, subYTest); } double sum = 0; for (int i = 0; i < meanSquaredErrors.length; i++) { sum += meanSquaredErrors[i]; } return (double) sum / meanSquaredErrors.length; }