Example usage for java.util Collections shuffle

List of usage examples for java.util Collections shuffle

Introduction

In this page you can find the example usage for java.util Collections shuffle.

Prototype

public static void shuffle(List<?> list) 

Source Link

Document

Randomly permutes the specified list using a default source of randomness.

Usage

From source file:com.netflix.iep.dynprop.RemoteConfigurationSource.java

private List<String> getHostsForVip(String vip, boolean useIp) {
    List<InstanceInfo> instances = client.getInstancesByVipAddress(vip, false);
    List<String> filtered = new ArrayList<>(instances.size());
    for (InstanceInfo info : instances) {
        if (info.getStatus() == InstanceInfo.InstanceStatus.UP) {
            String host = useIp ? info.getIPAddr() : info.getHostName();
            filtered.add(host + ":" + info.getPort());
        }//from w  ww  .j a  v a 2 s.c  o  m
    }
    Collections.shuffle(filtered);
    return filtered;
}

From source file:net.sf.gazpachoquest.questionnaire.resolver.SectionBySectionResolver.java

@Override
protected List<SectionBreadcrumb> makeBreadcrumbs(QuestionnaireDefinition questionnaireDefinition,
        Questionnaire questionnaire) {/*from   www. j  a v  a  2 s.co m*/
    List<SectionBreadcrumb> breadcrumbs = new ArrayList<>();
    SectionBreadcrumb breadcrumb = null;
    Integer questionnaireDefinitionId = questionnaireDefinition.getId();
    RandomizationStrategy randomizationStrategy = questionnaireDefinition.getRandomizationStrategy();
    if (RandomizationStrategy.SECTIONS_RANDOMIZATION.equals(randomizationStrategy)) {
        List<Section> sections = sectionService.findByExample(
                Section.with()
                        .questionnaireDefinition(
                                QuestionnaireDefinition.with().id(questionnaireDefinitionId).build())
                        .build(),
                new SearchParameters());
        Collections.shuffle(sections);
        for (Section section : sections) {
            breadcrumb = SectionBreadcrumb.with().questionnaire(questionnaire).section(section)
                    .last(Boolean.FALSE).renderingMode(RenderingMode.SECTION_BY_SECTION).build();
            breadcrumbs.add(breadcrumb);
        }
        populateQuestionsBreadcrumbs(breadcrumbs, QUESTION_NUMBER_START_COUNTER);
    } else if (RandomizationStrategy.QUESTIONS_RANDOMIZATION.equals(randomizationStrategy)) {
        List<Question> questions = questionnaireDefinitionService.getQuestions(questionnaireDefinitionId);
        Collections.shuffle(questions);
        Integer questionPerPage = questionnaireDefinition.getQuestionsPerPage();
        int questionIdx = 0;
        Integer questionNumberCounter = QUESTION_NUMBER_START_COUNTER;
        for (Question question : questions) {
            if (questionIdx % questionPerPage == 0) {
                breadcrumb = SectionBreadcrumb.with().questionnaire(questionnaire).last(Boolean.FALSE)
                        .renderingMode(RenderingMode.SECTION_BY_SECTION).build();
                breadcrumbs.add(breadcrumb);
            }
            breadcrumb.addBreadcrumb(QuestionBreadcrumb.with().question(question).last(Boolean.FALSE)
                    .questionNumber(questionNumberCounter++).build());
            questionIdx++;
        }

    } else {
        Section section = sectionService.findOneByPositionInQuestionnaireDefinition(questionnaireDefinitionId,
                INITIAL_POSITION);
        breadcrumb = SectionBreadcrumb.with().questionnaire(questionnaire).section(section)
                .renderingMode(RenderingMode.SECTION_BY_SECTION).build();
        breadcrumbs.add(breadcrumb);
        populateQuestionsBreadcrumbs(breadcrumbs, QUESTION_NUMBER_START_COUNTER);
    }
    breadcrumbs.get(0).setLast(Boolean.TRUE);
    return breadcrumbs;
}

From source file:de.whs.poodle.controllers.student.StudentMcWorksheetController.java

