random.nextDouble creates the same sequence in a for block - java

I have the following code to create a random series of a numbers from 0 to a given amount.
ArrayList<Integer> places = new ArrayList<Integer>();
for (int cnt = 0; cnt < NUMBER; cnt++) {
int place = (int)(random.nextDouble()*places.size());
places.add(place , new Integer(cnt));
}
I use this code in a method and then I run this method for about 1000 times for statistics purposes.
My problem is that created series is the same for all of the 1000 time.
Every time that I run the sequence is different, but same for all of the for values.
What should I do? Is there a method like srand() in C++?

Your algorithm seems flawed if you are trying to generate an array with numbers 0 ... NUMBER-1 in random order. Consider:
Random rnd = new Random(System.currentTimeMillis());
...
ArrayList<Integer> places = new ArrayList<Integer>(NUMBER);
for (int i = 0; i < NUMBER; ++i) {
places.add(i);
}
Collections.shuffle(places, rnd);

Use you use Math.random(). It will return a double from 0.0 to 1.0 exclusively. So you can replace the 2 lines inside the for loop with this:
places.add((int)(Math.random() * places.size()),cnt);
//you don't have to do "new Integer(cnt)" because of Java's auto-boxing feature

Related

How to make a random super increasing array

I'm having a lab about making a Merkle Hellman Knapsack,the request said i need to make an automatically super increasing array but i don't know how to make it,is there any way to make it ? Thanks for reading
Random random = new Random();
int[] wInt = random.ints(8, 1, 999).toArray();
for(int i = 0; i < 8 - 1; i++) {
for (int j = i + 1; j < wInt.length; j++) {
if(wInt[i] > wInt[j]) {
int temp = wInt[i];
wInt[i] = wInt[j];
wInt[j] = temp;
}
}
}
A superincreasing sequence is one where each term is at least as big as the sum of all the preceding terms. Therefore, one way to generate a superincreasing sequence would be to keep track of the sum of all elements currently in the sequence, then to add some random, nonzero number onto the total when forming the next element. In pseudocode:
sequence = []
total = 0
while the sequence has fewer than n items in it:
total += some random number
append total to the sequence
I'll leave it as an exercise to translate this into your Programming Language of Choice.

How to initialize an Integer Array with multiple values while using "for"

While I was trying to create a small GUI in Java, I've stumbled onto this small issue with arrays.
I've tried inserting Random Integers into an one dimensional array, only to find out that the Random Integers won't get assigned.
//Declaring an Integer Array
int[] wuerfel = new int[2];
//It will loop once while assigning a random number to the array
for(int i = 0; i <= 1; i++) {
Random rand = new Random(6);
int zahlen = rand.nextInt(6) + 1;
wuerfel[i] = zahlen;
}
System.out.println(Arrays.toString(wuerfel));
I expect the output from the array to be a number between 1 - 6.
However, I keep receiving [2,2] as a result every time I try to rerun.
The constructor call new Random(6) doesn't do what you think it does: 6 is the seed, rather than the range of possible outputs. Therefore it will produce the same output every time.
Possible solutions:
Use the no-argument constructor for Random() instead, which will give it a different seed each time.
Declare and initialise rand outside the loop, with or without an explicit seed.
Use Math.random().
So in your code you set up a seed for your Random and you create new Random object every loop iteration so it just returns same number every time. If you use seed the documentation of Random class says :
If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.
In your case you can get rid of seed value from your constructor or move Random class object creation outside of the loop :
public static void main(String[] args) {
int[] arr = new int[2];
Random rand = new Random();
for(int i = 0; i <= 1; i++) {
int zahlen = rand.nextInt(6) + 1;
arr[i] = zahlen;
}
System.out.println(Arrays.toString(arr));
}
Here I moved creation of Random instance outside of the loop so only one object is created and I am not passing seed to the constructor. I could pass the seed but in this case it is not needed as I don't need to create more instances of Random and I dont need them to generate same results.
*
int[] wuerfel = new int[2];
//It will loop once while assigning a random number to the array
Random rand = new Random();
for(int i = 0; i <= 1; i++) {
int zahlen = rand.nextInt(6) + 1;
wuerfel[i] = zahlen;
}
System.out.println(Arrays.toString(wuerfel));
* try this one create Random object with passing parameter

Random numbers mean and standard deviation Java

