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

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void shuffle(List<?> list, Random rnd) 

Source Link

Document

Randomly permute the specified list using the specified source of randomness.

Usage

From source file:edu.byu.nlp.al.RandomMeasurementSelector.java

/**
 * @param modelBuilder/*from   w  w  w. jav  a  2s  .  c om*/
 * @param annotations 
 */
public RandomMeasurementSelector(MeasurementModelBuilder modelBuilder, Dataset dataset,
        EmpiricalAnnotations<SparseFeatureVector, Integer> annotations, RandomGenerator rnd) {
    // we want to add all measurements that are not already taken (used as seed set contained in dataset)
    // FIXME: this is horrifically inefficient! Fix it! 
    for (FlatInstance<SparseFeatureVector, Integer> meas : annotations.getMeasurements()) {
        if (!dataset.getMeasurements().contains(meas)) {
            candidates.add(meas);
        }
    }
    for (Multimap<Integer, FlatInstance<SparseFeatureVector, Integer>> perAnnotatorAnnotations : annotations
            .getPerInstancePerAnnotatorAnnotations().values()) {
        for (FlatInstance<SparseFeatureVector, Integer> meas : perAnnotatorAnnotations.values()) {
            candidates.add(meas);
        }
    }
    Collections.shuffle(candidates, new RandomAdaptor(rnd));
}

From source file:org.messic.server.api.APIRandomLists.java

@Transactional
public List<RandomList> getAllLists(User user) {
    ArrayList<RandomList> result = new ArrayList<RandomList>();

    // we will get only 4 lists as maximum, each time different ones... so lets shuffle the lists
    long seed = System.nanoTime();
    ArrayList<RandomListPlugin> lplugins = new ArrayList<RandomListPlugin>();
    for (int i = 0; i < plugins.length; i++) {
        lplugins.add(plugins[i]);/*from   ww  w.  jav a  2 s  .  c o  m*/
    }
    Collections.shuffle(lplugins, new Random(seed));

    for (int i = 0; i < lplugins.size() && i < 4; i++) {
        long start = System.currentTimeMillis();

        RandomListPlugin rlp = lplugins.get(i);
        RandomList rl = rlp.getRandomList(user);
        if (rl != null && rl.getSongs().size() > 0) {
            result.add(rl);
        }

        long end = System.currentTimeMillis();

        log.debug("(" + ((end - start)) + "ms)-Timing obtaining info from plugin:" + rlp.getName());
    }

    return result;
}

From source file:emlab.repository.GenericRepository.java

public <T extends NodeBacked> Iterable<T> findAllAtRandom(Class<T> clazz) {
    List<T> list = Utils.asList(findAll(clazz));
    Collections.shuffle(list, new Random());
    return list;/*from   w w  w. ja  v  a  2 s. c  om*/
}

From source file:com.example.android.dragonTV.ui.VerticalGridFragment.java

private void setupFragment() {
    VerticalGridPresenter gridPresenter = new VerticalGridPresenter();
    gridPresenter.setNumberOfColumns(NUM_COLUMNS);
    setGridPresenter(gridPresenter);/*from  www.  j  av a 2  s . c o m*/

    mAdapter = new ArrayObjectAdapter(new CardPresenter());

    long seed = System.nanoTime();

    HashMap<String, List<Movie>> movies = VideoProvider.getMovieList();

    for (Map.Entry<String, List<Movie>> entry : movies.entrySet()) {
        List<Movie> list = entry.getValue();
        Collections.shuffle(list, new Random(seed));
        for (Movie movie : list) {
            mAdapter.add(movie);
        }
    }

    setAdapter(mAdapter);

    setOnItemViewSelectedListener(new OnItemViewSelectedListener() {
        @Override
        public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item,
                RowPresenter.ViewHolder rowViewHolder, Row row) {
            Log.i(TAG, "onItemSelected: " + item + " row " + row);
        }
    });

    setOnItemViewClickedListener(new OnItemViewClickedListener() {
        @Override
        public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item,
                RowPresenter.ViewHolder rowViewHolder, Row row) {
            Log.i(TAG, "onItemClicked: " + item + " row " + row);
        }
    });
    setOnSearchClickedListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getActivity(), SearchActivity.class);
            startActivity(intent);
        }
    });

    setOnItemViewClickedListener(new ItemViewClickedListener());
    setOnItemViewSelectedListener(new ItemViewSelectedListener());
}