@RequestMapping
@PreAuthorize("@studentSecurity.hasAccessToMcWorksheet(authentication.name, #mcWorksheetId)")
public String get(@ModelAttribute Student student, @PathVariable int mcWorksheetId, Model model) {
    // get the worksheet
    McWorksheet mcWorksheet = mcWorksheetRepo.getByMcWorksheetId(mcWorksheetId);
    if (mcWorksheet == null)
        throw new NotFoundException();

    // get the question that the student has to answer next
    Integer currentQuestionId = mcWorksheetRepo.getCurrentQuestionIdForStudentAndWorksheet(student.getId(),
            mcWorksheetId);/*from w  w  w  .j  a  v a2  s.  c  o m*/

    // no next question, this must mean that the worksheets has been completed, show the results
    if (currentQuestionId == null) {
        return "redirect:/student/multipleChoiceResults/{mcWorksheetId}";
    }

    // get the question
    McQuestionOnWorksheet currentQuestion = mcWorksheet.getQuestions().stream()
            .filter(q -> q.getId() == currentQuestionId).findFirst().orElse(null);

    if (currentQuestion == null)
        throw new RuntimeException(
                "the current question for this worksheet is not in the worksheet, this shouldn't be possible...");

    // shuffle the answers
    Collections.shuffle(currentQuestion.getQuestion().getAnswers());

    // make sure to set a timestamp for "seen_at"
    mcWorksheetRepo.prepareMcStatistics(student.getId(), mcWorksheet.getCourseTerm().getId(),
            currentQuestion.getId());

    model.addAttribute("worksheet", mcWorksheet);
    model.addAttribute("questionOnWs", currentQuestion);

    return "student/answerMcQuestion";
}

From source file:co.mafiagame.engine.command.internalcommand.StartGameCommand.java

private void assignRoles(List<Player> players, GameState gameState) {
    Collections.shuffle(players);
    int assigned = 0;
    for (int i = 0; i < gameState.getCitizenNum(); i++)
        players.get(assigned + i).setRole(Role.CITIZEN);
    assigned += gameState.getCitizenNum();
    for (int i = 0; i < gameState.getMafiaNum(); i++)
        players.get(assigned + i).setRole(Role.MAFIA);
    assigned += gameState.getMafiaNum();
    for (int i = 0; i < gameState.getDetectiveNum(); i++)
        players.get(assigned + i).setRole(Role.DETECTIVE);
    assigned += gameState.getDetectiveNum();
    for (int i = 0; i < gameState.getDoctorNum(); i++)
        players.get(assigned + i).setRole(Role.DOCTOR);
    Collections.shuffle(players);
}

From source file:com.google.code.ssm.test.ReadThroughMultiCacheTest.java

@Test
public void test() {
    final Long rawNow = System.currentTimeMillis();
    final Long now = (rawNow / 1000) * 10000;
    final List<Long> subset = new ArrayList<Long>();
    final List<Long> superset = new ArrayList<Long>();
    final List<Long> jumbleset = new ArrayList<Long>();

    for (Long ix = 1 + now; ix < 35 + now; ix++) {
        if (ix % 3 == 0) {
            subset.add(ix);/* w  w w  .j  a  v a  2  s.  c o  m*/
        }
        superset.add(ix);
        jumbleset.add(ix);
    }
    Collections.shuffle(jumbleset);

    // final TestSvc test = (TestSvc) context.getBean("testSvc");

    // Get all the results for the subset ids.
    // Ensure the ids line up with the results, and have the same timestamp.
    final List<String> subsetResult = test.getTimestampValues(subset);
    assertEquals(subset.size(), subsetResult.size());
    String subsetTime = null;
    for (int ix = 0; ix < subset.size(); ix++) {
        final Long key = subset.get(ix);
        final String value = subsetResult.get(ix);
        System.out.println("Subset: " + value);
        final String[] parts = value.split("-X-");
        if (subsetTime == null) {
            subsetTime = parts[0];
        } else {
            assertEquals(subsetTime, parts[0]);
        }
        assertEquals(key.toString(), parts[1]);
    }

    // Now call the full list.
    // Ensure id's line up, and that results from ids that got passed in the subset
    // have the older time stamp.
    final List<String> supersetResult = test.getTimestampValues(superset);
    assertEquals(superset.size(), supersetResult.size());
    String supersetTime = null;
    for (int ix = 0; ix < superset.size(); ix++) {
        final Long key = superset.get(ix);
        final String value = supersetResult.get(ix);
        System.out.println("Superset: " + value);
        final String[] parts = value.split("-X-");
        final boolean inSubset = subset.contains(key);
        if (!inSubset && supersetTime == null) {
            supersetTime = parts[0];
        } else if (inSubset) {
            assertEquals(subsetTime, parts[0]);
        } else {
            assertEquals(supersetTime, parts[0]);
        }
        assertEquals(key.toString(), parts[1]);
    }

    // Now call for the results again, but with a randomized
    // set of keys. This is to ensure the proper values line up with
    // the given keys.
    final List<String> jumblesetResult = test.getTimestampValues(jumbleset);
    assertEquals(jumbleset.size(), jumblesetResult.size());
    for (int ix = 0; ix < jumbleset.size(); ix++) {
        final Long key = jumbleset.get(ix);
        final String value = jumblesetResult.get(ix);
        System.out.println("Jumbleset: " + value);
        final String[] parts = value.split("-X-");
        final boolean inSubset = subset.contains(key);
        if (inSubset) {
            assertEquals(subsetTime, parts[0]);
        } else {
            assertEquals(supersetTime, parts[0]);
        }
        assertEquals(key.toString(), parts[1]);
    }

}

