Example usage for java.util Random Random

List of usage examples for java.util Random Random

Introduction

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

Prototype

public Random() 

Source Link

Document

Creates a new random number generator.

Usage

From source file:ProxyTest.java

public static void main(String[] args) {
    Object[] elements = new Object[1000];

    // fill elements with proxies for the integers 1 ... 1000
    for (int i = 0; i < elements.length; i++) {
        Integer value = i + 1;/*from ww  w. jav  a2s.  co m*/
        InvocationHandler handler = new TraceHandler(value);
        Object proxy = Proxy.newProxyInstance(null, new Class[] { Comparable.class }, handler);
        elements[i] = proxy;
    }

    // construct a random integer
    Integer key = new Random().nextInt(elements.length) + 1;

    // search for the key
    int result = Arrays.binarySearch(elements, key);

    // print match if found
    if (result >= 0)
        System.out.println(elements[result]);
}

From source file:org.eclipse.swt.snippets.Snippet151.java

public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 151");
    shell.setLayout(new FillLayout());
    final Table table = new Table(shell, SWT.BORDER | SWT.VIRTUAL);
    table.addListener(SWT.SetData, e -> {
        TableItem item = (TableItem) e.item;
        int index = table.indexOf(item);
        item.setText("Item " + data[index]);
    });//from w  w  w.j a  v  a2s . c o  m
    Thread thread = new Thread() {
        @Override
        public void run() {
            int count = 0;
            Random random = new Random();
            while (count++ < 500) {
                if (table.isDisposed())
                    return;
                // add 10 random numbers to array and sort
                int grow = 10;
                int[] newData = new int[data.length + grow];
                System.arraycopy(data, 0, newData, 0, data.length);
                int index = data.length;
                data = newData;
                for (int j = 0; j < grow; j++) {
                    data[index++] = random.nextInt();
                }
                Arrays.sort(data);
                display.syncExec(() -> {
                    if (table.isDisposed())
                        return;
                    table.setItemCount(data.length);
                    table.clearAll();
                });
                try {
                    Thread.sleep(500);
                } catch (Throwable t) {
                }
            }
        }
    };
    thread.start();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:io.druid.query.aggregation.datasketches.quantiles.GenerateTestData.java

public static void main(String[] args) throws Exception {
    Path buildPath = FileSystems.getDefault().getPath("doubles_build_data.tsv");
    Path sketchPath = FileSystems.getDefault().getPath("doubles_sketch_data.tsv");
    BufferedWriter buildData = Files.newBufferedWriter(buildPath, StandardCharsets.UTF_8);
    BufferedWriter sketchData = Files.newBufferedWriter(sketchPath, StandardCharsets.UTF_8);
    Random rand = new Random();
    int sequenceNumber = 0;
    for (int i = 0; i < 20; i++) {
        int product = rand.nextInt(10);
        UpdateDoublesSketch sketch = UpdateDoublesSketch.builder().build();
        for (int j = 0; j < 20; j++) {
            double value = rand.nextDouble();
            buildData.write("2016010101");
            buildData.write('\t');
            buildData.write(Integer.toString(sequenceNumber)); // dimension with unique numbers for ingesting raw data
            buildData.write('\t');
            buildData.write(Integer.toString(product)); // product dimension
            buildData.write('\t');
            buildData.write(Double.toString(value));
            buildData.newLine();//from w ww . j a  v a2  s . co  m
            sketch.update(value);
            sequenceNumber++;
        }
        sketchData.write("2016010101");
        sketchData.write('\t');
        sketchData.write(Integer.toString(product)); // product dimension
        sketchData.write('\t');
        sketchData.write(Base64.encodeBase64String(sketch.toByteArray(true)));
        sketchData.newLine();
    }
    buildData.close();
    sketchData.close();
}

From source file:TableSetDataEvent.java

public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    final Table table = new Table(shell, SWT.BORDER | SWT.VIRTUAL);
    table.addListener(SWT.SetData, new Listener() {
        public void handleEvent(Event e) {
            System.out.println(e);
            TableItem item = (TableItem) e.item;
            int index = table.indexOf(item);
            item.setText("Item " + data[index]);
        }/* w  w w  .ja  va2  s .  c om*/
    });
    int count = 0;
    Random random = new Random();
    while (count++ < 50) {
        int grow = 10;
        int[] newData = new int[data.length + grow];
        System.arraycopy(data, 0, newData, 0, data.length);
        int index = data.length;
        data = newData;
        for (int j = 0; j < grow; j++) {
            data[index++] = random.nextInt();
        }

        table.setItemCount(data.length);
        table.clearAll();
    }
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:edu.uiowa.icts.util.TopN.java

/**
 * <p>main.</p>// ww w  .jav a2 s  .  c o  m
 *
 * @param args an array of {@link java.lang.String} objects.
 */
public static void main(String args[]) {
    TopN<Double> top10 = new TopN<Double>(10);
    Random r = new Random();
    for (int i = 0; i < 10000; i++) {
        double d = r.nextDouble();
        int pos = top10.inTopN(d);
        if (pos > 0) {
            log.debug(i + ":  Rank: " + pos + " is in top 10: " + d);
        }
    }

    top10.print();
    log.debug("size: " + top10.size());
    log.debug("max: " + top10.max());

}

