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:com.github.rinde.rinsim.examples.demo.swarm.DemoPanel.java

@Override
public void handleEvent(@Nullable Event event) {
    assert event != null;
    final Iterator<Point> points = SwarmDemo
            .measureString(((Text) event.widget).getText(), SwarmDemo.FONT_SIZE, SPACING, 0).iterator();
    final List<Vehicle> vs = newArrayList(vehicles);
    if (event.type == SWT.DefaultSelection) {
        Collections.shuffle(vs, new RandomAdaptor(rng));
    }//w ww  .  j a v a  2 s. com
    for (final Vehicle v : vs) {
        if (points.hasNext()) {
            v.setDestination(points.next());
        } else {
            v.setInactive();
        }
    }
}

From source file:com.github.rinde.rinsim.examples.demo.factory.FactoryExample.java

/**
 * Run the example.//from  ww w. j a  v a2 s .c  o m
 * @param endTime The time to stop.
 * @param display The display to show it on.
 * @param m The monitor to show it on.
 * @param list Listener for events.
 * @return The simulator used in the example.
 */
public static Simulator run(final long endTime, Display display, @Nullable Monitor m, @Nullable Listener list) {

    final Rectangle rect;
    if (m != null) {
        if (list != null) {
            rect = m.getClientArea();
        } else {
            // full screen
            rect = m.getBounds();
        }
    } else {
        rect = display.getPrimaryMonitor().getClientArea();
    }

    List<String> words = asList(" BioCo3 \nDistriNet");
    // spacing between vertical lines in line units

    // screen
    if (rect.width == FULL_HD_W) {
        // AgentWise\nKU Leuven", "iMinds\nDistriNet"
        // " Agent \n Wise ", " Distri \n Net "
        words = asList(" iMinds \nDistriNet");
    }

    final ImmutableList<ImmutableList<Point>> points = createPoints(words);
    final Graph<?> g = createGraph(points);

    final List<Point> borderNodes = newArrayList(getBorderNodes(g));
    Collections.shuffle(borderNodes, new Random(RANDOM_SEED));

    View.Builder view = View.builder().with(GraphRoadModelRenderer.builder().withMargin(CANVAS_MARGIN))
            .with(BoxRenderer.builder())
            .with(RoadUserRenderer.builder().withImageAssociation(AGV.class, "/graphics/flat/forklift2.png"))
            .withTitleAppendix("Factory Demo").withAutoPlay().withAutoClose().withSpeedUp(SPEED_UP);

    if (m != null) {
        view = view.withMonitor(m).withResolution(m.getClientArea().width, m.getClientArea().height)
                .withDisplay(display);

        if (list != null) {
            view = view.withCallback(list).withAsync();
        } else {
            view = view.withFullScreen();
        }
    }

    final RandomGenerator rng = new MersenneTwister(RANDOM_SEED);
    final Simulator simulator = Simulator.builder().setRandomGenerator(rng)
            .addModel(BlockingGraphRoadModel
                    .blockingBuilder(g).withDistanceUnit(SI.METER).withSpeedUnit(NonSI.KILOMETERS_PER_HOUR))
            .addModel(DefaultPDPModel.builder())
            .addModel(AgvModel.builder()
                    .withPoints(ImmutableList.<ImmutableList<Point>>builder().addAll(points)
                            .add(ImmutableList.copyOf(borderNodes)).build(), getBorderNodes(g)))
            .addModel(view).build();

    for (int i = 0; i < NUM_VEHICLES; i++) {
        final List<Point> l = points.get(rng.nextInt(points.size()));
        final Point p = l.get(rng.nextInt(l.size()));
        simulator.register(new AGV(p));
    }

    simulator.addTickListener(new TickListener() {
        @Override
        public void tick(TimeLapse time) {
            if (time.getStartTime() > endTime) {
                simulator.stop();
            }
        }

        @Override
        public void afterTick(TimeLapse timeLapse) {
        }
    });

    simulator.start();
    return simulator;
}

From source file:com.spotify.heroic.cluster.NodeRegistry.java

private List<ClusterNode> pickN(final Collection<ClusterNode> options, OptionalLimit n) {
    if (options.isEmpty()) {
        return ImmutableList.of();
    }/*from w ww.  j  a v  a2 s .  c o  m*/

    final List<ClusterNode> entries = options.stream().filter(ClusterNode::isAlive)
            .collect(Collectors.toList());

    Collections.shuffle(entries, random);

    return n.limitList(entries);
}

From source file:com.google.wolff.androidhunt.Hunt.java

/** Shuffles the clues.  Note that each clue is marked with
 *  a difficulty group, so that, say, a hard clue can't proceed
 *  an easier clue./*  ww  w  .j  a va 2s .  co m*/
 * @param seed The random number seed.
 */