From source file:com.linkedin.pinot.tools.query.comparison.StarTreeQueryGenerator.java

/**
 * Generate the aggregation section of the query, returns at least one aggregation.
 * @return//from ww  w .ja va  2s.co  m
 */
private String generateAggregations() {
    int numAggregations = _random.nextInt(_metricColumns.size() + 1);
    numAggregations = Math.max(numAggregations, 1);
    List<String> aggregations = new ArrayList<>(numAggregations);

    Collections.shuffle(_metricColumns);
    for (int i = 0; i < numAggregations; i++) {
        aggregations.add(generateAggregation(_metricColumns.get(i)));
    }

    return StringUtils.join(aggregations, ", ");
}

From source file:net.myrrix.batch.common.iterator.sequencefile.SequenceFileDirIterator.java

/**
 * Constructor that uses either {@link FileSystem#listStatus(Path)} or
 * {@link FileSystem#globStatus(Path)} to obtain list of files to iterate over
 * (depending on pathType parameter)./*w  w w. j a va2 s. co  m*/
 */
public SequenceFileDirIterator(Path path, PathType pathType, PathFilter filter, Comparator<FileStatus> ordering,
        final boolean reuseKeyValueInstances, final Configuration conf) throws IOException {

    FileStatus[] statuses;
    FileSystem fs = path.getFileSystem(conf);
    if (filter == null) {
        statuses = pathType == PathType.GLOB ? fs.globStatus(path) : fs.listStatus(path);
    } else {
        statuses = pathType == PathType.GLOB ? fs.globStatus(path, filter) : fs.listStatus(path, filter);
    }

    if (statuses == null) {
        statuses = NO_STATUSES;
    } else {
        if (ordering == null) {
            // If order does not matter, use a random order
            Collections.shuffle(Arrays.asList(statuses));
        } else {
            Arrays.sort(statuses, ordering);
        }
    }

    closer = Closer.create();

    Iterator<Iterator<Pair<K, V>>> fsIterators = Iterators.transform(Iterators.forArray(statuses),
            new Function<FileStatus, Iterator<Pair<K, V>>>() {
                @Override
                public Iterator<Pair<K, V>> apply(FileStatus from) {
                    try {
                        SequenceFileIterator<K, V> iterator = new SequenceFileIterator<K, V>(from.getPath(),
                                reuseKeyValueInstances, conf);
                        closer.register(iterator);
                        return iterator;
                    } catch (IOException ioe) {
                        throw new IllegalStateException(from.getPath().toString(), ioe);
                    }
                }
            });

    delegate = Iterators.concat(fsIterators);
}

From source file:de.unisb.cs.st.javalanche.rhino.coverage.CoberturaParser.java