From source file:com.yahoo.ads.pb.mttf.PistachiosMTTFTest.java

public static void main(String[] args) {
    PistachiosClient client;//from  ww  w .j  a  v  a  2 s.  c  o m
    try {
        client = new PistachiosClient();
    } catch (Exception e) {
        logger.info("error creating client", e);
        return;
    }
    Random rand = new Random();

    while (true) {
        try {
            long id = rand.nextLong();
            String value = InetAddress.getLocalHost().getHostName() + rand.nextInt();
            client.store(0, id, value.getBytes());
            for (int i = 0; i < 30; i++) {
                byte[] clientValue = client.lookup(0, id);
                String remoteValue = new String(clientValue);
                if (Arrays.equals(value.getBytes(), clientValue)
                        || !remoteValue.contains(InetAddress.getLocalHost().getHostName())) {
                    logger.debug("succeeded checking id {} value {}", id, value);
                } else {
                    logger.error("failed checking id {} value {} != {}", id, value, new String(clientValue));
                    System.exit(0);
                }
                Thread.sleep(100);
            }
        } catch (Exception e) {
            System.out.println("error testing" + e);
            System.exit(0);
        }
    }
}

From source file:org.opencredo.cloud.storage.samples.quote.S3QuoteDemo.java

public static void main(String[] args) {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("quoteDemo-context.xml");

    TickerUploader tickerUploader = (TickerUploader) context.getBean("tickerUploader");
    // sending requests for tickers to be uploaded to S3, so that they can
    // later be read by another application.
    // can be commented out if already uploaded enough information
    for (int i = 0; i < 4; i++) {
        char[] chars = new char[3];
        for (int j = 0; j < 3; j++) {
            chars[j] = (char) (new Random().nextInt(25) + 65);
        }//  w ww  .ja  v a 2  s .c o  m
        String ticker = new String(chars);
        LOG.info("ticker to upload: {}", ticker);
        MessageBuilder<String> builder = MessageBuilder.withPayload(ticker);
        tickerUploader.sendTicker(builder.build());
    }
}

From source file:apidemo.APIDemo.java

public static void main(String[] args) throws InterruptedException, Exception {
    Random random = new Random();
    int uReqFeq = 1;

    while (uReqFeq < 101) {
        String strJSON = ObjectToString(new JSMessage((long) random.nextInt(10) + 1,
                (long) random.nextInt(10) + 11, "msg_" + Integer.toString(uReqFeq)));

        String res = sendPostJson("http://localhost:9494/api/nsservice/msg", strJSON, 10000);
        System.out.println("Result: " + res);

        ++uReqFeq;/*w  ww.  ja v  a2 s.c  o m*/
    }
}

From source file:backup.store.ExternalExtendedBlockSort.java

public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();
    Path dir = new Path("file:///home/apm/Development/git-projects/hdfs-backup/hdfs-backup-core/tmp");
    dir.getFileSystem(conf).delete(dir, true);
    long start = System.nanoTime();
    try (ExternalExtendedBlockSort<LongWritable> sort = new ExternalExtendedBlockSort<>(conf, dir,
            LongWritable.class)) {
        Random random = new Random();
        for (int bp = 0; bp < 1; bp++) {
            String bpid = UUID.randomUUID().toString();
            for (int i = 0; i < 10000000; i++) {
                // for (int i = 0; i < 10; i++) {
                long genstamp = random.nextInt(20000);
                long blockId = random.nextLong();
                ExtendedBlock extendedBlock = new ExtendedBlock(bpid, blockId,
                        random.nextInt(Integer.MAX_VALUE), genstamp);
                sort.add(extendedBlock, new LongWritable(blockId));
            }// w  w  w.  jav  a  2  s  .  c  o  m
        }
        System.out.println("finished");
        sort.finished();
        System.out.println("interate");
        for (String blockPoolId : sort.getBlockPoolIds()) {
            ExtendedBlockEnum<LongWritable> blockEnum = sort.getBlockEnum(blockPoolId);
            ExtendedBlock block;
            long l = 0;
            while ((block = blockEnum.next()) != null) {
                // System.out.println(block);
                long blockId = block.getBlockId();
                l += blockId;
                LongWritable currentValue = blockEnum.currentValue();
                if (currentValue.get() != blockId) {
                    System.err.println("Error " + blockId);
                }
            }
            System.out.println(l);
        }
    }
    long end = System.nanoTime();
    System.out.println("Time [" + (end - start) / 1000000.0 + " ms]");
}

From source file:QuickSort.java

/**
 * @param args/*from  w  w w.  java2  s .c  om*/
 */
public static void main(String[] args) {
    Integer[] array = new Integer[15];
    Random rng = new Random();
    int split = 10;
    for (int i = 0; i < split; i++) {
        array[i] = new Integer(rng.nextInt(100));
    }
    for (int i = split; i < array.length; i++) {
        array[i] = null;
    }

    System.out.println(Arrays.toString(array));

    QuickSort.sort(array, new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o1.compareTo(o2);
        };
    }, 0, split - 1);

    System.out.println(Arrays.toString(array));

}