From source file:interactivespaces.service.audio.player.jukebox.support.ShuffleJukeboxOperation.java

@Override
public synchronized void start() {
    if (!isRunning) {
        log.info("Starting music jukebox shuffle play");

        tracksToPlay = Lists.newArrayList(Iterables.transform(audioRepository.getAllPlayableTracks(),
                new Function<FilePlayableAudioTrack, String>() {
                    @Override/*from  w w w . j  av  a2 s  . c  o m*/
                    public String apply(FilePlayableAudioTrack input) {
                        return input.getMetadata().getId();
                    }
                }));

        Collections.shuffle(tracksToPlay, random);

        isRunning = true;

        startPlayingNewTrack();
    } else {
        log.warn("Trying to starting music jukebox shuffle play when already playing");
    }
}

From source file:emlab.repository.GenericRepository.java

public <T extends NodeBacked> T findOneAtRandom(Class<T> clazz) {
    List<T> list = Utils.asList(findAll(clazz));
    Collections.shuffle(list, new Random());
    return list.get(0);
}

From source file:additionalpipes.pipes.PipeFluidsTeleport.java

@Override
public int fill(ForgeDirection from, FluidStack resource, boolean doFill) {
    if (CoreProxy.proxy.isRenderWorld(container.worldObj)) {
        return 0;
    }//from  w  w w  . j a v  a2 s.c  o  m

    FluidStack fluid = resource.copy();

    List<PipeFluidsTeleport> connectedPipes = logic.getConnectedPipes(true);
    connectedPipes = Lists.newArrayList(connectedPipes);
    Collections.shuffle(connectedPipes, container.worldObj.rand);
    OUTER: for (PipeFluidsTeleport destPipe : connectedPipes) {
        List<Pair<ForgeDirection, IFluidHandler>> fluidsList = destPipe.getPossibleFluidsMovements();
        Collections.shuffle(fluidsList, container.worldObj.rand);
        for (Pair<ForgeDirection, IFluidHandler> fluids : fluidsList) {
            ForgeDirection side = fluids.getLeft();
            IFluidHandler tank = fluids.getRight();

            int usedSingle = tank.fill(side, fluid, false);
            if (usedSingle > 0) {
                int energy = APUtils.divideAndCeil(usedSingle, AdditionalPipes.unitFluids);
                if (doFill ? logic.useEnergy(energy) : logic.canUseEnergy(energy)) {
                    if (doFill) {
                        tank.fill(side, fluid, doFill);
                    }
                    fluid.amount -= usedSingle;
                    if (fluid.amount <= 0) {
                        break OUTER;
                    }
                }
            }
        }
    }

    return resource.amount - fluid.amount;
}

From source file:com.music.Arpeggiator.java

