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

The following examples show how to use java.util.Random#setSeed() . 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 File: StringGenerator.java    From android-database-performance with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the same random sequence of strings.
 */
public static String[] createFixedRandomStrings(int count) {
    String[] strings = new String[count];

    Random lengthRandom = new Random();
    lengthRandom.setSeed(SEED);

    Random stringRandom = new Random();
    stringRandom.setSeed(SEED);

    for (int i = 0; i < count; i++) {
        int nextLength = lengthRandom.nextInt(MAX_LENGTH - MIN_LENGTH - 1);
        nextLength += MIN_LENGTH;
        strings[i] = RandomStringUtils.random(nextLength, 0, CHARS.length, true, true, CHARS,
                stringRandom);
    }
    return strings;
}
 
Example 2
Source File: FileBench.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private static void fillBlocks(JobConf conf) {
  Random r = new Random();
  long seed = conf.getLong("filebench.seed", -1);
  if (seed > 0) {
    r.setSeed(seed);
  }

  int keylen = conf.getInt("filebench.key.words", 5);
  int vallen = conf.getInt("filebench.val.words", 20);
  int acc = (3 * conf.getInt("io.seqfile.compress.blocksize", 1000000)) >> 1;
  ArrayList<String> k = new ArrayList<String>();
  ArrayList<String> v = new ArrayList<String>();
  for (int i = 0; acc > 0; ++i) {
    String s = generateSentence(r, keylen);
    acc -= s.length();
    k.add(s);
    s = generateSentence(r, vallen);
    acc -= s.length();
    v.add(s);
  }
  keys = k.toArray(new String[0]);
  values = v.toArray(new String[0]);
}
 
Example 3
Source File: TestIndexedSort.java    From hadoop-gpu with Apache License 2.0 6 votes vote down vote up
public void sortSorted(IndexedSorter sorter) throws Exception {
  final int SAMPLE = 500;
  int[] values = new int[SAMPLE];
  Random r = new Random();
  long seed = r.nextLong();
  r.setSeed(seed);
  System.out.println("testSorted seed: " + seed +
      "(" + sorter.getClass().getName() + ")");
  for (int i = 0; i < SAMPLE; ++i) {
    values[i] = r.nextInt(100);
  }
  Arrays.sort(values);
  SampleSortable s = new SampleSortable(values);
  sorter.sort(s, 0, SAMPLE);
  int[] check = s.getSorted();
  assertTrue(Arrays.toString(values) + "\ndoesn't match\n" +
      Arrays.toString(check), Arrays.equals(values, check));
}
 
Example 4
Source File: TapNestingTest.java    From sql-layer with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testRandomTemporaryDisable()
{
    final int N = 100000;
    Random random = new Random();
    random.setSeed(419);
    InOutTap tap = Tap.createTimer("test");
    enable();
    boolean enabled = true;
    for (int i = 0; i < N; i++) {
        if ((i % 2) == 0) {
            tap.in();
        } else {
            tap.out();
        }
        if ((random.nextInt() % 3) == 0) {
            if (enabled) {
                disable();
                enabled = false;
            } else {
                enable();
                enabled = true;
            }
        }
    }
}
 
Example 5
Source File: MSeqTestBase.java    From jenetics with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "sequences")
public void toISeq(final MSeq<Integer> seq) {
	final ISeq<Integer> iseq = seq.toISeq();
	final Integer[] copy = seq.toArray(new Integer[0]);

	final long seed = Randoms.seed();
	final Random random = new Random(seed);
	for (int i = 0; i < seq.length(); ++i) {
		seq.set(i, random.nextInt());
	}

	random.setSeed(seed);
	for (int i = 0; i < seq.length(); ++i) {
		Assert.assertEquals(seq.get(i).intValue(), random.nextInt());
	}

	for (int i = 0; i < seq.length(); ++i) {
		Assert.assertEquals(iseq.get(i), copy[i]);
	}
}
 
Example 6
Source File: MineshaftAlgorithm_Base.java    From amidst with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean isValidLocation(int chunkX, int chunkY) {
	/**
	 * Note: even if this check succeeds, the mineshaft may fail to generate if the
	 * central room isn't in a suitable location (for example, if it spawns inside
	 * a cave or a ravine). We can't check these cases, so we will have to accept
	 * some false positives.
	 */
	Random random = new Random(seed);

	long var13 = chunkX * random.nextLong();
	long var15 = chunkY * random.nextLong();

	random.setSeed(var13 ^ var15 ^ seed);
	if(doExtraCheck())
		random.nextInt();

	if(!getResult(chunkX, chunkY, random))
		return false;
	return !doExtraCheck() || random.nextInt(80) < Math.max(Math.abs(chunkX), Math.abs(chunkY));
}
 
