Generating random numbers array in Java - java

I'm working on a code that should generate an array with a length of 100 and then separates numbers form the array to:
Numbers that are multiples of 4.
Numbers that are not multiples of 4.
Below is my code, however, I'm getting a weird output (lots of zeros). How can I identify the problem?
public class Assignment8 {
public static void main(String[] args) {
// Defined array to hold the values
int[] randomValueArray = new int[100];
int[] mod4ValueArray = new int[100];
int[] nonMod4ValueArray = new int[100];
// Initiate the randomValue Array
for (int i = 0; i < 100; ++i) {
// Generate a random number from the range 1 to 100
int randomValue = (int) (Math.random() * 100 + 1);
randomValueArray[i] = randomValue;
}
// Pass the array to the class method to separate mod4
// value and non mod4 value from the randomized array
mod4ValueArray = isMod4(randomValueArray);
nonMod4ValueArray = isNonMod4(randomValueArray);
// Print out the two result arrays
System.out.println("Randomly generated numbers that are multiples of four: ");
for (int i = 0; i < mod4ValueArray.length; ++i) {
System.out.println(mod4ValueArray[i]);
}
System.out.println("Randomly generated numbers that are not multiples of four: ");
for (int i = 0; i < nonMod4ValueArray.length; ++i) {
System.out.println(nonMod4ValueArray[i]);
}
}
// Mod4 Checker Method
public static int[] isMod4(int[] array) {
int[] resultArray = new int[array.length];
for (int i = 0; i < array.length; ++i) {
int itemValue = array[i];
if ((array[i] % 4) == 0) {
resultArray[i] = itemValue;
}
}
return resultArray;
}
// Non Mod 4 Checker Method
public static int[] isNonMod4(int[] array) {
int[] resultArray = new int[array.length];
for (int i = 0; i < array.length; ++i) {
int itemValue = array[i];
if ((itemValue % 4) != 0) {
resultArray[i] = itemValue;
}
}
return resultArray;
}
}

Try this.
int[] randomValueArray = new Random().ints(100, 1, 101).toArray();
int[] mod4ValueArray = IntStream.of(randomValueArray).filter(i -> i % 4 == 0).toArray();
int[] nonMod4ValueArray = IntStream.of(randomValueArray).filter(i -> i % 4 != 0).toArray();

try this:
new Random().ints(100, 1, 100).filter(n -> n % 4 == 0).toArray();
new Random().ints(100, 1, 100).filter(n -> n % 4 != 0).toArray();

Java 8 Stream-esque solution:
Map<Boolean, int[]> map = new Random().ints(10, 1, 100)
.mapToObj(i -> i)
.collect(partitioningBy(i -> i % 4 == 0, collectingAndThen(toList(), list -> list.stream()
.mapToInt(i -> i)
.toArray()
)));
This pulls 100 random integers from 1 to 100, then boxes all ints to Integers, then partitions by whether the number is dividable by 4. Then, the resulting List<Integer> is converted to an int[].
However, I think a plain old for loop is better. The only difficulty you have, is that you don't know how large each array will get. So at the end, you'll need to resize the arrays.
int[] fourMods = new int[100];
int[] nonFourMods = new int[100];
int fourModsCardinality = 0;
int nonFourModsCardinality = 0;
Random random = new Random();
for (int i = 0; i < 100; i++) {
int num = random.nextInt(100) + 1;
if (num % 4 == 0) {
fourMods[fourModsCardinality] = num;
fourModsCardinality++;
}
else {
nonFourMods[fourModsCardinality] = num;
nonFourModsCardinality++;
}
}

Related

How to count number of occurrences in a random array?

