Java Code Examples for java.util.Random

The following are top voted examples for showing how to use java.util.Random. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: iot-server-appliances   File: CommunicationUtils.java View source code 6 votes vote down vote up
/**
 * Attempts to find a free port between the MIN_PORT_NUMBER(9000) and MAX_PORT_NUMBER(11000).
 * Tries 'RANDOMLY picked' port numbers between this range up-until "randomAttempts" number of
 * times. If still fails, then tries each port in descending order from the MAX_PORT_NUMBER
 * whilst skipping already attempted ones via random selection.
 *
 * @param randomAttempts no of times to TEST port numbers picked randomly over the given range
 * @return an available/free port
 */
public static synchronized int getAvailablePort(int randomAttempts) {
	ArrayList<Integer> failedPorts = new ArrayList<Integer>(randomAttempts);

	Random randomNum = new Random();
	int randomPort = MAX_PORT_NUMBER;

	while (randomAttempts > 0) {
		randomPort = randomNum.nextInt(MAX_PORT_NUMBER - MIN_PORT_NUMBER) + MIN_PORT_NUMBER;

		if (checkIfPortAvailable(randomPort)) {
			return randomPort;
		}
		failedPorts.add(randomPort);
		randomAttempts--;
	}

	randomPort = MAX_PORT_NUMBER;

	while (true) {
		if (!failedPorts.contains(randomPort) && checkIfPortAvailable(randomPort)) {
			return randomPort;
		}
		randomPort--;
	}
}
 
Example 2
Project: finmath-experiments   File: PseudoRandomNumberSequence.java View source code 6 votes vote down vote up
private void initRandomNumbers() {
	randomNumbers = new double[length];

	// Create random number sequence
	switch(type) {
	case LCG_JAVA:
		Random lcgJava = new Random(seed);
		for(int numberIndex=0; numberIndex < length; numberIndex++) {
			randomNumbers[numberIndex] = lcgJava.nextDouble();
		}
		break;
	case MERSENNE_TWISTER:
	default:
		MersenneTwister64		mersenneTwister		= new MersenneTwister64((int) seed);
		for(int numberIndex=0; numberIndex < length; numberIndex++) {
			randomNumbers[numberIndex] = mersenneTwister.nextDouble();
		}
		break;
	}
}
 
Example 3
Project: netlib   File: Node.java View source code 6 votes vote down vote up
/** constructor for client-side */
public Node(RouterImpl init) {
    if (init == null) {
        throw new NullPointerException("can't init node on NULL server");
    }
    // save a pointer to the server's data
    this.router = init;
    Random rnd = new Random();

    // Diffie-Hellman: generate our secret
    dhPrivate = new BigInteger(dhP.bitLength() - 1, rnd);
    // Diffie-Hellman: generate g^x
    dhX = dhG.modPow(dhPrivate, dhP);
    dhXBytes = convertBigIntegerTo128Bytes(dhX);

    log.fine("Node.<init client>: dhX = \n"
            + Encoding.toHexString(dhXBytes, 100) + "\n" + "dhY = \n"
            + Encoding.toHexString(dhYBytes, 100));

    // generate random symmetric key for circuit creation
    symmetricKeyForCreate = new byte[16];
    rnd.nextBytes(symmetricKeyForCreate);
}
 
Example 4
Project: Biota   File: BlockContainerBiota.java View source code 6 votes vote down vote up
protected void dropInventory(World world, int x, int y, int z)
{
    TileEntity tileEntity = world.getTileEntity(x, y, z);

    if (!(tileEntity instanceof IInventory))
    {
        return;
    }

    IInventory inventory = (IInventory) tileEntity;

    for (int i = 0; i < inventory.getSizeInventory(); i++)
    {
        ItemStack itemStack = inventory.getStackInSlot(i);

        if (itemStack != null && itemStack.stackSize > 0)
        {
            Random rand = new Random();

            float dX = rand.nextFloat() * 0.8F + 0.1F;
            float dY = rand.nextFloat() * 0.8F + 0.1F;
            float dZ = rand.nextFloat() * 0.8F + 0.1F;

            EntityItem entityItem = new EntityItem(world, x + dX, y + dY, z + dZ, itemStack.copy());

            if (itemStack.hasTagCompound())
            {
                entityItem.getEntityItem().setTagCompound((NBTTagCompound) itemStack.getTagCompound().copy());
            }

            float factor = 0.05F;
            entityItem.motionX = rand.nextGaussian() * factor;
            entityItem.motionY = rand.nextGaussian() * factor + 0.2F;
            entityItem.motionZ = rand.nextGaussian() * factor;
            world.spawnEntityInWorld(entityItem);
            itemStack.stackSize = 0;
        }
    }
}
 