private static void getCoveragePrioritization() {
    File[] files = getXmlFiles();
    Map<CoverageData, String> map = parseFiles(files);
    FailureMatrix fm = FailureMatrix/*  w ww.j av  a  2s .c  o m*/
            .parseFile(new File("/scratch/schuler/subjects/ibugs_rhino-0.1/failureMatrix.csv"));
    ArrayList<CoverageData> coverageDataList = new ArrayList<CoverageData>(map.keySet());
    List<List<PriorizationResult>> averageList = new ArrayList<List<PriorizationResult>>();
    final int SHUFFLES = 1000;
    for (int i = 1; i < SHUFFLES; i++) {
        if (i % 100 == 0) {
            System.out.println("Computing result " + i);
        }
        Collections.shuffle(coverageDataList);
        List<PriorizationResult> prioritizedTotal = CoverageData.prioritizeTotal(coverageDataList);
        averageList.add(new ArrayList<PriorizationResult>(prioritizedTotal));
        if (i == 1) {
            double[] averageData = generateAverageData(fm, averageList);
            writeRData(averageData, "total-coverage");
        }
    }
    double[] avarageData = generateAverageData(fm, averageList);
    writeRData(avarageData, "total-coverage-average");
    averageList = new ArrayList<List<PriorizationResult>>();
    for (int i = 1; i < SHUFFLES; i++) {
        if (i % 100 == 0) {
            System.out.println("Computing result " + i);
        }
        Collections.shuffle(coverageDataList);
        List<PriorizationResult> prioritizedAdditional = CoverageData.prioritizeAdditional(coverageDataList);
        averageList.add(new ArrayList<PriorizationResult>(prioritizedAdditional));
        if (i == 1) {
            double[] averageData = generateAverageData(fm, averageList);
            writeRData(averageData, "additional-coverage");
        }

    }
    double[] avarageDataAdd = generateAverageData(fm, averageList);
    writeRData(avarageDataAdd, "additional-coverage-average");
}

From source file:c5db.tablet.tabletCreationBehaviors.RootTabletLeaderBehavior.java

private List<Long> shuffleListAndReturnMetaRegionPeers(final List<Long> peers) {
    Collections.shuffle(new ArrayList<>(peers));
    return peers.subList(0, (int) numberOfMetaPeers);
}

From source file:com.google.android.apps.santatracker.games.cityquiz.CityQuizUtil.java

private static List<City> getCities(Context context) {
    List<City> cities = new ArrayList<>();
    JSONArray jCities = getCitiesFromFile(context);
    for (int i = 0; jCities != null && i < jCities.length(); i++) {
        try {//from  ww  w.ja  va  2s. c om
            JSONObject jCity = jCities.getJSONObject(i);
            double lat = jCity.getDouble("lat");
            double lng = jCity.getDouble("lng");
            String cityResourceName = jCity.getString("name");
            int cityNameResourceId = context.getResources().getIdentifier(cityResourceName, "string",
                    context.getPackageName());
            String cityName;
            // Check if city name string resource is found.
            if (cityNameResourceId != 0) {
                // Use string resource for city name.
                cityName = context.getResources().getString(cityNameResourceId);
            } else {
                // Use default English city name.
                cityName = jCity.getString("default_name");
            }
            String imageUrl = jCity.getString("image_name");
            String imageAuthor = jCity.getString("image_author");
            City city = new City(lat, lng, imageUrl, imageAuthor, cityName);
            cities.add(city);
        } catch (JSONException e) {
            Log.e(TAG, "Unable to get city from json, " + e);
        }
    }

    // Check if there are enough cities to set fake ones.
    if (cities.size() > 3) {
        // Set fake locations for each city.
        for (int i = 0; i < cities.size(); i++) {
            City city = cities.get(i);
            List<City> tempCities = new ArrayList<>(cities);
            // Sort tempCities in order of closest to the current city.
            Collections.sort(tempCities, new CityLocationComparator(city));

            // Get the closest three cities, excluding the current city.
            List<City> closestCities = tempCities.subList(1, 4);
            Collections.shuffle(closestCities);

            // Choose the first two of the three cities from the closestCities list.
            city.setIncorrectLoaciton(City.FIRST_FAKE_INDEX, closestCities.get(0).getCorrectLocation());
            city.setIncorrectLoaciton(City.SECOND_FAKE_INDEX, closestCities.get(1).getCorrectLocation());
        }
    }

    return cities;
}