Java Code Examples for java.util.Random#nextInt()

The following examples show how to use java.util.Random#nextInt() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: FoxBPM   File: RandomAssign.java    License: Apache License 2.0 6 votes vote down vote up
public void assign(DelegateTask task) throws Exception {
	if (null == userId) {
		LOG.warn("处理人选择器(资源中随机分配)用户编号表达式为空 ! 节点编号:" + task.getNodeId());
		return;
	}
	// 获取待分配的用户
	List<String> userIds = AssigneeUtil.executionExpressionObj(userId);
	if (userIds.size() == 1) {
		task.setAssignee(StringUtil.trim(userIds.get(0)));
	} else {
		// 随机产生
		Random random = new Random();
		int index = random.nextInt(userIds.size());
		task.setAssignee(StringUtil.trim(userIds.get(index)));
	}
	
}
 
Example 2
@Override
public void update(TimeStep timeStep, ParticleData particles) {
    this.spawnTimer.update(timeStep);
    if(this.spawnTimer.isOnFirstTime()) {
        particles.emitter.resetUpdaters();
        
        Random rand = particles.emitter.getRandom();
        if(this.maxSpawnTime > this.minSpawnTime) {
            long timer = this.minSpawnTime + rand.nextInt((int)(this.maxSpawnTime - this.minSpawnTime));                
            this.spawnTimer.setEndTime(timer);
            this.spawnTimer.reset();
            
            particles.reset();                
        }
        
        for(int i = 0; i < this.batchSize; i++) {
            int index = particles.spawnParticle();
            if(index > -1) {                    
                updateSingleParticles(index, timeStep, particles);
            }
        }
    }
}
 
Example 3
Source Project: Artifacts   File: ComponentHeal.java    License: MIT License 6 votes vote down vote up
@Override
public String getPreAdj(Random rand) {
	String str = "";
	switch(rand.nextInt(2)) {
		case 0:
			str = "Healing";
			break;
		case 1:
			str = "Rejuvenating";
			break;
		case 2:
			str = "Holy";
			break;
	}
	return str;
}
 
Example 4
/**
 * Task to get the target node for vm crash
 */
protected ClientVmInfo getTargetNodeToKill(Region region) {
  if (region instanceof PartitionedRegion) {
    List otherVMs = new ArrayList(ClientVmMgr.getOtherClientVmids());
    if (ExecuteExceptionBB.getBB().getSharedMap().get(CACHE_CLOSED_VM) != null) {
      Integer cacheClosedVmId = (Integer)ExecuteExceptionBB.getBB()
          .getSharedMap().get(CACHE_CLOSED_VM);
      otherVMs.remove(cacheClosedVmId);
    }
    return new ClientVmInfo((Integer)otherVMs.get(0));
  }
  else {
    List endpoints = BridgeHelper.getEndpoints();
    Random rand = new Random();
    int index = rand.nextInt(endpoints.size() - 1);
    BridgeHelper.Endpoint endpoint = (BridgeHelper.Endpoint)endpoints
        .get(index);
    ClientVmInfo target = new ClientVmInfo(endpoint);
    return target;
  }
}
 
Example 5
@Test
void removeAllWithIteratorTest() {
    final Random rng = new Random(RAND_SEED);
    final LongHopscotchSet hopscotchSet = new LongHopscotchSet(HHASH_NVALS);
    for (int valNo = 0; valNo != HHASH_NVALS; ++valNo) {
        final long longVal = ((long) rng.nextInt()) & ~Long.MIN_VALUE;
        hopscotchSet.add(longVal);
    }
    final LongIterator itr = hopscotchSet.iterator();
    while (itr.hasNext()) {
        final long next = itr.next();
        itr.remove();
        Assert.assertFalse(hopscotchSet.contains(next));
    }
    Assert.assertEquals(hopscotchSet.size(), 0);
}
 