I have some homework where. I have to write a simple program where 1000000 randoms between 1-100 are generated and stored in an array. After the program has to print out the number of occurrences of 25, 50 and 100. I've been trying for loops but no luck. Till now I have this:
package randomnumbers;
import java.util.Random;
public class random {
public static void main(String[] args) {
Random r = new Random();
int number[] = new int[1000000];
for (int count = 0; count < number.length; count++) {
number[count] = 1 + r.nextInt(100);
}
}
}
public static void main(String[] args) {
Random r = new Random();
int low = 1;
int high = 101;
int number[] = new int[1000000];
int count25 = 0;
int count50 = 0;
int count100 = 0;
for (int i = 0; i < number.length; i++) {
int num = r.nextInt(high - low) + low;
if (num == 25) {
count25++;
} else if (num == 50) {
count50++;
} else if (num == 100) {
count100++;
}
number[i] = num;
}
System.out.println(count25);
System.out.println(count50);
System.out.println(count100);
}
Here r.nextInt(high - low) + low generates random value between lower bound(inclusive) and upper bound(exclusive). Hence I have used upper bound as 101.
There are 3 different counters which would increment by one if its value matches the required value(25, 50 and 100).
After the loop is completed the value of the counter can be printed.
You can use IntStream.count() method for this purpose. Your code might look something like this:
public static void main(String[] args) {
// generate array of 1,000,000 elements
int[] arr = IntStream.range(0, 1000000)
// random value from 1 to 100
.map(i -> (int) (1 + Math.random() * 100))
.toArray();
// test output
System.out.println(countOf(arr, 0)); // 0
System.out.println(countOf(arr, 1)); // 10137
System.out.println(countOf(arr, 25)); // 10026
System.out.println(countOf(arr, 50)); // 10103
System.out.println(countOf(arr, 100)); // 10100
System.out.println(countOf(null,100)); // 0
System.out.println(countOf(arr, 101)); // 0
}
private static long countOf(int[] arr, int value) {
if (arr == null)
return 0;
else
return Arrays.stream(arr).filter(i -> i == value).count();
}
See also:
• How to find duplicate elements in array in effective way?
• How to get elements of an array that is not null?

Generate even numbers in an int array?

