Example usage for java.util Random nextBoolean

List of usage examples for java.util Random nextBoolean

Introduction

In this page you can find the example usage for java.util Random nextBoolean.

Prototype

public boolean nextBoolean() 

Source Link

Document

Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {

    Random rand = new Random();

    boolean b = rand.nextBoolean();
    long l = rand.nextLong();
    float f = rand.nextFloat(); // 0.0 <= f < 1.0
    double d = rand.nextDouble(); // 0.0 <= d < 1.0
}

From source file:Main.java

public static void main(String args[]) {

    Random randomno = new Random();

    // get next next boolean value 
    boolean value = randomno.nextBoolean();

    // check the value  
    System.out.println("Value is: " + value);
}

From source file:Main.java

public static final void main(String... args) {
    Random randomGenerator = new Random();
    for (int idx = 1; idx <= 10; ++idx) {
        boolean randomBool = randomGenerator.nextBoolean();
        System.out.println("Generated : " + randomBool);
    }//from   ww w .  j  a v a  2  s .com
}

From source file:Main.java

public static void main(String[] args) {
    Random r = new Random();

    // generate some random boolean values
    boolean[] booleans = new boolean[10];
    for (int i = 0; i < booleans.length; i++) {
        booleans[i] = r.nextBoolean();
    }//from  www.  j  a v a  2 s  .  c om

    for (boolean b : booleans) {
        System.out.print(b + ", ");
    }

    // generate a uniformly distributed int random numbers
    int[] integers = new int[10];
    for (int i = 0; i < integers.length; i++) {
        integers[i] = r.nextInt();
    }

    for (int i : integers) {
        System.out.print(i + ", ");
    }

    // generate a uniformly distributed float random numbers
    float[] floats = new float[10];
    for (int i = 0; i < floats.length; i++) {
        floats[i] = r.nextFloat();
    }

    for (float f : floats) {
        System.out.print(f + ", ");
    }

    // generate a Gaussian normally distributed random numbers
    double[] gaussians = new double[10];
    for (int i = 0; i < gaussians.length; i++) {
        gaussians[i] = r.nextGaussian();
    }

    for (double d : gaussians) {
        System.out.print(d + ", ");
    }
}

From source file:ubic.BAMSandAllen.FocusedAnalysis.TestConnectivityRobustness.java

/**
 * @param args/*from  w  w  w  . j a  v a2  s .  c o m*/
 */
public static void main(String[] args) throws Exception {

    main2();
    System.exit(1);

    Direction direction = AnalyzeBAMSandAllenGenes.Direction.OUTGOING;
    boolean makeVirtualRegions = true;

    boolean squareMatrix = false;
    boolean logDistance = true;
    boolean slow = false;
    RegressMatrix regressType = RegressMatrix.BOTH;
    boolean useVirtual = true;
    boolean removeNonExp = true;

    ConnectivityAndAllenExpressionMatrixPair pair = ExpressionMatrixPairFactory.connectivityPartial(direction,
            slow, regressType, useVirtual, removeNonExp, logDistance);
    pair.getCorrelation();
    // ConnectivityAndAllenExpressionMatrixPair pair = ExpressionMatrixPairFactory.connectivityAndExpression(
    // direction, useVirtual, removeNonExp );

    String filename = "/grp/java/workspace/BAMSandAllen/data/rankedGenes/near final ammon/";
    filename += "LOOGenesInOrder.in.partialcon.ammon.txt.452.0.01985.topGenes.txt";
    // filename += "LOOGenesInOrder.out.partialcon.ammon.txt.374.0.016424.topGenes.txt";

    RankedGeneListLoader aLook = new RankedGeneListLoader(filename);
    pair.setMatrixBDataRows(aLook.getLines());
    log.info("Original:" + pair.getCorrelation());

    log.info(pair.runJackKnife(true));

    // second try

    List<String> connectionRows = pair.getMatrixA().getRowNames();
    int seed = 7;
    Random r = new Random(seed);
    List<String> removeRows = new LinkedList<String>();
    for (String region : connectionRows) {
        boolean remove = r.nextBoolean();
        if (remove) {
            removeRows.add(region);
        }
    }
    pair.removeMatrixADataRows(removeRows);
    pair.printConnectionInfo();
    pair.printDimensions();
    log.info("After remvoing half:" + pair.getCorrelation() + ", seed=" + seed);

}