Example 6
@Test
public void testString()
    throws IOException {
  // use arbitrary cardinality and avg string length
  // we will test with complete randomness
  int initialCapacity = 5;
  int estimatedAvgStringLength = 30;
  try (VarByteSingleColumnSingleValueReaderWriter readerWriter =
      new VarByteSingleColumnSingleValueReaderWriter(_memoryManager, "StringColumn",  initialCapacity, estimatedAvgStringLength)) {
    int rows = 1000;
    Random random = new Random();
    String[] data = new String[rows];

    for (int i = 0; i < rows; i++) {
      // generate a random string of length between 10 and 100
      int length = 10 + random.nextInt(100 - 10);
      data[i] = RandomStringUtils.randomAlphanumeric(length);
      readerWriter.setString(i, data[i]);
    }

    for (int i = 0; i < rows; i++) {
      Assert.assertEquals(readerWriter.getString(i), data[i]);
    }
  }
}
 
Example 7
/**
 * permutes the elements of a given array.
 *
 * @param v       the array to permute
 * @param random  the random number generator.
 */
protected void permute( int v[], Random random ) {

  for(int i = v.length - 1; i > 0; i-- ) {
    int j = random.nextInt( i + 1 );
    if( i != j ) {
      int tmp = v[i];
      v[i] = v[j];
      v[j] = tmp;
    }
  }
}
 
Example 8
Source Project: cloud-odata-java   File: StringHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generates a string with given length containing random upper case characters ([A-Z]).
 * @param len length of the generated string
 * @return random upper case characters ([A-Z])
 */
public static String generateData(final int len) {
  Random random = new Random();
  StringBuilder b = new StringBuilder(len);
  for (int j = 0; j < len; j++) {
    final char c = (char) ('A' + random.nextInt('Z' - 'A' + 1));
    b.append(c);
  }
  return b.toString();
}
 
Example 9
@SuppressWarnings("SameParameterValue")
public static String csRandomAlphaNumericString(int numChars) {
	SecureRandom secRand = new SecureRandom();
	Random rand = new Random();
	char[] buff = new char[numChars];

	for (int i = 0; i < numChars; ++i) {
		// reseed rand once you've used up all available entropy bits
		if ((i % 10) == 0)
			rand.setSeed(secRand.nextLong()); // 64 bits of random!

		buff[i] = VALID_CHARACTERS[rand.nextInt(VALID_CHARACTERS.length)];
	}
	return new String(buff);
}
 
Example 10
Source Project: bazel   File: FileWriteActionTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a string filled with (deterministic) random characters to get a string that won't
 * compress to a tiny size.
 */
private String generateLongRandomString() {
  StringBuilder sb = new StringBuilder();
  Random random = new Random(0);
  for (int i = 0; i < 16 * 1024; ++i) {
    char c = (char) random.nextInt(128);
    sb.append(c);
  }
  return sb.toString();
}
 
Example 11
public static String[] getRandomShortName(String name)
{
    String[] fileAndExtension = new String[2];
    String strStep1 = name.replaceAll("\\s+", "");
    boolean first = false;
    StringBuilder strStep2Builder = new StringBuilder(strStep1);
    for(int i=strStep1.length()-1;i>=0;i--)
    {
        if(strStep1.charAt(i) == '.' && !first)
        {
            first = true;
        }else if(strStep1.charAt(i) == '.' && first)
        {
            strStep2Builder.deleteCharAt(i);
        }
    }

    String[] strStep3 = strStep2Builder.toString().split("\\.");
    if(strStep3.length > 1)
    {
        if(strStep3[1].length() > 3)
            strStep3[1] = strStep3[1].substring(0, 3);
        fileAndExtension[1] = strStep3[1];
    }else
        fileAndExtension[1] = "";

    String shortName = "";
    Random r = new Random();
    for(int i=0; i<=5;i++)
    {
        char c = (char)(r.nextInt(26) + 'a');
        shortName += String.valueOf(c);
    }

    shortName += "~";
    shortName += String.valueOf((int) (Math.random() * 10));
    fileAndExtension[0] = shortName;
    return fileAndExtension;
}
 
Example 12
Source Project: terracotta-platform   File: StringTest.java    License: Apache License 2.0 5 votes vote down vote up
private static String randomString(Random rnd, int minLength, int maxLength, int percentNonAscii) {

    final StringBuilder sb = new StringBuilder(maxLength - minLength + 1);
    int remaining = minLength + rnd.nextInt(maxLength - minLength + 1);
    while (remaining > 0) {
      if (percentNonAscii == 0 || rnd.nextInt(100) > percentNonAscii) {
        sb.appendCodePoint((rnd.nextInt(0x7F) + 1));
      } else {
        sb.appendCodePoint(rnd.nextInt(Character.MAX_CODE_POINT) + 1);
      }
      remaining--;
    }

    return sb.toString();
  }
 
