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:TestCipher.java

public static void main(String args[]) throws Exception {
    Set set = new HashSet();
    Random random = new Random();
    for (int i = 0; i < 10; i++) {
        Point point = new Point(random.nextInt(1000), random.nextInt(2000));
        set.add(point);/*from   w ww .ja v  a 2 s .  c  o  m*/
    }
    int last = random.nextInt(5000);

    // Create Key
    byte key[] = password.getBytes();
    DESKeySpec desKeySpec = new DESKeySpec(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

    // Create Cipher
    Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    desCipher.init(Cipher.ENCRYPT_MODE, secretKey);

    // Create stream
    FileOutputStream fos = new FileOutputStream("out.des");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    CipherOutputStream cos = new CipherOutputStream(bos, desCipher);
    ObjectOutputStream oos = new ObjectOutputStream(cos);

    // Write objects
    oos.writeObject(set);
    oos.writeInt(last);
    oos.flush();
    oos.close();

    // Change cipher mode
    desCipher.init(Cipher.DECRYPT_MODE, secretKey);

    // Create stream
    FileInputStream fis = new FileInputStream("out.des");
    BufferedInputStream bis = new BufferedInputStream(fis);
    CipherInputStream cis = new CipherInputStream(bis, desCipher);
    ObjectInputStream ois = new ObjectInputStream(cis);

    // Read objects
    Set set2 = (Set) ois.readObject();
    int last2 = ois.readInt();
    ois.close();

    // Compare original with what was read back
    int count = 0;
    if (set.equals(set2)) {
        System.out.println("Set1: " + set);
        System.out.println("Set2: " + set2);
        System.out.println("Sets are okay.");
        count++;
    }
    if (last == last2) {
        System.out.println("int1: " + last);
        System.out.println("int2: " + last2);
        System.out.println("ints are okay.");
        count++;
    }
    if (count != 2) {
        System.out.println("Problem during encryption/decryption");
    }
}

From source file:Main.java

public static void main(String[] args) {
    JFrame frame = new JFrame();
    DrawPanel dp = new DrawPanel();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(dp);/*from   w w  w.  ja v  a2s .c o m*/
    frame.pack();
    frame.setLocationByPlatform(true);
    try {
        Sequence seq = new Sequence(Sequence.PPQ, 4);
        Track track = seq.createTrack();
        for (int i = 0; i < 120; i += 4) {
            int d = (int) Math.abs(new Random().nextGaussian() * 24) + 32;
            track.add(makeEvent(ShortMessage.NOTE_ON, 1, d, 127, i));
            track.add(makeEvent(ShortMessage.CONTROL_CHANGE, 1, 127, 0, i));
            track.add(makeEvent(ShortMessage.NOTE_OFF, 1, d, 127, i));
        }
        Sequencer sequencer = MidiSystem.getSequencer();
        sequencer.open();
        sequencer.setSequence(seq);
        sequencer.addControllerEventListener(dp, new int[] { 127 });
        sequencer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
    frame.setVisible(true);
}

From source file:main.java.utils.Test.java

public static void main(String[] args) {

    Global.rand = new Random();
    Global.rand.setSeed(0);// w  w w  .  j a v a 2s  .  c o m

    for (int i = 0; i < 5; i++) {
        //System.out.println(RandomStringUtils.randomAlphanumeric(10));
        System.out.println(
                RandomStringGenerator.generateRandomString(10, RandomStringGenerator.Mode.ALPHANUMERIC));
    }
}

From source file:com.offbynull.peernetic.debug.visualizer.App.java

public static void main(String[] args) throws Throwable {
    Random random = new Random();
    Visualizer<Integer> visualizer = new JGraphXVisualizer<>();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Recorder<Integer> recorder = new XStreamRecorder(baos);

    visualizer.visualize(recorder, null);

    visualizer.step("Adding nodes 1 and 2", new AddNodeCommand<>(1),
            new ChangeNodeCommand(1, null, new Point(random.nextInt(400), random.nextInt(400)), Color.RED),
            new AddNodeCommand<>(2),
            new ChangeNodeCommand(2, null, new Point(random.nextInt(400), random.nextInt(400)), Color.BLUE));
    Thread.sleep(500);/* w w w. j  a v  a 2  s  .co m*/

    visualizer.step("Adding nodes 3 and 4", new AddNodeCommand<>(3),
            new ChangeNodeCommand(3, null, new Point(random.nextInt(400), random.nextInt(400)), Color.ORANGE),
            new AddNodeCommand<>(4),
            new ChangeNodeCommand(4, null, new Point(random.nextInt(400), random.nextInt(400)), Color.PINK));
    Thread.sleep(500);

    visualizer.step("Connecting 1/2/3 to 4", new AddEdgeCommand<>(1, 4), new AddEdgeCommand<>(2, 4),
            new AddEdgeCommand<>(3, 4));
    Thread.sleep(500);

    visualizer.step("Adding trigger to 4 when no more edges",
            new TriggerOnLingeringNodeCommand(4, new RemoveNodeCommand<>(4)));
    Thread.sleep(500);

    visualizer.step("Removing connections from 1 and 2", new RemoveEdgeCommand<>(1, 4),
            new RemoveEdgeCommand<>(2, 4));
    Thread.sleep(500);

    visualizer.step("Removing connections from 3", new RemoveEdgeCommand<>(3, 4));
    Thread.sleep(500);

    recorder.close();

    Thread.sleep(2000);

    JGraphXVisualizer<Integer> visualizer2 = new JGraphXVisualizer<>();
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    Player<Integer> player = new XStreamPlayer<>(bais);

    visualizer2.visualize();

    player.play(visualizer2);

}

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

public static void main(String[] args) {
    // initialize data with keys and random values
    int size = 100;
    Random random = new Random();
    final int[][] data = new int[size][];
    for (int i = 0; i < data.length; i++) {
        data[i] = new int[] { i, random.nextInt() };
    }//from w  ww.j a  v  a  2  s. c o  m
    // create a virtual table to display data
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 192");
    shell.setLayout(new FillLayout());
    final Table table = new Table(shell, SWT.VIRTUAL);
    table.setHeaderVisible(true);
    table.setLinesVisible(true);
    table.setItemCount(size);
    final TableColumn column1 = new TableColumn(table, SWT.NONE);
    column1.setText("Key");
    column1.setWidth(200);
    final TableColumn column2 = new TableColumn(table, SWT.NONE);
    column2.setText("Value");
    column2.setWidth(200);
    table.addListener(SWT.SetData, e -> {
        TableItem item = (TableItem) e.item;
        int index = table.indexOf(item);
        int[] datum = data[index];
        item.setText(new String[] { Integer.toString(datum[0]), Integer.toString(datum[1]) });
    });
    // Add sort indicator and sort data when column selected
    Listener sortListener = e -> {
        // determine new sort column and direction
        TableColumn sortColumn = table.getSortColumn();
        TableColumn currentColumn = (TableColumn) e.widget;
        int dir = table.getSortDirection();
        if (sortColumn == currentColumn) {
            dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
        } else {
            table.setSortColumn(currentColumn);
            dir = SWT.UP;
        }
        // sort the data based on column and direction
        final int index = currentColumn == column1 ? 0 : 1;
        final int direction = dir;
        Arrays.sort(data, (a, b) -> {
            if (a[index] == b[index])
                return 0;
            if (direction == SWT.UP) {
                return a[index] < b[index] ? -1 : 1;
            }
            return a[index] < b[index] ? 1 : -1;
        });
        // update data displayed in table
        table.setSortDirection(dir);
        table.clearAll();
    };
    column1.addListener(SWT.Selection, sortListener);
    column2.addListener(SWT.Selection, sortListener);
    table.setSortColumn(column1);
    table.setSortDirection(SWT.UP);
    shell.setSize(shell.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, 300);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:stratego.neural.net.RandomSampleTest.java

public static void main(String[] args) {
    double[] wins = new double[data_points];
    double[] winrate = new double[data_points];
    List<double[]> data = new ArrayList<>();

    for (int i = 0; i < random.length; i++) {
        random[i] = new Random();
    }//from  www . j ava  2s .  c o  m

    for (int index = 0; index < repetitions; index++) {

        for (int i = 0; i < wins.length; i++) {
            wins[i] = (double) random[index].nextInt(2);
        }

        winrate[0] = wins[0];

        for (int i = 1; i < winrate.length; i++) {
            double total_wins = 0;
            for (int j = 0; j < i; j++) {
                total_wins = total_wins + wins[j];
            }
            winrate[i] = (total_wins / i);
        }

        data.add(winrate);
    }

    plotDataSet(data);
}

From source file:Snippet151.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) {
            TableItem item = (TableItem) e.item;
            int index = table.indexOf(item);
            item.setText("Item " + data[index]);
        }/*from w w  w  .  j a  v  a2  s.c  o m*/
    });
    Thread thread = new Thread() {
        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(new Runnable() {
                    public void run() {
                        if (table.isDisposed())
                            return;
                        table.setItemCount(data.length);
                        table.clearAll();
                    }
                });
                try {
                    Thread.sleep(500);
                } catch (Throwable t) {
                }
            }
        }
    };
    thread.start();
    shell.open();
    while (!shell.isDisposed() || thread.isAlive()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:TableSortTwoDirection.java

public static void main(String[] args) {
    // initialize data with keys and random values
    int size = 100;
    Random random = new Random();
    final int[][] data = new int[size][];
    for (int i = 0; i < data.length; i++) {
        data[i] = new int[] { i, random.nextInt() };
    }//from  ww  w.  j  a  v  a 2  s .c o  m
    // create a virtual table to display data
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    final Table table = new Table(shell, SWT.VIRTUAL);
    table.setHeaderVisible(true);
    table.setLinesVisible(true);
    table.setItemCount(size);
    final TableColumn column1 = new TableColumn(table, SWT.NONE);
    column1.setText("Key");
    column1.setWidth(200);
    final TableColumn column2 = new TableColumn(table, SWT.NONE);
    column2.setText("Value");
    column2.setWidth(200);
    table.addListener(SWT.SetData, new Listener() {
        public void handleEvent(Event e) {
            TableItem item = (TableItem) e.item;
            int index = table.indexOf(item);
            int[] datum = data[index];
            item.setText(new String[] { Integer.toString(datum[0]), Integer.toString(datum[1]) });
        }
    });
    // Add sort indicator and sort data when column selected
    Listener sortListener = new Listener() {
        public void handleEvent(Event e) {
            // determine new sort column and direction
            TableColumn sortColumn = table.getSortColumn();
            TableColumn currentColumn = (TableColumn) e.widget;
            int dir = table.getSortDirection();
            if (sortColumn == currentColumn) {
                dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
            } else {
                table.setSortColumn(currentColumn);
                dir = SWT.UP;
            }
            // sort the data based on column and direction
            final int index = currentColumn == column1 ? 0 : 1;
            final int direction = dir;
            Arrays.sort(data, new Comparator() {
                public int compare(Object arg0, Object arg1) {
                    int[] a = (int[]) arg0;
                    int[] b = (int[]) arg1;
                    if (a[index] == b[index])
                        return 0;
                    if (direction == SWT.UP) {
                        return a[index] < b[index] ? -1 : 1;
                    }
                    return a[index] < b[index] ? 1 : -1;
                }
            });
            // update data displayed in table
            table.setSortDirection(dir);
            table.clearAll();
        }
    };
    column1.addListener(SWT.Selection, sortListener);
    column2.addListener(SWT.Selection, sortListener);
    table.setSortColumn(column1);
    table.setSortDirection(SWT.UP);
    shell.setSize(shell.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, 300);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:com.intuit.utils.PopulateUsers.java

public static void main(String[] args) {
    Date now = new Date();
    System.out.println("Current date is: " + now.toString());

    MongoClient mongo = new MongoClient("localhost", 27017);
    DB db = mongo.getDB("tweetsdb");
    DBCollection collection = db.getCollection("userscollection");
    WriteResult result = collection.remove(new BasicDBObject());

    int userIndex = 1;
    for (int i = 1; i <= 10; i++) {
        JSONObject userDocument = new JSONObject();
        String user = "user" + userIndex;
        userDocument.put("user", user);

        JSONArray followerList = new JSONArray();
        Random randomGenerator = new Random();
        for (int j = 0; j < 3; j++) {
            int followerId = randomGenerator.nextInt(10) + 1;
            // Assumption here is, a user will not be a follower on himself
            while (followerId == userIndex) {
                followerId = randomGenerator.nextInt(10) + 1;
            }/*from   w ww.j av  a  2 s. c o  m*/

            String follower = "user" + followerId;
            if (!followerList.contains(follower)) {
                followerList.add(follower);
            }
        }
        userDocument.put("followers", followerList);

        JSONArray followingList = new JSONArray();
        for (int k = 0; k < 3; k++) {
            int followingId = randomGenerator.nextInt(10) + 1;
            // Assumption here is, a user will not be following his own tweets
            while (followingId == userIndex) {
                followingId = randomGenerator.nextInt(10) + 1;
            }

            String followingUser = "user" + followingId;
            if (!followingList.contains(followingUser)) {
                followingList.add(followingUser);
            }
        }
        userDocument.put("following", followingList);
        System.out.println("Json string is: " + userDocument.toString());
        DBObject userDBObject = (DBObject) JSON.parse(userDocument.toString());
        collection.insert(userDBObject);
        userIndex++;

    }

    //        try {
    //            FileWriter file = new FileWriter("/Users/dmurty/Documents/MongoData/usersCollection.js");
    //            file.write(usersArray.toJSONString());
    //            file.flush();
    //            file.close();
    //        } catch (IOException ex) {
    //            Logger.getLogger(PopulateUsers.class.getName()).log(Level.SEVERE, null, ex);
    //        } 
}

From source file:main.java.entry.Main.java

public static void main(String[] args) throws IOException {
    Global.rand = new Random();
    Global.rdg = new RandomDataGenerator();

    Global.LOGGER.info("Simulating shared-nothing OLTP database cluster.");

    ReadConfig.readArgs(args);/* ww w.j a  v  a  2s.  co  m*/

    // Reading simulation aspects
    ReadConfig.readConfigFile("./sim.cnf");

    while (Global.repeatedRuns != 0) {

        Global.LOGGER.info("=============================================================================");
        Global.LOGGER.info("Starting simulation for run " + Global.repeatedRuns + " ...");

        // Re-seed the Random Data Generator
        Global.rand.setSeed(Global.repeatedRuns);
        Global.rdg.reSeed(Global.repeatedRuns);

        // Database initialization and population
        Database db = null;
        Workload wrl = null;

        switch (Global.wrl) {
        case "tpcc":
            db = new TpccDatabase("tpcc");
            wrl = new TpccWorkload("/tpcc.cnf");
            break;

        case "twitter":
            db = new TwitterDatabase("twitter");
            wrl = new TwitterWorkload("/twitter.cnf");
            break;

        default:
            Global.LOGGER.info(Global.run_usage);
            Global.LOGGER.info(Global.abort);
            break;
        }

        // CLuster, Workload Executor, and Metric Collector initialization
        Cluster dbCluster = new Cluster();
        WorkloadExecutor wrlExecutor = new WorkloadExecutor();
        Metric.init(dbCluster);

        // Read TPCC configurations
        wrl.readConfig();

        // Populate initial database                        
        db.populate(wrl);

        // Create a database cluster consisted of a set of physical servers and a consistent hash ring to store the physical data tuples
        WorkloadBatch wb = dbCluster.setup(db, wrl);

        // Workload execution
        wrlExecutor.execute(db, dbCluster, wb, wrl);

        // Close Metric collector
        Metric.close();

        // Proceed for the next iterative simulation run
        Global.LOGGER.info("Simulation ended for iterative run-" + Global.repeatedRuns + ".");
        --Global.repeatedRuns;
    }

    Global.LOGGER.info("Simulation ended.");
}