From source file:Main.java

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    StyledDocument doc = new DefaultStyledDocument();
    JTextPane textPane = new JTextPane(doc);
    textPane.setText("this is a test.");

    Random random = new Random();
    for (int i = 0; i < textPane.getDocument().getLength(); i++) {
        SimpleAttributeSet set = new SimpleAttributeSet();
        StyleConstants.setForeground(set,
                new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
        StyleConstants.setFontSize(set, random.nextInt(12) + 12);
        StyleConstants.setBold(set, random.nextBoolean());
        StyleConstants.setItalic(set, random.nextBoolean());
        StyleConstants.setUnderline(set, random.nextBoolean());

        doc.setCharacterAttributes(i, 1, set, true);
    }/*from w  w w .java2  s. c  om*/

    frame.add(new JScrollPane(textPane));
    frame.setSize(500, 400);
    frame.setVisible(true);
}

From source file:io.druid.examples.rabbitmq.RabbitMQProducerMain.java

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();

    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg()
            .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg()
            .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg()
            .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]")
            .create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg()
            .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]")
            .create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg()
            .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]")
            .create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg()
            .withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg()
            .withDescription("the routing key to use when sending messages [default: 'default.routing.key']")
            .create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg()
            .withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable")
            .withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete")
            .withDescription("if set, an auto-delete exchange will be declared [default: not set]")
            .create("a"));
    optionList.add(OptionBuilder.withLongOpt("single")
            .withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg()
            .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]")
            .create());/*from  w  ww  .ja v a2 s . c o m*/
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription(
            "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg()
            .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg()
            .withDescription("the delay between sending messages in milliseconds [default: 100]").create());

    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    formatter.setOptionComparator(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            // I know this isn't fast, but who cares! The list is short.
            return optionList.indexOf(o1) - optionList.indexOf(o2);
        }
    });

    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }

    CommandLine cmd = null;

    try {
        cmd = new BasicParser().parse(options, args);

    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }

    ConnectionFactory factory = new ConnectionFactory();

    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }

    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }

    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));

    Random r = new Random();
    Calendar timer = Calendar.getInstance();
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);

        String line = String.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

        channel.basicPublish(exchange, routingKey, null, line.getBytes());

        System.out.println("Sent message: " + line);

        timer.add(Calendar.SECOND, interval);

        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));

    connection.close();
}

From source file:org.apache.druid.examples.rabbitmq.RabbitMQProducerMain.java

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();

    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg()
            .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg()
            .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg()
            .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]")
            .create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg()
            .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]")
            .create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg()
            .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]")
            .create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg()
            .withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg()
            .withDescription("the routing key to use when sending messages [default: 'default.routing.key']")
            .create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg()
            .withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable")
            .withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete")
            .withDescription("if set, an auto-delete exchange will be declared [default: not set]")
            .create("a"));
    optionList.add(OptionBuilder.withLongOpt("single")
            .withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg()
            .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]")
            .create());/*w w  w . j  av  a2 s . c  o m*/
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription(
            "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg()
            .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg()
            .withDescription("the delay between sending messages in milliseconds [default: 100]").create());

    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    //noinspection ComparatorCombinators -- don't replace with comparingInt() to preserve comments
    formatter.setOptionComparator((o1, o2) -> {
        // I know this isn't fast, but who cares! The list is short.
        //noinspection SuspiciousMethodCalls
        return Integer.compare(optionList.indexOf(o1), optionList.indexOf(o2));
    });

    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }

    CommandLine cmd = null;

    try {
        cmd = new BasicParser().parse(options, args);
    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }

    ConnectionFactory factory = new ConnectionFactory();

    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }

    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }

    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));

    Random r = ThreadLocalRandom.current();
    Calendar timer = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ENGLISH);
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);

        String line = StringUtils.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

        channel.basicPublish(exchange, routingKey, null, StringUtils.toUtf8(line));

        System.out.println("Sent message: " + line);

        timer.add(Calendar.SECOND, interval);

        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));

    connection.close();
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step2ArgumentPairsSampling.java