Example 13
Source Project: presto   File: TestReadWrite.java    License: Apache License 2.0 4 votes vote down vote up
private static int nextDate(Random random)
{
    return MIN_GENERATED_DATE + random.nextInt(MAX_GENERATED_DATE - MIN_GENERATED_DATE);
}
 
Example 14
@Test
public void testRandomPolynomialsFirstDerivative() {

    Random random = new Random(0x570803c982ca5d3bl);

    for (int i = 0; i < 100; ++i) {

        int maxDegree = 0;
        PolynomialFunction[] p      = new PolynomialFunction[5];
        PolynomialFunction[] pPrime = new PolynomialFunction[5];
        for (int k = 0; k < p.length; ++k) {
            int degree = random.nextInt(7);
            p[k]      = randomPolynomial(degree, random);
            pPrime[k] = p[k].polynomialDerivative();
            maxDegree = FastMath.max(maxDegree, degree);
        }

        HermiteInterpolator interpolator = new HermiteInterpolator();
        for (int j = 0; j < 1 + maxDegree / 2; ++j) {
            double x = 0.1 * j;
            double[] values      = new double[p.length];
            double[] derivatives = new double[p.length];
            for (int k = 0; k < p.length; ++k) {
                values[k]      = p[k].value(x);
                derivatives[k] = pPrime[k].value(x);
            }
            interpolator.addSamplePoint(x, values, derivatives);
        }

        for (double x = 0; x < 2; x += 0.1) {
            DerivativeStructure[] y = interpolator.value(new DerivativeStructure(1, 1, 0, x));
            Assert.assertEquals(p.length, y.length);
            for (int k = 0; k < p.length; ++k) {
                Assert.assertEquals(p[k].value(x), y[k].getValue(), 1.0e-8 * FastMath.abs(p[k].value(x)));
                Assert.assertEquals(pPrime[k].value(x), y[k].getPartialDerivative(1), 4.0e-8 * FastMath.abs(p[k].value(x)));
            }
        }

        PolynomialFunction[] result = interpolator.getPolynomials();
        for (int k = 0; k < p.length; ++k) {
            checkPolynomial(p[k], result[k]);
        }

    }
}
 
