How do I make a large number of random arrays? - java

I need to make an array that has 8000 random integers between values 0 - 65535 for a hash table assignment, I understand the math.random function but how do I get random numbers for such a large range of numbers? Thanks!

If you're in Java 8, you can write
int[] array = new Random().ints(0, 65536).limit(8000).toArray();
otherwise you'd just write something like
int[] array = new int[8000];
Random rng = new Random();
for (int i = 0; i < 8000; i++) {
array[i] = rng.nextInt(65536);
}

Related

How to generate a random array for each iteration of a loop in java

I'm trying to create a large number of arrays with random integers of similar size for each iteration of a loop. e.g 500 iterations.(So for each loop, a new array is created) Then sort these 500 arrays using my implemented sort methods. I'm pretty new to java and I don't even know where to start.
I have a random array method which inputs random variables into an array to help with inputting the variables
Thanks.
See this code snippet helps you or not. Let me know.
private int[] getRandomArray(int size){
int[] arr = new int[size];
for(int i=0; i<arr.length; i++){
//if you don't any bound
int rand = ThreadLocalRandom.current().nextInt();
//if you need any bound. for example following will return int value in between 10 and 100
//int rand = ThreadLocalRandom.current().nextInt(10, 100);
arr[i] = rand;
}
return arr;
}

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

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();

random.nextDouble creates the same sequence in a for block

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

Generating a random index for an array

I know this for normal integers, but is there for such a thing as indices?
Random dice = new Random();
int n = dice.nextInt(6);
System.out.println(n);
What do you mean? Array indices are normal numbers, so you can easily do
String names[] = { "One", "Two", "Three", "Four", "Five", "Six" };
Random Dice = new Random();
int n = Dice.nextInt(6);
System.out.println(names[n]);
Or do you mean a random Iterator class? Google is your friend here, this is the first hit I get.
To generate a random index for someArray you do
int index = new Random().nextInt(someArray.length);
nextInt(n) returns a number between 0 (inclusive) and n (exclusive) which is why someArray.length is given as argument.
Another solution would be:
int randomElement = yourArray[Math.random()*yourArray.length];
Math.random() generates a random number between 0 and 1. If you multiply that number by the length of your array, you will get an random index for the array.
For example: If Math.random() generated .2 and your array had a length of 10, you would get an index of 2.
Here is another possibility that worked for me in React js if you want to return the value of that index in an array.
const myArray = [1,2,5,7,6,87,45,34,23,12]
const rand = myArray[Math.floor(Math.random() * myArray.length)];
console.log('value of the index', rand);
console.log('index in the array',myArray.indexOf(rand));

Categories