So I have a program that has a 50 number long list with random numbers between 1 and 50. I need to find the mean and the standard deviation of said list. I'm having trouble with adding all the random numbers together.
This is the code I have so far:
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i < 51; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
for (int i = 0; i < 50; i++) { // Set to 50 as max number just for example
}
}
}
As #azro mentioned you are not using random ints from 1 to 50. You are just shuffling the numbers from 1 to 50 in the list.
If you really want a list of Random numbers from 1-50 then you can use Random::nextInt to get a random number like this:
ArrayList<Integer> list = new ArrayList<>();
Random r = new Random();
for (int i = 1; i <= 50; i++) {
list.add(r.nextInt(50) + 1);
}
or even easier using Random::ints in Java 8:
List<Integer> list = new Random().ints(50,1,51) // generate 50 random numbers from 1 inclusive to 51 exclusive
.boxed() // box each int
.collect(Collectors.toList()); // get a list with the numbers
A couple issues I see with the code. It sounds like you're attempting to add 50 random numbers to a list. What your above code actually does is add the numbers 1:50 (inclusive) to a list, and then randomly shuffle the order of those numbers in the list. You will still have non-random numbers (all the numbers 1:50 will still be in the list, just in a random order).
What you should be doing is randomly generating the numbers and then adding them to the list. For example:
Random rand = new Random();
int upperBound = 50;
int sum = 0;
for (int i = 0; i < 50; i++) {
int randInt = rand.nextInt(upperBound) + 1;
list.add(randInt);
sum += randInt;
}
I'm not sure about naming conventions. Does mean mean average? Sum divided by count?
Random random = new Random ();
int[] ia = IntStream.generate (()-> random.nextInt (50)).limit (50).toArray();
// ia wieder zu Stream machen?
IntStream is = IntStream.of (ia);
double avg = is.summaryStatistics().getAverage()
// indeed, summaryStatistics exists.
// Expression value is:
// IntSummaryStatistics{count=50, sum=1159, min=0, average=23,180000, max=47}
// but no stddev
double stddev (int[] l, double avg) {
double sum = 0.0;
for (double d : l) {
double xd = d - avg;
sum += xd * xd;
}
return sum;
}
double std = stddev (ia, avg);
A different way, working with mapToDouble:
is = IntStream.of (ia);
double qabw (int i, double avg) {
double abw = 1.0 * i - avg;
double q = abw * abw;
return q;
}
DoubleStream ds = is.mapToDouble(i-> qabw (i, avg));
double qsum ds.sum ();
I'm pretty fresh to the stream thing. It should be possible to feed the function stddev, which is, btw., incomplete, into a stream.
On the other side, by summaryStatistics().getAverage(), the stream is consumed and gone. So I have to store the values in an Array, for example, first, and then recreate a stream from the array.
Pretty complicated.
However, I think we need a Math.sqrt in the end for a correct value, and/or a division by count, so the mathematical part needs surely correction.
For improvement on working with streams: you're welcome.

Simple deterministic method to generate an array of random numbers?

I am looking for a simple method to populate a large int[] testArray with data. Method should accept a single parameter to generate a deterministic sequence of integers, but look like noise at a first glance.
Something like this comes to mind, but data might have patterns.
public int[] populate(int arraySize, int somePrime){
int[] testArray = new int[arraySize];
int offset = -100000;
long fib = 0; long fibm1 = 1; long fibm2 = 1;
//...
for(int i = offset; i< testArray.length; i++){
fib= fibm1+ fibm2;
fibm2= fibm1;
fibm1= fib;
if(i >= 0){ testArray[i] = (int) fib%somePrime; }
}
return testArray[i];
}
What would be a better method?
You can do this by initializing a random number generator with a fixed seed. The sequence it generates will look random to someone who doesn't know the seed, but you will be able to reconstruct the sequence by using the same seed again.
For example:
Random r = new Random(mySeed);
int[] testArray = new int[arraySize];
for(int i=0; i<arraySize; i++) {
testArray[i] = r.nextInt();
}
Update: This method is susceptible to someone guessing your seed by trial and error, especially if it's a small number or otherwise predictable. You could also store a secret, fixed seed and combine the two into a longer seed. But you should be careful about how you do this, as there are pitfalls. See Deterministically combine more than one source of entropy.
You could use SecureRandom. Then you could use your number to generate a seed:
int seed = 1234;
Random rand = new SecureRandom(SecureRandom.getSeed(seed));
int number = rand.nextInt();

Java - Help writing function to return array (with Junit test)

I can really use a hand from someone with more experience to learn about writing a function to create and return an integer array. Any guidance is appreciated, I am extremely confused with the next step I should take in order to pass the Junit test described below.
It seems that I should be able to gain quite a bit of insight from the test, however this is my first exposure to Junit tests. Can anyone help me interpret this unit test snippet?
The Goal
Write a function that creates and returns an array of integers:
The values should be from 0 to 100000.
Use Math.random() to generate random numbers from 0.0 to 1.0.
Must pass Junit test (see snippet below)
NOTE: I will eventually write functions to bubble sort and select sort. I will also report timing on vectors (of random integers) of size 1000 to 10000, stepping by 1000, how long it takes the bubble and selection sort functions.
Junit test for generateNumbers
#org.junit.Test
public void generateNumbers() {
for (int i = 1; i < 10000; i += 10) {
int[] newArray = SortingDriver.generateNumbers(i);
Assert.assertEquals(i, newArray.length);
}
}
Current Code (SortingDriver)
public static int[] generateNumbers(int howMany) {
// TODO: Create and return array of integers
// TODO: The values should be from 0 to 100000
// TODO: Use Math.random() to generate random numbers from 0.0 to 1.0
int size = 100000;
// Create array of integers
int[] sortMe = new int[size];
// Utilize random function to create a random number in between 0 and 100,000
int rand = (int)(Math.random() * (size + 1));
// For loop?
}
public static int[] generateNumbers(int howMany) {
int size = howMany;
// Create array of integers and instantiate variable to determine random number
int[] sortMe = new int[size];
int rand = (int)(Math.random() * 100000 + 1);
// For loop to generate random number
for (int i = 1; i < sortMe.length; i += 10) {
// Utilize random function to create a random number in array between 0 and 100,000
sortMe[i] = rand;
}
return sortMe;
}

Categories