Example usage for java.lang Math random

List of usage examples for java.lang Math random

Introduction

In this page you can find the example usage for java.lang Math random.

Prototype

public static double random() 

Source Link

Document

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0 .

Usage

From source file:Main.java

public MyModel(int size) {
    arraySize = size;//  w w w . j av a 2  s  .  c om
    myArray = new int[arraySize];
    for (int i = 0; i < arraySize; i++) {
        myArray[i] = (int) (Math.random() * 99) + 1;
    }
}

From source file:com.callidusrobotics.droptables.view.ResultListViewTest.java

@Before
public void before() throws Exception {
    results = new ArrayList<ResultEntry>();
    for (int i = 0; i < 10; i++) {
        ResultEntry result = ModelUtil.buildResult();
        Map<String, String> params = new HashMap<String, String>();
        params.put("foo", "" + (int) (Math.random() * 1000));
        result.setParameters(params);//from w  w w.  java  2s  .co  m
        results.add(result);
    }
    results.get(0).setReport(null);
    ModelUtil.clearTTL(results.get(1));

    view = new ResultListView(results);
    renderer = new FreemarkerViewRenderer();
    writer = new ByteArrayOutputStream();
}

From source file:com.ciphertool.genetics.algorithms.mutation.cipherkey.RandomValueMutationAlgorithm.java

@Override
public void mutateChromosome(KeyedChromosome<Object> chromosome) {
    if (maxMutationsPerChromosome == null) {
        throw new IllegalStateException("The maxMutationsPerChromosome cannot be null.");
    }/*from w w w  . ja v a  2s  . c  o m*/

    /*
     * Choose a random number of mutations constrained by the configurable
     * max and the total number of genes
     */
    int numMutations = (int) (Math.random() * Math.min(maxMutationsPerChromosome, chromosome.getGenes().size()))
            + 1;

    Set<Object> availableKeys = chromosome.getGenes().keySet();

    for (int i = 0; i < numMutations; i++) {
        // Keep track of the mutated keys
        mutateRandomGene(chromosome, availableKeys);
    }
}

From source file:gov.nih.nci.cabig.ctms.tools.configuration.DatabaseBackedConfigurationTest.java

@Override
protected void setUp() throws Exception {
    super.setUp();
    sessionFactory = new AnnotationConfiguration().addAnnotatedClass(DefaultConfigurationEntry.class)
            .addAnnotatedClass(AlternateConfigurationEntry.class)
            .setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver")
            .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test" + Math.random())
            .setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "")
            .buildSessionFactory();//from   ww  w  .  j a va2 s  .  co m
    stubListener = new StubConfigurationListener();
    configuration = new ExampleConfiguration();
    configuration.setSessionFactory(sessionFactory);
    configuration.addConfigurationListener(stubListener);
    altConfiguration = new AlternateConfiguration();
    altConfiguration.setSessionFactory(sessionFactory);
    SingleConnectionDataSource ds = new SingleConnectionDataSource(sessionFactory.openSession().connection(),
            false);
    ds.setAutoCommit(true);
    jdbc = new JdbcTemplate(ds);

    for (String table : new String[] { DEFAULT_TABLE, ALT_TABLE }) {
        jdbc.execute(String.format(
                "CREATE TABLE %s (key VARCHAR(255) PRIMARY KEY, value VARCHAR(255), version INTEGER DEFAULT '0' NOT NULL)",
                table));
    }
}

From source file:com.ciphertool.genetics.algorithms.mutation.ConservativeMutationAlgorithm.java

@Override
public void mutateChromosome(Chromosome chromosome) {
    if (maxMutationsPerChromosome == null) {
        throw new IllegalStateException("The maxMutationsPerChromosome cannot be null.");
    }// ww w  .ja v a 2s  . c  o  m

    /*
     * Choose a random number of mutations constrained by the configurable
     * max and the total number of genes
     */
    int numMutations = (int) (Math.random() * Math.min(maxMutationsPerChromosome, chromosome.getGenes().size()))
            + 1;

    List<Integer> geneIndices = new ArrayList<Integer>();
    for (int i = 0; i < numMutations; i++) {
        // Keep track of the mutated indices
        geneIndices.add(mutateRandomGene(chromosome, geneIndices));
    }
}

From source file:tech.beshu.ror.integration.FiltersAndFieldsSecurityTests.java

private static void insertDoc(String docName, RestClient restClient, String idx, String field) {
    if (adminClient == null) {
        adminClient = restClient;//ww w  .  j a v a 2s  .co  m
    }

    String path = "/" + IDX_PREFIX + idx + "/documents/doc-" + docName + String.valueOf(Math.random());
    try {

        HttpPut request = new HttpPut(restClient.from(path));
        request.setHeader("Content-Type", "application/json");
        request.setHeader("refresh", "true");
        request.setHeader("timeout", "50s");
        request.setEntity(new StringEntity("{\"" + field + "\": \"" + docName + "\", \"dummy\": true}"));
        System.out.println(body(restClient.execute(request)));

    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Test problem", e);
    }

    // Polling phase.. #TODO is there a better way?
    try {
        HttpResponse response;
        do {
            HttpHead request = new HttpHead(restClient.from(path));
            request.setHeader("x-api-key", "p");
            response = restClient.execute(request);
            System.out.println(
                    "polling for " + docName + ".. result: " + response.getStatusLine().getReasonPhrase());
            Thread.sleep(200);
        } while (response.getStatusLine().getStatusCode() != 200);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Cannot configure test case", e);
    }
}

From source file:gov.nih.nci.caintegrator.application.zip.FileNameGenerator.java