Example 15
@Test
public void testSplitableCodecs() throws Exception {
  final Job job = Job.getInstance(defaultConf);
  final Configuration conf = job.getConfiguration();

  // Create the codec
  CompressionCodec codec = null;
  try {
    codec = (CompressionCodec)
    ReflectionUtils.newInstance(conf.getClassByName("org.apache.hadoop.io.compress.BZip2Codec"), conf);
  } catch (ClassNotFoundException cnfe) {
    throw new IOException("Illegal codec!");
  }
  Path file = new Path(workDir, "test"+codec.getDefaultExtension());

  int seed = new Random().nextInt();
  LOG.info("seed = " + seed);
  Random random = new Random(seed);

  localFs.delete(workDir, true);
  FileInputFormat.setInputPaths(job, workDir);

  final int MAX_LENGTH = 500000;
  FileInputFormat.setMaxInputSplitSize(job, MAX_LENGTH / 20);
  // for a variety of lengths
  for (int length = 0; length < MAX_LENGTH;
       length += random.nextInt(MAX_LENGTH / 4) + 1) {

    LOG.info("creating; entries = " + length);

    // create a file with length entries
    Writer writer =
      new OutputStreamWriter(codec.createOutputStream(localFs.create(file)));
    try {
      for (int i = 0; i < length; i++) {
        writer.write(Integer.toString(i * 2));
        writer.write("\t");
        writer.write(Integer.toString(i));
        writer.write("\n");
      }
    } finally {
      writer.close();
    }

    // try splitting the file in a variety of sizes
    KeyValueTextInputFormat format = new KeyValueTextInputFormat();
    assertTrue("KVTIF claims not splittable", format.isSplitable(job, file));
    for (int i = 0; i < 3; i++) {
      int numSplits = random.nextInt(MAX_LENGTH / 2000) + 1;
      LOG.info("splitting: requesting = " + numSplits);
      List<InputSplit> splits = format.getSplits(job);
      LOG.info("splitting: got =        " + splits.size());

      // check each split
      BitSet bits = new BitSet(length);
      for (int j = 0; j < splits.size(); j++) {
        LOG.debug("split["+j+"]= " + splits.get(j));
        TaskAttemptContext context = MapReduceTestUtil.
          createDummyMapTaskAttemptContext(job.getConfiguration());
        RecordReader<Text, Text> reader = format.createRecordReader(
          splits.get(j), context);
        Class<?> clazz = reader.getClass();
        MapContext<Text, Text, Text, Text> mcontext =
          new MapContextImpl<Text, Text, Text, Text>(job.getConfiguration(),
          context.getTaskAttemptID(), reader, null, null,
          MapReduceTestUtil.createDummyReporter(), splits.get(j));
        reader.initialize(splits.get(j), mcontext);

        Text key = null;
        Text value = null;
        try {
          int count = 0;
          while (reader.nextKeyValue()) {
            key = reader.getCurrentKey();
            value = reader.getCurrentValue();
            final int k = Integer.parseInt(key.toString());
            final int v = Integer.parseInt(value.toString());
            assertEquals("Bad key", 0, k % 2);
            assertEquals("Mismatched key/value", k / 2, v);
            LOG.debug("read " + k + "," + v);
            assertFalse(k + "," + v + " in multiple partitions.",bits.get(v));
            bits.set(v);
            count++;
          }
          if (count > 0) {
            LOG.info("splits["+j+"]="+splits.get(j)+" count=" + count);
          } else {
            LOG.debug("splits["+j+"]="+splits.get(j)+" count=" + count);
          }
        } finally {
          reader.close();
        }
      }
      assertEquals("Some keys in no partition.", length, bits.cardinality());
    }

  }
}
 
Example 16
void build(int[] a, int m, Random random) {
    for (int i = 0; i < a.length; i++) {
        a[i] = random.nextInt(m);
    }
}
 
Example 17
Source Project: Flink-CEPplus   File: CharType.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public CharType getRandom(Random rnd) {
	return new CharType((char) rnd.nextInt(10000));
}
 
Example 18
Source Project: jelectrum   File: EleCheck.java    License: MIT License 3 votes vote down vote up
public static void checkBlockHeaderCheckPoint(EleConn conn)
  throws Exception
{
  
  //int blk_n = 109;
  //int cp = 32911;
  Random rnd = new Random();

  for(int i=0; i<20; i++)
  {
    JSONArray params = new JSONArray();
    int cp = rnd.nextInt(630000)+10;
    int blk_n = rnd.nextInt(cp);
    //cp = 5;
    //blk_n = 2;

    params.add(blk_n);
    params.add(cp);

    JSONObject msg = conn.request("blockchain.block.header", params);
    JSONObject result = (JSONObject) msg.get("result");

    String header = (String) result.get("header");
    
    if (header.length() != 160) throw new Exception("Header not 160 chars"); 
    JSONArray branch = (JSONArray) result.get("branch");

    String header_hex = (String) result.get("header");

    
    String root = (String) result.get("root");
    validateMerkle(HexUtil.hexStringToBytes(header_hex), branch, blk_n, cp, root);

  }
  

  
}
 
Example 19
/**
  * Generates a basic dense vector in Polar form
  *
  * @return Dense representation of vector in Polar form.
  */

 public ComplexVector generateRandomVector(int dimension, Random random) {
   
if (getDominantMode().equals(Mode.HERMITIAN))
	return generateHermitianRandomVector(dimension, random);


ComplexVector randomVector = new ComplexVector(dimension, Mode.POLAR_DENSE);

   for (int d = 0; d < randomVector.phaseAngles.length; d++)
     randomVector.phaseAngles[d] = (short) random.nextInt(CircleLookupTable.PHASE_RESOLUTION);

   return randomVector;
 }
 
Example 20
Source Project: DevUtils   File: RandomUtils.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 获取伪随机 int 值
 * @param random Random
 * @return 随机 int 值
 */
public static int nextInt(final Random random) {
    return random != null ? random.nextInt() : new Random().nextInt();
}