For my program I need to make a 10 element array and the goal is to print out the even numbers from 2 to 20. I have to do this by adding 2 to the beginning element. This is what I have so far. I think I should use a loop as shown but I don't know how to go about adding 2 and printing that out. Thanks!
int[] array = new int[10];
for(int counter=0; counter<array.length; counter++) {
}
if you want program print even number between 2 & 20
for(int i=2;i<=20;i++)
{
if(i%2 == 0)
print(i)
}
Start at 2 and increment by 2 to get the even numbers:
int[] array = new int[10]
for(int counter=2; counter <= 20; counter += 2) {
array[counter/2 - 1] = counter
}
or
int[] array = new int[10]
for(int i=0; i <= 10; i++) {
array[i] = i*2 + 2
}
this is also an option
int i, value;
int nums[] = new int[10];
for (i = 0, value = 2; i < nums.length; value = value + 2, i = i + 1) {
nums[i] = value;
}
for (i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
int[] array = new int[10];
for (int i = 0, j = 1; i < array.length && j <= 20; j++) {
if (j % 2 == 0) {
array[i] = j;
i++;
}
}
System.out.println(Arrays.toString(array));
Java 8: int[] array = IntStream.range(1, 11).map(x -> x * 2).toArray();
Or, to just print: IntStream.range(1, 11).map(x -> x * 2).forEach(System.out::println);
From java-9 you can use IntStream.iterate to create int array
int[] arr= IntStream.iterate(2, i->i<=20, i->i+2).toArray();
for Integer array you can use Stream.iterate
Integer[] ary = Stream.iterate(2, i->i<=20, i->i+2).toArray(Integer[]::new);
Dear Alexis,
Below is an example using do-while.
you can simply define a range of expected even numbers using minVal and maxVal.
Program will execute and return list of ordered even numbers for given range. Assuming input values are correct even numbers. You can improve to apply validations.
public class EvenNumberGenerator {
static int minVal=2; //enter valid min value even number
static int maxVal = 20; //enter valid max value even number
public static void main(String[] args) {
List<Integer> evenNumbers = new ArrayList();
do {
if(minVal % 2 == 0) {
evenNumbers.add(minVal);
}
minVal++;
} while (!evenNumbers.contains(maxVal));
System.out.println(evenNumbers);
// evenNumbers.toArray(); in case you need an array
}
}
OUTPUT
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Hope it helps!
Using your code as a start, this will work:
int[] array = new int[10];
for(int counter=0; counter<array.length; counter++) {
array[counter] = (counter + 1) * 2;
}
System.out.println(Arrays.toString(array));
The following will also work with Eclipse Collections:
int[] array = IntInterval.evensFromTo(2, 20).toArray();
System.out.println(Arrays.toString(array));
Note: I am a committer for Eclipse Collections

Duplicate number check doesn't always work

I have a function getNormalList() that must return a list with 3 random integers 0-5, not all the same. It's not working like I want it to work. Sometimes, despite the check, it outputs the same 3 numbers.
public class SpinResultGenerator {
public ArrayList<Integer> getNormalList() {
ArrayList<Integer> integerList = new ArrayList<Integer>();
Random r = new Random();
int Low = 0;
int High = 6;
for (int i = 0; i < 3; i++) {
int number = r.nextInt(High - Low) + Low;
integerList.add(number);
}
if (integerList.get(0) == integerList.get(1) && integerList.get(0) == integerList.get(2)
&& integerList.get(1) == integerList.get(2)) {
integerList.clear();
for (int i = 0; i < 3; i++) {
int number = r.nextInt(High - Low) + Low;
integerList.add(number);
}
}
return integerList;
}
public ArrayList<Integer> getJackpotList() {
ArrayList<Integer> integerList = new ArrayList<Integer>();
integerList.add(5);
integerList.add(5);
integerList.add(5);
return integerList;
}
}
If the result is, for example, [4,4,4], the for loop generates new numbers. Yet it is still able to output 3 of the same integers. Why?
You need a nested loop. Your for loop should repeat until 3 acceptable numbers are found. I used an array to make the code more compact, but the same can be done with ArrayList.
public List<Integer> getNormalList() {
Random r = new Random();
int[] arr = new int[3]; // initialized to 0s by default
int Low = 0;
int High = 6;
while (arr[0] == arr[1] && arr[1] == arr[2]) { // will repeat as long as the 3 number as
// all equal
for (int i = 0; i < arr.length; i++) {
arr[i] = r.nextInt(High - Low) + Low;
}
}
return Arrays.asList(arr);
}
Your current code fails because if it generates a list of duplicates, it just clears it and generates a new list, without checking if the new list contains duplicates. Here's my suggested alternate solution:
do {
List<Integer> result = ThreadLocalRandom.current().ints(0, 6).limit(3).boxed().collect(toList())
} while (result.get(0) == result.get(1) && result.get(0) == result.get(2))
return result;

How to Avoid duplication in String[] in Java? [duplicate]

I want to create a set of random numbers without duplicates in Java.
For example I have an array to store 10,000 random integers from 0 to 9999.
Here is what I have so far:
import java.util.Random;
public class Sort{
public static void main(String[] args){
int[] nums = new int[10000];
Random randomGenerator = new Random();
for (int i = 0; i < nums.length; ++i){
nums[i] = randomGenerator.nextInt(10000);
}
}
}
But the above code creates duplicates. How can I make sure the random numbers do not repeat?
Integer[] arr = {...};
Collections.shuffle(Arrays.asList(arr));
For example:
public static void main(String[] args) {
Integer[] arr = new Integer[1000];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
Collections.shuffle(Arrays.asList(arr));
System.out.println(Arrays.toString(arr));
}
A simple algorithm that gives you random numbers without duplicates can be found in the book Programming Pearls p. 127.
Attention: The resulting array contains the numbers in order! If you want them in random order, you have to shuffle the array, either with Fisher–Yates shuffle or by using a List and call Collections.shuffle().
The benefit of this algorithm is that you do not need to create an array with all the possible numbers and the runtime complexity is still linear O(n).
public static int[] sampleRandomNumbersWithoutRepetition(int start, int end, int count) {
Random rng = new Random();
int[] result = new int[count];
int cur = 0;
int remaining = end - start;
for (int i = start; i < end && count > 0; i++) {
double probability = rng.nextDouble();
if (probability < ((double) count) / (double) remaining) {
count--;
result[cur++] = i;
}
remaining--;
}
return result;
}
In Java 8, if you want to have a list of non-repeating N random integers in range (a, b), where b is exclusive, you can use something like this:
Random random = new Random();
List<Integer> randomNumbers = random.ints(a, b).distinct().limit(N).boxed().collect(Collectors.toList());
Achintya Jha has the right idea here. Instead of thinking about how to remove duplicates, you remove the ability for duplicates to be created in the first place.
If you want to stick with an array of ints and want to randomize their order (manually, which is quite simple) follow these steps.
create array of size n.
loop through and initialize each value at index i to the value i (or i+1 if you wish to have the numbers 1 to n rather than 0 to n-1).
finally, loop through the array again swapping each value for a value at a random index.
Your code could be modified to look like this:
import java.util.Random;
public class Sort
{
// use a constant rather than having the "magic number" 10000 scattered about
public static final int N = 10000;
public static void main(String[] args)
{
//array to store N random integers (0 - N-1)
int[] nums = new int[N];
// initialize each value at index i to the value i
for (int i = 0; i < nums.length; ++i)
{
nums[i] = i;
}
Random randomGenerator = new Random();
int randomIndex; // the randomly selected index each time through the loop
int randomValue; // the value at nums[randomIndex] each time through the loop
// randomize order of values
for(int i = 0; i < nums.length; ++i)
{
// select a random index
randomIndex = randomGenerator.nextInt(nums.length);
// swap values
randomValue = nums[randomIndex];
nums[randomIndex] = nums[i];
nums[i] = randomValue;
}
}
}
And if I were you I would likely break each of these blocks into separate, smaller methods rather than having one large main method.
Hope this helps.
If you need generate numbers with intervals, it can be just like that:
Integer[] arr = new Integer[((int) (Math.random() * (16 - 30) + 30))];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
Collections.shuffle(Arrays.asList(arr));
System.out.println(Arrays.toString(arr));`
The result:
[1, 10, 2, 4, 9, 8, 7, 13, 18, 17, 5, 21, 12, 16, 23, 20, 6, 0, 22, 14, 24, 15, 3, 11, 19]
Note:
If you need that the zero does not leave you could put an "if"
How about this?
LinkedHashSet<Integer> test = new LinkedHashSet<Integer>();
Random random = new Random();
do{
test.add(random.nextInt(1000) + 1);
}while(test.size() != 1000);
The user can then iterate through the Set using a for loop.
public class RandomNum {
public static void main(String[] args) {
Random rn = new Random();
HashSet<Integer> hSet = new HashSet<>();
while(hSet.size() != 1000) {
hSet.add(rn.nextInt(1000));
}
System.out.println(hSet);
}
}
If you're using JAVA 8 or more than use stream functionality following way,
Stream.generate(() -> (new Random()).nextInt(10000)).distinct().limit(10000);
Here we Go!
public static int getRandomInt(int lower, int upper) {
if(lower > upper) return 0;
if(lower == upper) return lower;
int difference = upper - lower;
int start = getRandomInt();
//nonneg int in the range 0..difference - 1
start = Math.abs(start) % (difference+1);
start += lower;
return start;
}
public static void main(String[] args){
List<Integer> a= new ArrayList();
int i;
int c=0;
for(;;) {
c++;
i= getRandomInt(100, 500000);
if(!(a.contains(i))) {
a.add(i);
if (c == 10000) break;
System.out.println(i);
}
}
for(int rand : a) {
System.out.println(rand);
}
}
Get Random number Returns a random integer x satisfying lower <= x <= upper. If lower > upper, returns 0. #param lower #param upper #return
In the main method I created list then i check if the random number exist on the list if it doesn't exist i will add the random number to the list
It is very slow but straight forward.
A simple stream solution:
new Random().ints(0, 10000)
.distinct()
.limit(10000)
.forEach(System.out::println);
public class Randoms {
static int z, a = 1111, b = 9999, r;
public static void main(String ... args[])
{
rand();
}
public static void rand() {
Random ran = new Random();
for (int i = 1; i == 1; i++) {
z = ran.nextInt(b - a + 1) + a;
System.out.println(z);
randcheck();
}
}
private static void randcheck() {
for (int i = 3; i >= 0; i--) {
if (z != 0) {
r = z % 10;
arr[i] = r;
z = z / 10;
}
}
for (int i = 0; i <= 3; i++) {
for (int j = i + 1; j <= 3; j++) {
if (arr[i] == arr[j]) {
rand();
}
}
}
}
}
HashSet<Integer>hashSet=new HashSet<>();
Random random = new Random();
//now add random number to this set
while(true)
{
hashSet.add(random.nextInt(1000));
if(hashSet.size()==1000)
break;
}

Array method that returns a new array where every number is replicated by “itself” # of times

I am trying to write a method in Java that receives an array and returns a new array where each number is printed that number of times. Here is an example input and output: "1 2 3 0 4 3" ---> "1 2 2 3 3 3 4 4 4 4 3 3 3". I am stuck and my program will not compile. Does anyone see where I am going wrong?
public static int [] multiplicity(int [] nums) {
for (int i = 0 ; i < nums.length ; i++) {
int size = nums.length + 1;
int newNums[] = new int [size];
for (int j = 0 ; j < nums.length ; j++) {
int value = nums[j];
for (int v = 0 ; v < value ; v++) {
newNums[j + v] = value;
}
}
}
return newNums;
}
Your current code does not size your new array correctly, you could fix your compiler errors easily enough like
int size=nums.length+1;
int newNums [] = new int [size];
for (int i=0; i<nums.length; i++)
{
// int size=nums.length+1;
// int newNums [] = new int [size];
But that clearly won't allow you to populate all of your values. Instead (assuming you can't use a dynamic data-type like a Collection), you'll need to iterate the array once to get the final count of elements and then populate your array. Something like,
public static int[] multiplicity(int[] nums) {
// first pass
int count = 0;
for (int num : nums) {
for (int i = 0; i < num; i++) {
count++;
}
}
int[] ret = new int[count];
count = 0;
// second pass
for (int num : nums) {
for (int i = 0; i < num; i++) {
ret[count++] = num;
}
}
return ret;
}
Then you could test it like,
public static void main(String arg[]) {
int[] in = { 1, 2, 3, 0, 4, 3 };
int[] out = multiplicity(in);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < out.length; i++) {
if (i != 0) {
sb.append(' ');
}
sb.append(out[i]);
}
String expected = "1 2 2 3 3 3 4 4 4 4 3 3 3";
System.out.println(expected.equals(sb.toString()));
}
Output is
true
Once you initialise your int[] newNums, you can't dynamically resize it. Initialising it again will discard the previous array.
Here's another way to solve the problem:
public static int [] multiplicity (int [ ] nums)
{
// create a list to contain the output
List<Integer> newNums = new ArrayList<Integer>();
// for each incoming int
if(nums != null) {
for (final int i : nums)
{
// repeat adding the value
for(int j = 0; j < i; j++) {
newNums.add(i);
}
}
}
// now copy from the List<Integer> to the result int[]
int[] result = new int[newNums.size()];
for(int i=0; i < newNums.size(); i++) {
result[i] = newNums.get(i);
}
// return the result
return result;
}
You can't know the new array size until you explore the whole input array.
So you can
Explore the whole array and compute the lengh, then, re-explore the input array and fill the new. You need only 1 memory allocation (only 1 new int[])
Create a vector and fill it. Then use the .toarray method
Exemple to fill the array (check he had the right size)
int k = 0
for(int i: nums) {
for(int j = 0; j < i; j++) {
newArray[k] = i;
k++;
}
}

Categories