public static String generateUniqueFileName(String fileName, String type, String platform) {
    String uniqueZipFileName = null;
    String platformID = null;//from  w  ww  . jav a  2 s.co  m

    if (fileName != null && type != null && platform != null) {
        if (platform.equals(Constants.AFFY_OLIGO_PLATFORM)) {
            platformID = "AFFY-U133P2";
        } else if (platform.equals(Constants.AFFY_100K_SNP_ARRAY)) {
            platformID = "AFFY-100K-SNP";
        }
        uniqueZipFileName = createFilename(fileName);
        // Get a random number of up to 7 digits      
        int sevenDigitRandom = new Double(Math.random() * 10000000).intValue();

        // Get the last 7 digits of the Java timestamp
        String s = String.valueOf(System.currentTimeMillis());
        String lastSevenOfTimeStamp = s.substring(s.length() - 7, s.length());

        // Put it all together
        uniqueZipFileName = fileName + "_" + platformID + "_" + type + "_" + sevenDigitRandom
                + lastSevenOfTimeStamp;
    }
    return uniqueZipFileName;
}

From source file:com.almende.test.dht.TestScale.java

/**
 * Test a large nof nodes./*from  w w  w  . ja v  a2 s  .com*/
 * 
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws URISyntaxException
 *             the URI syntax exception
 * @throws InterruptedException
 *             the interrupted exception
 */
@Test
public void testScale() throws IOException, URISyntaxException, InterruptedException {
    DHTAgent[] agents = new DHTAgent[NOFNODES];

    DHTAgent agent = new DHTAgent("agent_0");
    agents[0] = agent;
    for (int i = 1; i < NOFNODES; i++) {
        System.out.print("Created node:agent_" + i + "\r");
        DHTAgent next = new DHTAgent("agent_" + i);
        try {
            next.getDht().join(agent.asNode());
        } catch (NullPointerException e) {
            System.err.println("NPE at:" + i);
            throw e;
        }
        agent = next;
        agents[i] = agent;
    }
    final Key key = Key.fromString("Hello world");
    final ObjectNode value = JOM.createObjectNode();
    value.put("Hello:", "world!");
    agents[0].getDht().iterative_store_value(key, value);

    JsonNode result = agents[(int) Math.floor(Math.random() * NOFNODES)].getDht()
            .iterative_find_value(Key.fromString("Hello world"), false);

    assertEquals(result, value);

    final int otherIdx = (int) Math.floor(Math.random() * NOFNODES);
    JsonNode result2 = agents[otherIdx].getDht().iterative_find_value(Key.fromString("Hello world"), false);
    assertEquals(result2, value);

    final Key key2 = Key.fromString("Some other key");
    final ObjectNode value2 = JOM.createObjectNode();
    value2.put("Hello:", "world2!");
    agents[0].getDht().iterative_store_value(key2, value2);

    JsonNode result3 = agents[(int) Math.floor(Math.random() * NOFNODES)].getDht()
            .iterative_find_value(Key.fromString("Some other key"), false);

    assertEquals(result3, value2);

    JsonNode result4 = agents[otherIdx].getDht().iterative_find_value(Key.fromString("Hello world"), false);
    assertNotSame(result4, value2);
    assertEquals(result4, value);

    JsonNode result5 = agents[otherIdx].getDht().iterative_find_value(Key.fromString("Hello world"), false);
    assertEquals(result5, value);
    JsonNode result6 = agents[otherIdx].getDht().iterative_find_value(Key.fromString("Hello world!"), false);
    assertNotSame(result6, value);
    assertEquals(result6, JOM.createNullNode());

    final BitSet set = key2.getVal();
    set.set(10, !set.get(10));
    final Key key3 = new Key(set);
    final ObjectNode value3 = JOM.createObjectNode();
    value3.put("Hello:", "world3!");
    agents[0].getDht().iterative_store_value(key3, value3);

    JsonNode result7 = agents[otherIdx + 2].getDht().iterative_find_value(key3, false);
    assertEquals(result7, value3);

    int count = 0;
    for (final DHTAgent a : agents) {
        if (a.getDht().hasValues()) {
            count++;
        }
    }
    System.out.println(count + " agents have some value stored.");
}

From source file:net.audumla.climate.bom.BOMClimateObserverCatalogue.java

protected static String generationCoordinateURL(ClimateDataSource llsource, String key) {
    // http://www.bom.gov.au/jsp/ncc/cdio/weatherData/av?p_stn_num=86071&p_display_type=nearest10_tab2&p_nccObsCode=139&p_match=50,,37.70,145.0972,,LATLON,201&sid=0.7166697874199599
    // 3079_86068 Watsonia VIC (4.5km away)
    String p_stn_num = "p_stn_num=86071&";
    String p_display_type = "p_display_type=nearest10_tab2&";
    String p_nccObsCode = "p_nccObsCode=139&";
    String p_match = "p_match=50,," + (-1 * llsource.getLatitude()) + "," + llsource.getLongitude()
            + ",,LATLON," + key;
    String sid = String.valueOf(Math.random());
    String url = BOMLatLongLookup + p_stn_num + p_display_type + p_nccObsCode + p_match + sid;
    return url;/* w  ww  .  j a v  a2 s  .c o  m*/

}

From source file:com.msopentech.odatajclient.proxy.api.context.EntityUUID.java

public EntityUUID(final String schemaName, final String containerName, final String entitySetName,
        final String name, final Object key) {
    this.schemaName = schemaName;
    this.containerName = containerName;
    this.entitySetName = entitySetName;
    this.name = name;
    this.key = key;
    this.tempKey = (int) (Math.random() * 1000000);
}