@Override
public void handleScore(Score score, ScoreContext ctx) {
    Part part = ctx.getParts().get(PartType.ARPEGGIO);
    if (part == null) {
        return;//from   w  ww .  j  a  v a  2 s.c  o  m
    }
    Part mainPart = ctx.getParts().get(PartType.MAIN);
    double currentMeasureSize = 0;
    double normalizedMeasureSize = ctx.getNormalizedMeasureSize();
    SpecialNoteType specialNoteType = null;
    for (Phrase phrase : mainPart.getPhraseArray()) {
        if (Chance.test(20)) { // change the special note type
            if (Chance.test(60)) { // to a new value
                specialNoteType = SpecialNoteType.values()[random.nextInt(SpecialNoteType.values().length)];
            } else { // reset
                specialNoteType = null;
            }
        }

        Phrase arpeggioPhrase = new Phrase();
        arpeggioPhrase.setTitle("Arpeggio phrase");
        Scale currentScale = ((ExtendedPhrase) phrase).getScale();
        // get copies of the static ones, so that we can shuffle them without affecting the original
        List<Chord> scaleChords = new ArrayList<Chord>(ChordUtils.chords.get(currentScale));
        Collections.shuffle(scaleChords, random);
        Note[] notes = phrase.getNoteArray();
        List<ToneType> firstToneTypes = new ArrayList<>();

        int measures = 0;
        Note[] currentNotes = null;
        boolean useTwoNoteChords = Chance.test(14);
        Chord chord = null;
        for (int i = 0; i < notes.length; i++) {
            Note currentNote = notes[i];
            if (currentNote.getRhythmValue() == 0) {
                continue; // rhythm value is 0 for the first notes of a (main-part) chord. So progress to the next
            }
            boolean lastMeasure = measures == ctx.getMeasures() - 1;
            if (currentMeasureSize == 0 && !currentNote.isRest() && !lastMeasure) {
                boolean preferStable = ToneResolver.needsContrastingChord(firstToneTypes, ToneGroups.UNSTABLE);
                boolean preferUnstable = ToneResolver.needsContrastingChord(firstToneTypes, ToneGroups.STABLE);
                // change the chord only in 1/4 of the cases
                if (currentNotes == null || Chance.test(25)) {
                    // no alternatives for now - only 3-note chords
                    Chord previous = chord;
                    chord = ChordUtils.getChord(ctx, currentNote.getPitch(), previous, scaleChords, scaleChords,
                            scaleChords, preferStable, preferUnstable);
                    if (chord != null) {
                        int[] pitches = chord.getPitches();
                        //remove the middle note in some cases (but make it possible to have three-note chords in a generally two-note phrase)
                        if (pitches.length == 3 && useTwoNoteChords && Chance.test(90)) {
                            pitches = ArrayUtils.remove(pitches, 1);
                        }
                        int count = Chance.test(90) ? (Chance.test(80) ? 4 : 2) : (Chance.test(80) ? 3 : 5);

                        currentNotes = new Note[count];
                        double length = normalizedMeasureSize / count;
                        for (int k = 0; k < count; k++) {
                            Note note = NoteFactory.createNote(pitches[random.nextInt(pitches.length)], length);
                            note.setDynamic(InstrumentGroups.getInstrumentSpecificDynamics(
                                    65 + random.nextInt(10), part.getInstrument()));
                            if (specialNoteType != null) {
                                note.setDuration(note.getRhythmValue() * specialNoteType.getValue());
                            }
                            currentNotes[k] = note;
                        }

                    }
                }
                if (Chance.test(85) && currentNotes != null) {
                    for (Note note : currentNotes) {
                        arpeggioPhrase.addNote(note);
                    }
                } else {
                    arpeggioPhrase.addRest(new Rest(normalizedMeasureSize));
                }
            } else if (currentMeasureSize == 0 && (currentNote.isRest() || lastMeasure)) {
                arpeggioPhrase.addRest(new Rest(normalizedMeasureSize));
            }

            currentMeasureSize += currentNote.getRhythmValue();
            if (currentMeasureSize >= normalizedMeasureSize) {
                currentMeasureSize = 0;
                measures++;
            }
        }
        part.add(arpeggioPhrase);
    }

}

From source file:cc.kave.commons.pointsto.evaluation.UsagePruning.java

/**
 * @return The number of pruned usages//from   ww w. j  av a 2 s .co m
 */
public int prune(final int maxUsages, List<Usage> usages) {
    if (maxUsages <= 0) {
        throw new IllegalArgumentException("maxUsages must be greater than zero");
    }
    if (usages.size() < maxUsages) {
        return 0;
    }

    Random rnd = new Random(rndGenerator.nextLong());
    Collections.shuffle(usages, rnd);
    final int initialNumUsages = usages.size();
    for (int i = usages.size() - 1; i >= maxUsages; --i) {
        usages.remove(i);
    }

    return initialNumUsages - usages.size();
}

From source file:com.example.android.tvleanback2.ui.VerticalGridFragment.java

private void setupFragment() {
    VerticalGridPresenter gridPresenter = new VerticalGridPresenter();
    gridPresenter.setNumberOfColumns(NUM_COLUMNS);
    setGridPresenter(gridPresenter);/*w  w w .  ja  v  a  2 s.  c o  m*/

    mAdapter = new ArrayObjectAdapter(new CardPresenter());

    new Handler().postDelayed(new Runnable() {
        public void run() {
            long seed = System.nanoTime();
            HashMap<String, List<Movie>> movies = VideoProvider.getMovieList();
            for (Map.Entry<String, List<Movie>> entry : movies.entrySet()) {
                List<Movie> list = entry.getValue();
                Collections.shuffle(list, new Random(seed));
                for (Movie movie : list) {
                    mAdapter.add(movie);
                }
            }
            startEntranceTransition();
        }
    }, 500);

    setAdapter(mAdapter);

    setOnSearchClickedListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getActivity(), SearchActivity.class);
            startActivity(intent);
        }
    });

    setOnItemViewClickedListener(new ItemViewClickedListener());
    setOnItemViewSelectedListener(new ItemViewSelectedListener());
}