public static void main(String[] args) throws Exception {
    String inputDir = args[0];//w w  w . j  a v a2s.c om

    // /tmp
    File outputDir = new File(args[1]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }

    // pseudo-random
    final Random random = new Random(1);

    int totalPairsCount = 0;

    // read all debates
    for (File file : IOHelper.listXmlFiles(new File(inputDir))) {
        Debate debate = DebateSerializer.deserializeFromXML(FileUtils.readFileToString(file, "utf-8"));

        // get two stances
        SortedSet<String> originalStances = debate.getStances();

        // cleaning: some debate has three or more stances (data are inconsistent)
        // remove those with only one argument
        SortedSet<String> stances = new TreeSet<>();
        for (String stance : originalStances) {
            if (debate.getArgumentsForStance(stance).size() > 1) {
                stances.add(stance);
            }
        }

        if (stances.size() != 2) {
            throw new IllegalStateException(
                    "2 stances per debate expected, was " + stances.size() + ", " + stances);
        }

        // for each stance, get pseudo-random N arguments
        for (String stance : stances) {
            List<Argument> argumentsForStance = debate.getArgumentsForStance(stance);

            // shuffle
            Collections.shuffle(argumentsForStance, random);

            // and get max first N arguments
            List<Argument> selectedArguments = argumentsForStance.subList(0,
                    argumentsForStance.size() < MAX_SELECTED_ARGUMENTS_PRO_SIDE ? argumentsForStance.size()
                            : MAX_SELECTED_ARGUMENTS_PRO_SIDE);

            List<ArgumentPair> argumentPairs = new ArrayList<>();

            // now create pairs
            for (int i = 0; i < selectedArguments.size(); i++) {
                for (int j = (i + 1); j < selectedArguments.size(); j++) {
                    Argument arg1 = selectedArguments.get(i);
                    Argument arg2 = selectedArguments.get(j);

                    ArgumentPair argumentPair = new ArgumentPair();
                    argumentPair.setDebateMetaData(debate.getDebateMetaData());

                    // assign arg1 and arg2 pseudo-randomly
                    // (not to have the same argument as arg1 all the time)
                    if (random.nextBoolean()) {
                        argumentPair.setArg1(arg1);
                        argumentPair.setArg2(arg2);
                    } else {
                        argumentPair.setArg1(arg2);
                        argumentPair.setArg2(arg1);
                    }

                    // set unique id
                    argumentPair.setId(argumentPair.getArg1().getId() + "_" + argumentPair.getArg2().getId());

                    argumentPairs.add(argumentPair);
                }
            }

            String fileName = IOHelper.createFileName(debate.getDebateMetaData(), stance);

            File outputFile = new File(outputDir, fileName);

            // and save all sampled pairs into a XML file
            XStreamTools.toXML(argumentPairs, outputFile);

            System.out.println("Saved " + argumentPairs.size() + " pairs to " + outputFile);

            totalPairsCount += argumentPairs.size();
        }

    }

    System.out.println("Total pairs generated: " + totalPairsCount);
}

From source file:Main.java

static int randomOneOrMinusOne() {
    Random rand = new Random();
    if (rand.nextBoolean())
        return 1;
    else/*from  www.  j  ava 2  s .co  m*/
        return -1;
}