public void shuffle(int seed) {
    if (isShuffled) {
        return;
    }
    // Divide into shuffle groups
    ArrayList<ArrayList<Clue>> groups = new ArrayList<ArrayList<Clue>>(10);

    for (int i = 0; i < 10; i++) {
        groups.add(null);
    }

    for (int i = 0; i < clueList.size(); i++) {
        Clue c = clueList.get(i);

        if (groups.get(c.shufflegroup) == null) {
            groups.set(c.shufflegroup, new ArrayList<Clue>());
        }

        groups.get(c.shufflegroup).add(c);
    }

    clueList = new ArrayList<Clue>();

    Random r = new Random(seed);

    for (int i = 0; i < 10; i++) {
        ArrayList<Clue> cl = groups.get(i);

        if (cl == null)
            continue;

        Collections.shuffle(cl, r);

        clueList.addAll(cl);
    }

    isShuffled = true;
}

From source file:org.matsim.contrib.analysis.vsp.traveltimedistance.TravelTimeValidationRunner.java

public void run() {

    EventsManager events = EventsUtils.createEventsManager();
    CarTripsExtractor carTripsExtractor = new CarTripsExtractor(population.getPersons().keySet(), network);
    events.addHandler(carTripsExtractor);
    new MatsimEventsReader(events).readFile(eventsFile);
    List<CarTrip> carTrips = carTripsExtractor.getTrips();
    Collections.shuffle(carTrips, MatsimRandom.getRandom());
    int i = 0;//  w  w w.  jav a2 s .com
    for (CarTrip trip : carTrips) {
        Tuple<Double, Double> timeDistance = travelTimeValidator.getTravelTime(trip);
        double validatedTravelTime = timeDistance.getFirst();
        trip.setValidatedTravelTime(validatedTravelTime);
        trip.setValidatedTravelDistance(timeDistance.getSecond());
        i++;
        if (i >= numberOfTripsToValidate) {
            break;
        }
    }
    writeTravelTimeValidation(outputfolder, carTrips);

}

From source file:de.unentscheidbar.csv2.CaseInsensitiveBenchmark.java

static Collection<String> getLotsOfColumnNames() {

    Random rnd = new Random(0);
    Set<String> names = Collections.newSetFromMap(new CaseInsensitiveMap<String, Boolean>());
    while (names.size() < 100) {
        names.add(randomString(rnd, 1 + rnd.nextInt(30)));
    }//from   w w w.j a  v a2  s .  co m
    List<String> uniqueNames = new ArrayList<>(names);
    /* For predictable iteration order: */
    Collections.sort(uniqueNames);
    Collections.shuffle(uniqueNames, rnd);
    return Collections.unmodifiableList(uniqueNames);
}

From source file:com.nearinfinity.blur.thrift.AsyncClientPool.java

/**
 * Gets a client instance that implements the AsyncIface interface that
 * connects to the given connection string.
 * /*w  w w . ja  v a  2  s .c  om*/
 * @param <T>
 * @param asyncIfaceClass
 *          the AsyncIface interface to pool.
 * @param connectionStr
 *          the connection string.
 * @return the client instance.
 */
@SuppressWarnings("unchecked")
public <T> T getClient(final Class<T> asyncIfaceClass, final String connectionStr) {
    List<Connection> connections = BlurClientManager.getConnections(connectionStr);
    Collections.shuffle(connections, random);
    //randomness ftw
    final Connection connection = connections.get(0);
    return (T) Proxy.newProxyInstance(asyncIfaceClass.getClassLoader(), new Class[] { asyncIfaceClass },
            new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    return execute(new AsyncCall(asyncIfaceClass, method, args, connection));
                }
            });
}

From source file:edu.uci.ics.hyracks.imru.jobgen.ClusterConfig.java