Example 7
Source File: KeyGenerator.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 8
Source File: RandomAdaptorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void checkConstant(Random random) {
    byte[] bytes = new byte[] {0};
    random.nextBytes(bytes);
    assertEquals(0, bytes[0]);
    assertEquals(false, random.nextBoolean());
    assertEquals(0, random.nextDouble(), 0);
    assertEquals(0, random.nextFloat(), 0);
    assertEquals(0, random.nextGaussian(), 0);
    assertEquals(0, random.nextInt());
    assertEquals(0, random.nextInt(1));
    assertEquals(0, random.nextLong());
    random.setSeed(100);
    assertEquals(0, random.nextDouble(), 0);
}
 
Example 9
Source File: TestGridmixRecord.java    From hadoop with Apache License 2.0 5 votes vote down vote up
static void binSortTest(GridmixRecord x, GridmixRecord y, int min,
    int max, WritableComparator cmp) throws Exception {
  final Random r = new Random();
  final long s = r.nextLong();
  r.setSeed(s);
  LOG.info("sort: " + s);
  final DataOutputBuffer out1 = new DataOutputBuffer();
  final DataOutputBuffer out2 = new DataOutputBuffer();
  for (int i = min; i < max; ++i) {
    final long seed1 = r.nextLong();
    setSerialize(x, seed1, i, out1);
    assertEquals(0, x.compareSeed(seed1, Math.max(0, i - x.fixedBytes())));

    final long seed2 = r.nextLong();
    setSerialize(y, seed2, i, out2);
    assertEquals(0, y.compareSeed(seed2, Math.max(0, i - x.fixedBytes())));

    // for eq sized records, ensure byte cmp where req
    final int chk = WritableComparator.compareBytes(
        out1.getData(), 0, out1.getLength(),
        out2.getData(), 0, out2.getLength());
    assertEquals(Integer.signum(chk), Integer.signum(x.compareTo(y)));
    assertEquals(Integer.signum(chk), Integer.signum(cmp.compare(
          out1.getData(), 0, out1.getLength(),
          out2.getData(), 0, out2.getLength())));
    // write second copy, compare eq
    final int s1 = out1.getLength();
    x.write(out1);
    assertEquals(0, cmp.compare(out1.getData(), 0, s1,
          out1.getData(), s1, out1.getLength() - s1));
    final int s2 = out2.getLength();
    y.write(out2);
    assertEquals(0, cmp.compare(out2.getData(), 0, s2,
          out2.getData(), s2, out2.getLength() - s2));
    assertEquals(Integer.signum(chk), Integer.signum(cmp.compare(out1.getData(), 0, s1,
          out2.getData(), s2, out2.getLength() - s2)));
  }
}
 