Example 5
Project: StreamCruncher   File: AppendOnlyListTest.java View source code 6 votes vote down vote up
public void write() {
    Random random = new Random(System.currentTimeMillis());

    while (totalItems < TOTAL_ITEMS) {
        long item = random.nextLong();
        list.add(item);

        writer.println(item);
        results[totalItems++] = item;

        if (totalItems % 35 == 0) {
            try {
                Thread.sleep(3000);
            }
            catch (InterruptedException e) {
                e.printStackTrace(System.err);
            }
        }
    }

    System.out.println("Writing done!");
}
 
Example 6
Project: SimpleAlgebra_V2   File: TestComplexTrig.java View source code 6 votes vote down vote up
/**
 * Tests a randomly-selected invocation of complex-number <math display="inline">
    * <mrow>
    *  <msup>
    *          <mo>e</mo>
    *        <mi>x</mi>
    *  </msup>
    * </mrow>
    * </math> against its known result.
 * 
 * @param seed The random number seed for generating the invocation.
 * @throws NotInvertibleException
 */
private void seedTestComplexTrig( long seed ) throws NotInvertibleException {
	
	final Random rand = new Random();
	
	rand.setSeed( seed );
	
	final double iValRe = 20.0 * ( rand.nextDouble() - 0.5 );
	
	final double iValIm = 20.0 * ( rand.nextDouble() - 0.5 );
	
	final DoubleElem elRe = new DoubleElem( iValRe );
	
	final DoubleElem elIm = new DoubleElem( iValIm );
	
	final ComplexElem<DoubleElem,DoubleElemFactory> el
		= new ComplexElem<DoubleElem,DoubleElemFactory>( elRe , elIm );
	
	final ComplexElem<DoubleElem,DoubleElemFactory> exp = el.exp( 10 );
	
	final double expectedReal = Math.exp( iValRe ) * Math.cos( iValIm );
	
	final double expectedIm = Math.exp( iValRe ) * Math.sin( iValIm );
	
	Assert.assertEquals( expectedReal , exp.getRe().getVal() , 1E-2 );
	
	Assert.assertEquals( expectedIm , exp.getIm().getVal() , 1E-2 );
}
 
Example 7
Project: SimpleAlgebra_V2   File: TestInvertSparse.java View source code 5 votes vote down vote up
/**
 * Generates a random sparse matrix for a Matrix Algebra <math display="inline">
    * <mrow>
    *  <msub>
    *          <mi>M</mi>
    *        <mn>50</mn>
    *  </msub>
    *  <mfenced open="(" close=")" separators=",">
    *    <mrow>
    *      <mi>R</mi>
    *    </mrow>
    *  </mfenced>
    * </mrow>
    * </math>
 * 
 * @param rand The random number generator.
 * @param se The factory for the enclosed type.
 * @return The random matrix.
 */
protected SquareMatrixElem<TestDimensionFifty,DoubleElem,DoubleElemFactory> generateMat( final Random rand,
		SquareMatrixElemFactory<TestDimensionFifty,DoubleElem,DoubleElemFactory> se )
{
	final BigInteger FIFTY = BigInteger.valueOf( FIFTY_INT );
	
	final SquareMatrixElem<TestDimensionFifty,DoubleElem,DoubleElemFactory> mat = se.zero();
	
	final HashSet<BigInteger> rows = new HashSet<BigInteger>();
	final HashSet<BigInteger> cols = new HashSet<BigInteger>();
	
	int cnt;
	for( cnt = 0 ; cnt < FIFTY_INT ; cnt++ )
	{
		rows.add( BigInteger.valueOf( cnt ) );
		cols.add( BigInteger.valueOf( cnt ) );
	}
	
	while( ( rows.size() > 0 ) || ( cols.size() > 0 ) )
	{
		BigInteger row = null;
		BigInteger col = null;
		
		if( rand.nextBoolean() )
		{
			row = BigInteger.valueOf( rand.nextInt( 2 ) );
			col = BigInteger.ZERO;
		}
		else
		{
			col = BigInteger.valueOf( rand.nextInt( 2 ) );
			row = BigInteger.ZERO;
		}
		
		while( ( row.compareTo( FIFTY ) < 0 ) && ( col.compareTo( FIFTY ) < 0 ) )
		{
			DoubleElem val = new DoubleElem( 2.0 * ( rand.nextDouble() ) - 1.0 );
			// DoubleElem val2 = new DoubleElem( 2.0 * ( rand.nextDouble() ) - 1.0 );
			mat.setVal( row , col , val );
			// mat.setVal( col , row , val2 );
			rows.remove( row );
			cols.remove( col );
			// rows.remove( col );
			// cols.remove( row );
			row = row.add( BigInteger.ONE );
			col = col.add( BigInteger.ONE );
		}
	}
	
	return( mat );
}