/**
 * Set location constraints for an operator based on the locations of input
 * files in HDFS. Randomly assigns partitions to NCs where the HDFS files
 * are local; assigns the rest randomly.
 * /*from   w ww.j  av a  2 s . c om*/
 * @param spec
 *            A job specification.
 * @param operator
 *            The operator that will be constrained.
 * @param splits
 *            A list of InputSplits specifying files in HDFS.
 * @param random
 *            A source of randomness (so the partition-assignment can be
 *            repeated across iterations, provided that the HDFS file
 *            locations don't change).
 * @return The assigned partition locations.
 * @throws IOException
 * @throws HyracksException
 */
public static String[] setLocationConstraint(JobSpecification spec, IMRUOperatorDescriptor operator,
        InputSplit[] hdfsSplits, IMRUFileSplit[] splits, Random random) throws IOException {
    if (NCs == null)
        loadClusterConfig();
    if (splits.length == 0)
        return new String[0];

    if (hdfsSplits == null) {
        int partitionCount = splits.length;
        String[] partitionLocations = new String[partitionCount];
        for (int partition = 0; partition < partitionCount; partition++) {
            int pos = partition % NCs.length;
            String path = splits[partition].getPath();
            int t = path.indexOf(":");
            if (t > 0)
                partitionLocations[partition] = path.substring(0, t);
            else
                partitionLocations[partition] = NCs[pos];
        }
        if (operator != null) {
            PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, operator, partitionLocations);
            PartitionConstraintHelper.addPartitionCountConstraint(spec, operator, partitionCount);
        }
        return partitionLocations;
    }
    int partitionCount = splits.length;
    String[] partitionLocations = new String[partitionCount];
    int localAssignments = 0;
    int nonlocalAssignments = 0;
    for (int partition = 0; partition < partitionCount; partition++) {
        String[] localHosts = hdfsSplits[partition].getLocations();
        // Remove nondeterminism from the call to getLocations():
        Collections.sort(Arrays.asList(localHosts));
        Collections.shuffle(Arrays.asList(localHosts), random);
        if (localHosts.length > 0) {
            LOG.info("Partition " + partition + " is local at " + localHosts.length + " hosts: "
                    + StringUtils.join(localHosts, ", "));
            for (int host = 0; host < localHosts.length; host++) {
                InetAddress[] hostIps = InetAddress.getAllByName(localHosts[host]);
                for (InetAddress ip : hostIps) {
                    if (ipToNcMapping.get(ip.getHostAddress()) != null) {
                        List<String> ncs = ipToNcMapping.get(ip.getHostAddress());
                        int pos = random.nextInt(ncs.size());
                        partitionLocations[partition] = ncs.get(pos);
                        LOG.info("Partition " + partition + " assigned to " + ncs.get(pos)
                                + ", where it is local.");
                        localAssignments++;
                        break;
                    }
                }
                if (partitionLocations[partition] != null) {
                    break;
                }
            }
            if (partitionLocations[partition] == null) {
                int pos = random.nextInt(NCs.length);
                partitionLocations[partition] = NCs[pos];
                nonlocalAssignments++;
                LOG.info("Partition " + partition + " assigned to " + NCs[pos]
                        + " because there is no NC where it is local.");
            }
        } else {
            int pos = random.nextInt(NCs.length);
            partitionLocations[partition] = NCs[pos];
            nonlocalAssignments++;
            LOG.info("Partition " + partition + " assigned to " + NCs[pos]
                    + " becasue getLocations() returned no locations.");

        }
    }
    if (LOG.isLoggable(Level.INFO)) {
        LOG.info("NC partition counts:");
        Map<String, MutableInt> ncPartitionCounts = new HashMap<String, MutableInt>();
        for (int i = 0; i < partitionLocations.length; i++) {
            if (ncPartitionCounts.get(partitionLocations[i]) == null) {
                ncPartitionCounts.put(partitionLocations[i], new MutableInt(1));
            } else {
                ncPartitionCounts.get(partitionLocations[i]).increment();
            }
        }
        for (Map.Entry<String, MutableInt> entry : ncPartitionCounts.entrySet()) {
            LOG.info(entry.getKey() + ": " + entry.getValue().intValue() + " partitions");
        }
    }
    double localityPercentage = ((1.0 * localAssignments) / (localAssignments + nonlocalAssignments)) * 100;
    if (operator != null) {
        LOG.info(operator.getClass().getSimpleName() + ": " + localAssignments + " local; "
                + nonlocalAssignments + " non-local; " + localityPercentage + "% locality");
        PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, operator, partitionLocations);
        PartitionConstraintHelper.addPartitionCountConstraint(spec, operator, partitionCount);
    }
    return partitionLocations;
}

From source file:com.github.cc007.sciencespinoffsquiz.web.controllers.RequestController.java

@RequestMapping(value = "/explanation", method = RequestMethod.GET)
public String explanation(ModelMap map) {
    map.put("statisticsredirect",
            "<meta http-equiv=\"refresh\" content=\"15;url=/ScienceSpinoffsQuiz/statistics\" />");
    map.put("statisticshide", " style=\"border:none;background-color:inherit;\"");
    QuestionPool qp = new QuestionPool("questions_en.xml");
    List<Question> questions = qp.getQuestions();
    Collections.shuffle(questions, new Random(System.currentTimeMillis()));
    Question q = questions.get(0);/*from   w  w w.  j  a v a  2 s  . com*/
    map.put("imgName", q.getExplanationImage());
    map.put("explanation", q.getExplanation());
    return "explanation";
}

From source file:grakn.core.deduplicator.AttributeDeduplicatorE2E.java

private static void insertNameShuffled(GraknClient.Session session, int nameCount, int duplicatePerNameCount,
        ExecutorService executorService) throws ExecutionException, InterruptedException {

    List<String> duplicatedNames = new ArrayList<>();
    for (int i = 0; i < nameCount; ++i) {
        for (int j = 0; j < duplicatePerNameCount; ++j) {
            String name = "lorem ipsum dolor sit amet " + i;
            duplicatedNames.add(name);//  w  ww .  ja v  a 2  s  . c  om
        }
    }

    Collections.shuffle(duplicatedNames, new Random(1));

    List<CompletableFuture<Void>> asyncInsertions = new ArrayList<>();
    for (String name : duplicatedNames) {
        CompletableFuture<Void> asyncInsert = CompletableFuture.supplyAsync(() -> {
            try (GraknClient.Transaction tx = session.transaction().write()) {
                List<ConceptMap> answer = tx.execute(Graql.insert(var().isa("name").val(name)));
                tx.commit();
            }
            return null;
        }, executorService);
        asyncInsertions.add(asyncInsert);
    }

    CompletableFuture.allOf(asyncInsertions.toArray(new CompletableFuture[] {})).get();
}