Example 10
Source File: StringGenerator.java    From android-database-performance with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the same random sequence of indexes. To be used to select strings by {@link
 * #createFixedRandomStrings(int)}.
 */
public static int[] getFixedRandomIndices(int count, int maxIndex) {
    int[] indices = new int[count];

    Random random = new Random();
    random.setSeed(StringGenerator.SEED);

    for (int i = 0; i < count; i++) {
        indices[i] = random.nextInt(maxIndex + 1);
    }

    return indices;
}
 
Example 11
Source File: RollingMethodsTest.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public final void testTopRoll()
{
	final Random random = new Random(SEED);
	RandomUtil.setRandomGenerator(random);

	final int[] keepArr = IntStream.rangeClosed(TIMES - KEEP, KEEP).toArray();

	random.setSeed(SEED);
	int[] rolls = IntStream.generate(() -> RollingMethods.roll(SIDES)).limit(TIMES).sorted().toArray();

	// compute the sum of all the rolls
	final int sum = IntStream.of(rolls).sum();

	// drop the lowest N rolls and sum
	final int dropSum = sum-IntStream.of(rolls).limit(TIMES-KEEP).sum();

	// reset the seed so we generate the same random numbers
	random.setSeed(SEED);
	final int testDropSum = RollingMethods.roll(TIMES, SIDES, keepArr);

	// verify the RollingMethods generates the correct results
	assertEquals(dropSum, testDropSum);

	final String topStr = "roll("+TIMES+","+SIDES+",top("+KEEP+"))";
	
	// reset the seed so we generate the same random numbers
	random.setSeed(SEED);

	// verify the RollingMethods generates the correct results
	final int strDropSum = RollingMethods.roll(topStr);
	assertEquals(dropSum, strDropSum);

}
 
Example 12
Source File: DataFrameBenchmark.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private static Long[] generateLongObjectData(int n) {
  Random r = new Random();
  r.setSeed(SEED);
  Long[] values = new Long[n];
  for(int i=0; i<n; i++) {
    values[i] = r.nextLong();
  }
  return values;
}
 
Example 13
Source File: Pkcs8Util.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private static int generateIterationCount() {
	// Generate a random iteration count in range 1000-1999
	Random rng = new Random();
	rng.setSeed(Calendar.getInstance().getTimeInMillis());

	int random = rng.nextInt();

	int mod1000 = random % 1000;

	return mod1000 + 1000;
}
 
Example 14
Source File: TestCombineTextInputFormat.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Test(timeout=10000)
public void testFormat() throws Exception {
  JobConf job = new JobConf(defaultConf);

  Random random = new Random();
  long seed = random.nextLong();
  LOG.info("seed = "+seed);
  random.setSeed(seed);

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

  final int length = 10000;
  final int numFiles = 10;

  createFiles(length, numFiles, random);

  // create a combined split for the files
  CombineTextInputFormat format = new CombineTextInputFormat();
  LongWritable key = new LongWritable();
  Text value = new Text();
  for (int i = 0; i < 3; i++) {
    int numSplits = random.nextInt(length/20)+1;
    LOG.info("splitting: requesting = " + numSplits);
    InputSplit[] splits = format.getSplits(job, numSplits);
    LOG.info("splitting: got =        " + splits.length);

    // we should have a single split as the length is comfortably smaller than
    // the block size
    assertEquals("We got more than one splits!", 1, splits.length);
    InputSplit split = splits[0];
    assertEquals("It should be CombineFileSplit",
      CombineFileSplit.class, split.getClass());

    // check the split
    BitSet bits = new BitSet(length);
    LOG.debug("split= " + split);
    RecordReader<LongWritable, Text> reader =
      format.getRecordReader(split, job, voidReporter);
    try {
      int count = 0;
      while (reader.next(key, value)) {
        int v = Integer.parseInt(value.toString());
        LOG.debug("read " + v);
        if (bits.get(v)) {
          LOG.warn("conflict with " + v +
                   " at position "+reader.getPos());
        }
        assertFalse("Key in multiple partitions.", bits.get(v));
        bits.set(v);
        count++;
      }
      LOG.info("splits="+split+" count=" + count);
    } finally {
      reader.close();
    }
    assertEquals("Some keys in no partition.", length, bits.cardinality());
  }
}
 
Example 15
Source File: RandomUtilsTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** test distribution of nextInt(Random) */
public void testNextInt2() {
    Random rnd = new Random();
    rnd.setSeed(System.currentTimeMillis());
    tstNextInt(rnd);
}
 
Example 16
Source File: KDEDistributionTest.java    From beast-mcmc with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testSampleWitchHat() {
        // Witch hat gamma
        Random randUnif = new Random();
        randUnif.setSeed(17920920); // The day before
        int length = 10000;
        Double[] samples = new Double[length];
        double scale = 0.001;
        for (int i = 0; i < samples.length; i++) {
            samples[i] = randUnif.nextDouble();
            samples[i] = -Math.log(samples[i]) * scale; // Gamma(1, scale)
        }

        // R vector
        System.out.print("samples <- c(");
        for (int i = 0; i < samples.length - 1; i++) {
            System.out.print(samples[i] + ",");
        }
        System.out.println(samples[samples.length - 1] + ")\n");

        // Estimations
        NormalKDEDistribution nKDE = new NormalKDEDistribution(samples, null, null, null, 2048);
        LogTransformedNormalKDEDistribution ltnOld = new LogTransformedNormalKDEDistribution(samples);
        TransformedNormalKDEDistribution ltnNew = getLogTransformedNormalKDEDistribution(samples);

        // R estimations
        /*
        densNormal <- density(samples, n = 512, bw = "nrd")
        densLogNormal <- logKDE::logdensity_fft(samples, n = 2048, bw = "nrd")
         */

        // bandwidth
        double tolerance = 1E-3;
        assertEquals(rBandWidth[1], nKDE.getBandWidth(), tolerance);
        assertEquals(rLogBandWidth[0], ltnNew.getBandWidth(), tolerance);

        System.out.println("bw(normal) = " + nKDE.getBandWidth());
        System.out.println("bw(logNormal) = " + ltnNew.getBandWidth());
        System.out.println("bw(logNormalOLD) = " + ltnOld.getBandWidth());

        // cdf normal (Fails)
        double cdf = nKDE.cdf(0.00005);
        System.out.println("cdf(0.00005) = " + cdf);
//        assertEquals(cdf, 0.04877058, cdfTolerance);
        cdf = nKDE.cdf(0.0001);
        System.out.println("cdf(0.0001) = " + cdf);
//        assertEquals(cdf, 0.09516258, cdfTolerance);
        cdf = nKDE.cdf(0.001);
        System.out.println("cdf(0.001) = " + cdf);
//        assertEquals(cdf, 0.6321206, cdfTolerance);

        // cdf log normal (Succeeds)
        cdf = ltnNew.cdf(0.00005);
        System.out.println("cdfLog(0.00005) = " + cdf);
        assertEquals(cdf, 0.04877058, cdfTolerance);
        cdf = ltnNew.cdf(0.0001);
        System.out.println("cdfLog(0.0001) = " + cdf);
        assertEquals(cdf, 0.09516258, cdfTolerance);
        cdf = ltnNew.cdf(0.001);
        System.out.println("cdfLog(0.001) = " + cdf);
        assertEquals(cdf, 0.6321206, cdfTolerance);

        // cdf log normal old (Fails)
        cdf = ltnOld.cdf(0.00005);
        System.out.println("cdfLogOld(0.00005) = " + cdf);
//        assertEquals(cdf, 0.04877058, cdfTolerance);
        cdf = ltnOld.cdf(0.0001);
        System.out.println("cdfLogOld(0.0001) = " + cdf);
//        assertEquals(cdf, 0.09516258, cdfTolerance);
        cdf = ltnOld.cdf(0.001);
        System.out.println("cdfLogOld(0.001) = " + cdf);
//        assertEquals(cdf, 0.6321206, cdfTolerance);

    }
 
Example 17
Source File: TestResourceLocalizationService.java    From big-c with Apache License 2.0 4 votes vote down vote up
@Test( timeout = 10000)
@SuppressWarnings("unchecked") // mocked generics
public void testLocalizerRunnerException() throws Exception {
  DrainDispatcher dispatcher = new DrainDispatcher();
  dispatcher.init(conf);
  dispatcher.start();
  EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
  dispatcher.register(ApplicationEventType.class, applicationBus);
  EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
  dispatcher.register(ContainerEventType.class, containerBus);

  ContainerExecutor exec = mock(ContainerExecutor.class);
  LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
  LocalDirsHandlerService dirsHandlerSpy = spy(dirsHandler);
  dirsHandlerSpy.init(conf);

  DeletionService delServiceReal = new DeletionService(exec);
  DeletionService delService = spy(delServiceReal);
  delService.init(new Configuration());
  delService.start();

  ResourceLocalizationService rawService =
      new ResourceLocalizationService(dispatcher, exec, delService,
      dirsHandlerSpy, nmContext);
  ResourceLocalizationService spyService = spy(rawService);
  doReturn(mockServer).when(spyService).createServer();
  try {
    spyService.init(conf);
    spyService.start();

    // init application
    final Application app = mock(Application.class);
    final ApplicationId appId =
        BuilderUtils.newApplicationId(314159265358979L, 3);
    when(app.getUser()).thenReturn("user0");
    when(app.getAppId()).thenReturn(appId);
    spyService.handle(new ApplicationLocalizationEvent(
        LocalizationEventType.INIT_APPLICATION_RESOURCES, app));
    dispatcher.await();

    Random r = new Random();
    long seed = r.nextLong();
    System.out.println("SEED: " + seed);
    r.setSeed(seed);
    final Container c = getMockContainer(appId, 42, "user0");
    final LocalResource resource1 = getPrivateMockedResource(r);
    System.out.println("Here 4");
    
    final LocalResourceRequest req1 = new LocalResourceRequest(resource1);
    Map<LocalResourceVisibility, Collection<LocalResourceRequest>> rsrcs =
      new HashMap<LocalResourceVisibility, 
                  Collection<LocalResourceRequest>>();
    List<LocalResourceRequest> privateResourceList =
        new ArrayList<LocalResourceRequest>();
    privateResourceList.add(req1);
    rsrcs.put(LocalResourceVisibility.PRIVATE, privateResourceList);

    final Constructor<?>[] constructors =
        FSError.class.getDeclaredConstructors();
    constructors[0].setAccessible(true);
    FSError fsError =
        (FSError) constructors[0].newInstance(new IOException("Disk Error"));

    Mockito
      .doThrow(fsError)
      .when(dirsHandlerSpy)
      .getLocalPathForWrite(isA(String.class));
    spyService.handle(new ContainerLocalizationRequestEvent(c, rsrcs));
    Thread.sleep(1000);
    dispatcher.await();
    // Verify if ContainerResourceFailedEvent is invoked on FSError
    verify(containerBus).handle(isA(ContainerResourceFailedEvent.class));
  } finally {
    spyService.stop();
    dispatcher.stop();
    delService.stop();
  }
}
 
Example 18
Source File: RandomUtilsTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** test distribution of nextDouble(Random) */
public void testNextDouble2() {
    Random rnd = new Random();
    rnd.setSeed(System.currentTimeMillis());
    tstNextDouble(rnd);
}
 
Example 19
Source File: SpilledBufferOrEventSequenceTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
@Test
public void testMixedSequence() {
	try {
		final Random rnd = new Random();
		final Random bufferRnd = new Random();

		final long bufferSeed = rnd.nextLong();
		bufferRnd.setSeed(bufferSeed);

		final int numEventsAndBuffers = 3000;
		final int numberOfChannels = 1656;

		final ArrayList<BufferOrEvent> events = new ArrayList<BufferOrEvent>(128);

		// generate sequence

		for (int i = 0; i < numEventsAndBuffers; i++) {
			boolean isEvent = rnd.nextDouble() < 0.05d;
			if (isEvent) {
				events.add(generateAndWriteEvent(fileChannel, rnd, numberOfChannels));
			}
			else {
				writeBuffer(fileChannel, bufferRnd.nextInt(pageSize) + 1, bufferRnd.nextInt(numberOfChannels));
			}
		}

		// reset and create reader

		fileChannel.position(0L);
		bufferRnd.setSeed(bufferSeed);
		SpilledBufferOrEventSequence seq = new SpilledBufferOrEventSequence(tempFile, fileChannel, buffer, pageSize);
		seq.open();

		// read and validate the sequence

		int numEvent = 0;
		for (int i = 0; i < numEventsAndBuffers; i++) {
			BufferOrEvent next = seq.getNext();
			if (next.isEvent()) {
				BufferOrEvent expected = events.get(numEvent++);
				assertEquals(expected.getEvent(), next.getEvent());
				assertEquals(expected.getChannelIndex(), next.getChannelIndex());
			}
			else {
				validateBuffer(next, bufferRnd.nextInt(pageSize) + 1, bufferRnd.nextInt(numberOfChannels));
			}
		}

		// no further data
		assertNull(seq.getNext());

		// all events need to be consumed
		assertEquals(events.size(), numEvent);
	}
	catch (Exception e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example 20
Source File: Scribbler.java    From pumpernickel with MIT License 4 votes vote down vote up
/**
 * 
 * @param tol
 *            a float from [0,1]
 * @param movement
 *            a float from [0,1]
 */
public static void create(Shape s, float tol, float movement,
		long randomSeed, PathWriter writer) {
	Random random = new Random(randomSeed);
	PathIterator i = s.getPathIterator(null, .2);
	float[] f = new float[6];
	float x = 0;
	float y = 0;
	float dx = 0;
	float dy = 0;
	int segments;
	float startX;
	float startY;
	float progress;
	float newX, newY;
	while (i.isDone() == false) {
		int k = i.currentSegment(f);
		if (k == PathIterator.SEG_MOVETO) {
			x = f[0];
			y = f[1];
			writer.moveTo(x, y);
		} else if (k == PathIterator.SEG_LINETO) {
			random.setSeed(randomSeed);
			startX = x;
			startY = y;
			segments = (int) (Math.sqrt((f[0] - x) * (f[0] - x)
					+ (f[1] - y) * (f[1] - y)) / 10 + .5);
			if (segments <= 0)
				segments = 1;

			for (k = 0; k < segments; k++) {
				dx += movement / 2 - movement * random.nextFloat();
				if (dx > tol)
					dx = tol;
				if (dx < -tol)
					dx = -tol;
				dy += movement / 2 - movement * random.nextFloat();
				if (dy > tol)
					dy = tol;
				if (dy < -tol)
					dy = -tol;
				progress = ((float) k + 1) / (segments);
				newX = f[0] * progress + startX * (1 - progress) + dx;
				newY = f[1] * progress + startY * (1 - progress) + dy;
				writer.lineTo(newX, newY);
				x = newX;
				y = newY;
			}
			x = f[0];
			y = f[1];
		} else if (k == PathIterator.SEG_CLOSE) {
			writer.closePath();
		}
		i.next();
	}
}