This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 3 years ago.
I am having trouble placing the random generator in the array, how can I get #20 random numbers from 0-9 in the array? Then you count the occurrences of those numbers.
import java.util.Random;
public class CountDigits {
public static void main(String[] args) {
Random digit = new Random();
int Random[] = new int [20];
int Digits[] = {0,1,2,3,4,5,6,7,8,9};
int Count [] = new int [10];
for ( int i = 0; i < Digits.length; i++) {
for( int j = 0; j < Random.length; j++) {
if ( Digits [i] == Random [j] )
Count[i]++;
}
}
for ( int i = 0; i < Count.length; i++) {
if ( Count[i] == 1)
System.out.printf(" %d occurs 1 time " , Digits[i] );
else
System.out.printf("%d occurs %d times" , Digits[i], Count[i]);
}
result so far::
0 occurs 20 times1 occurs 0 times2 occurs 0 times3 occurs 0 times4 occurs 0 times5 occurs 0 times6 occurs 0 times7 occurs 0 times8 occurs 0 times9 occurs 0 times
You need to actually get a Random number, and get within the range. The Java Random will provide the necessary capability, and includes a .nextInt(int bound) that returns between 0 and bound:
public int nextInt(int bound)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
So something like:
Random rnd = new Random();
int num = rnd.nextInt(10); // returns between 0 and 9
Given that, you have two other questions:
- Generating 20 numbers
- Counting
Knowing that the number of possible entries is between 0 and 9, it is easy to use an array to hold the counts.
int[] counts = new int[10]; // holds between 0 and 9
for (int i = 0; i < 20; ++i) {
int num = rnd.nextInt(10);
counts[num]++;
}
The output of the counts array will give the count of the number of times a given number between 0 and 9 was randomly generated.
See an example here
You forgot to assign random numbers to the array elements.this answer to see how random numbers are generated.
You need to call Random object's nextInt(an integer) method. If you give 25 to it, it will return a random integer between 0-24 inclusive.
Example Usage:
Random rand = new Random();
int random_int = rand.nextInt(50); // --------> Random integer 0-49
And the full code:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random digit = new Random();
int Random[] = new int[20];
for (int x=0;x<20;x++) {
Random[x] = digit.nextInt(10);
}
int Digits[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int Count[] = new int[10];
for (int i = 0; i < Digits.length; i++) {
for (int j = 0; j < Random.length; j++) {
if (Digits[i] == Random[j])
Count[i]++;
}
}
for (int i = 0; i < Count.length; i++) {
if (Count[i] == 1)
System.out.printf(" %d occurs 1 time ", Digits[i]);
else
System.out.printf("%d occurs %d times", Digits[i], Count[i]);
}
}
}
Outputs :
0 occurs 2 times1 occurs 2 times 2 occurs 1 time 3 occurs 3 times4 occurs 6 times 5 occurs 1 time 6 occurs 2 times7 occurs 0 times 8 occurs 1 time 9 occurs 2 times
You can print the random numbers like this
for (int x=0;x<20;x++) {
System.out.println(Random[x]);
}
You can try this:
Create an array of int with length 20, then use a simple for loop where you are gonna generate a random number and them put it inside the array
int[] random = new int[20];
for(int i=0;i<20;i++){
int r = Math.floor(Math.random()*9+1);
random[i]=r;
}
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am still new to Java, this question like: An ISBN-10 (International Standard Book Number)
consists of 10 digits: d1d2d3d4d5d6d7d8d9d10. The last digit, d10, is a checksum,
which is calculated from the other nine digits using the following formula:
(d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 +
d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9) % 11
If the checksum is 10, the last digit is denoted as X according to the ISBN-10
convention. Write a program that prompts the user to enter the first 9 digits and
displays the 10-digit ISBN (including leading zeros). Your program should read
the input as an integer.
See my code below:
It is working but the result is not correct!
public static Scanner input;
public static void main(String[] args)
{
input = new Scanner(System.in);
System.out.print("Enter first 9 digit numbers: ");
int[] arr = new int[9];
int checkSum = 0;
for (int i = 0 ; i < arr.length; i++)
{
arr[i] = input.nextInt();
checkSum = (arr[i] * i) % 11;
}
System.out.print("The ISBN-10 Number is " );
for(int j = 0 ; j < arr.length; j++)
{
System.out.print(arr[j]);
}
if(checkSum == 10)
{
System.out.println("x");
}
else
{
System.out.println(checkSum);
}
I just want to use loop, make my method works. , i know how to use method without loop.
well. for JAVA
an array index start from 0. and Max index is length - 1.
if the index is not within this range. an arrayoutofbounds exception will be thrown
The problem is not that you are doing int i = 1 instead of int i = 0. The problem is that you changed i < arr.length; to i <= arr.length;. Since arr.length is 9, your code is trying to refer to arr[9] but arr only has elements arr[0] through arr[8].
First, review how we use arrays...
int[] I = new int[3];
The above creates an array with 3 spots in it. After instantiating the array, each element is based off of a 0-index. You only have I[0], I[1], and I[2] available (note this is three numbers) and trying to access I[3] will throw the error that you encountered in your program above: ArrayIndexOutOfBoundsException.
That being said, your loop is trying to access arr[9]. The highest index you have in the array is arr[8], because despite the array having 9 elements in it, it's 0-indexed.
Assuming you MUST have i starting from 1 for a homework assignment or something, change your code to:
public static Scanner input;
public static void main(String[] args)
{
input = new Scanner(System.in);
System.out.print("Enter first 9 digit numbers: ");
int[] arr = new int[9];
int checkSum = 0;
for (int i = 1 ; i <= arr.length; i++)
{
arr[i-1] = input.nextInt();
checkSum = (arr[i-1] * i) % 11;
}
System.out.print("The ISBN-10 Number is " );
for(int j = 1 ; j <= arr.length; j++)
{
System.out.print(arr[j-1]);
}
if(checkSum == 10)
{
System.out.println("x");
}
else
{
System.out.println(checkSum);
}
int[] arr = new int[9];
This means the array has 9 slots. And the numbering of those slots starts from 0. Thus,
arr[0] is the first slot
arr[1] is the second slot
The last slot would be arr[8]. But in the following code you are iterating till i is equal to 9 which does not exist.
for (int i = 1 ; i <= arr.length; i++)
{
arr[i] = input.nextInt();
checkSum = (arr[i] * (i+1)) % 11;
}
This results in the ArrayIndexOutOfBoundsException. Change for (int i = 1 ; i <= arr.length; i++) to for (int i = 0 ; i < arr.length; i++)
I'm trying to make it so the random generator doesn't produce the same number in the array. I also don't know how to find the missing number. I tried the if statement, and it works, but it repeats.
The question problem "find the missing number in an array. The array consists of numbers from 1 to 10 in random sequence. One of the numbers in the array is absent and you must find it. Use one loop. An example {5,6,9,4,1,2,8,3,10} – the result will be: 7
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [10];
Random rand = new Random();
int numArr = 1;
for (int i = 1; i < 9; i++)
{
int n = rand.nextInt(10) + 1;
numbers[i] = n;
if (numbers[i] == numArr)
numArr++;
else
System.out.println("The missing num is " +numArr);
}
for(int val : numbers)
{
System.out.println("The next value is " +
val);
}
}
}
Assumption:
Numbers are unique
Only one entry is missing
number ranges from [1, 10] inclusive.
Solution
return 55 - Arrays.stream(yourArr).sum();
This is with O(n) runtime and O(1) space complexity.
If we break assumptions.
You will need O(N) space to figure out which entries are missing. To hold the marker either you can use List or BitSet or 2 bytes and manage it by hand. N is here the random number generation width.
There seems to be no mention on using a temporary data structure.
You can either sort the array and find the missing number, OR use a temporary sorted data structure.
You are conflating two things: the generator algorithm for a problem case and the solution to the problem itself. You shouldn't be interested in how the "random array" is generated at all (unless you want to test your solution). What you certainly shouldn't do is try to write the code that solves the problem in the method that generates the sample array.
If you want a randomly sorted list, Collections.shuffle will handle that for you. If you want a list without a single element, just generate a list of all elements 1..n and then remove the randomly selected number (then shuffle). So much for the generator. As for the solution, there are many methods to do it, someone already suggested using the sum, that's a perfectly valid solution.
It seems you are looking for this code.
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [9];
Random rand = new Random();
int numArr = 1;
numbers[0] = rand.nextInt(10) + 1;
for (int i = 1; i < 9; i++)
{
int n = rand.nextInt(10) + 1;
numbers[i] = n;
int x =0;
while(x<i){
if(numbers[x] == n){
i = i-1;
break;
}
x++;
}
}
int sum = 0;
for (int val : numbers) {
sum = sum + val;
System.out.println("The next value is " +
val);
}
System.out.println("Missing number is " + (55 - sum));
}
}
Output is -
The next value is 6
The next value is 2
The next value is 8
The next value is 1
The next value is 4
The next value is 3
The next value is 9
The next value is 10
The next value is 7
Missing number is 5
I am generating 9 Numbers between(1 to 10) randomly and then printing which number is missing among them.
You have two options:
The way I did it in the code below: setting the random array without repeating the same number. And then a for loop from 1 to 10 and check if that number exist in the array.
You know that 1 + 2 + 3 + 2 + 3 + 4 + 5 + 6 + 8 + 9 + 10 = 55. So if you get the sum of all ints in the array you will have 55 - (the missing number). So now the missing number = 55 - sum.
This is the code I did (first method):
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [9];
Random rand = new Random();
for (int i = 0; i <9; i++)
{
//setting random numbers in array without repeating
numbers[i] = checkForANumber(rand, numbers, i);
}
//print all nums
for(int val: numbers) System.out.println("The next value is " +
val);
for (int i = 1; i <= 10; i++)
{
boolean exist = false;
for(int val : numbers)
{
if(val == i){
exist = true;
}
}
if (!exist) System.out.println("The missing number is " + i);
}
}
private static int checkForANumber(Random rand, int[] numbers, int i){
int n = rand.nextInt(10) + 1;
boolean NumAlreadyExist = false;
for(int j = 0; j < i; j++)
{
if(numbers[j] == n){
NumAlreadyExist = true;
}
}
if(NumAlreadyExist) return checkForANumber(rand, numbers, i);
else return n;
}
}
Output:
The next value is 9
The next value is 3
The next value is 8
The next value is 6
The next value is 7
The next value is 10
The next value is 4
The next value is 2
The next value is 1
The missing number is 5
I have to write a method that takes an array of 30 random integers and returns a new histogram array. The histogram should contain 11 elements with the following contents:
element 0 -- number of elements in the array that are <= 0
1 -- number of elements in the array that are == 1
2 -- number of elements in the array that are == 2
...
9 -- number of elements in the array that are == 9
10 -- number of elements in the array that are >= 10
I'm not sure how to make a histogram using random numbers. I have a method for making a histogram, and a method for making random numbers, but I'm not sure how to combine them.
public static int[] arrayHist(int n) {
int[] a = new int[n];
for (int i = 0; i<a.length; i++) {
a[i] = randomInt (0, 100);
}
return a;
}
public static void printHist() {
int[] scores = new int[30];
int[] counts = new int [100];
for (int i = 0; i<100; i++) {
counts[i] = arrayHist (scores, i, i+1);
}
}
Here is my attempt to calculate a histogram of any given positive integer according to your specification:
public static int[] histogram(int[] scores) {
int[] counts = new int [11];
for (int i = 0; i < scores.length; i++) {
int hist = scores[i] / 10;
if(hist == 0) {
counts[scores[i]]++;
} else {
counts[10] ++;
}
}
return counts;
}
You can pass your array of random numbers to this function. Print the results accordantly.
Basically you have to split your implementation into functions.
Create array of random integer
Calculate the histogram (see my method as example)
Print the histogramm
You mustn't mix this thinks up ;)
I would like to fill a 3x3 2D array with values 1,2,3.
I need each number to appear for a given times.
For example:
1 to appear 2 times
2 to appear 4 times
3 to appear 3 times
What I need is to store this numbers to array in a random position.
For Example:
1,2,2
3,2,2
1,3,3
I already did this in a simple way using only 2 different numbers controlled by a counter. So I loop through the 2D array and applying random values of number 1 and number 2.
I'm checking if the value is 1 and add it in the counter and the same with number 2. if one of the counter exceeds the number I have set as the maximum appear times then it continues and applies the other value.
Is there any better approach to fill the 3 numbers in random array position?
See code below:
int [][] array = new int [3][3];
int counter1 =0;
int counter2 =0;
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
array[i][j] = (int)random(1, 3); //1,2
if (arrray[i][j]==1) {
counter1++;
} else if (array[i][j] ==2) {
counter2++;
}
//if it is more than 5 times in the array put only the other value
if (counter1>5) {
array[i][j] = 2;
}
//if it is more than 4 times in the array put only the other value
else if (counter2>4) {
array[i][j] = 1;
}
}
}
I finally did this according to this discussion:
How can I generate a random number within a range but exclude some?, with 1D array for tesing, but it does not always works.
Please see attached code:
int []values = new int[28];
int counter1=0;
int counter2=0;
int counter3=0;
for (int i=0; i<values.length; i++) {
if (counter1==14) {
ex = append(ex, 5);
}
if (counter2==4) {
ex =append(ex, 6);
}
if (counter3==10) {
ex =append(ex, 7);
}
values[i] = getRandomWithExclusion(5, 8, ex);
if (values[i]==5) {
counter1++;
} else if (values[i] ==6) {
counter2++;
} else if (values[i] ==7) {
counter3++;
}
}
int getRandomWithExclusion(int start, int end, int []exclude) {
int rand = 0;
do {
rand = (int) random(start, end);
}
while (Arrays.binarySearch (exclude, rand) >= 0);
return rand;
}
I would like to fill the 1D array with values of 5,6 or 7. Each one a specific number. Number 5 can be added 14 times. Number 6 can be added 4 times. Number 7 can be added 10 times.
The above code works most of the times, however somethimes it does not. Please let me know if you have any ideas
This is the Octave/Matlab code for your problem.
n=3;
N=n*n;
count = [1 2; 2 4; 3 3];
if sum(count(:,2)) ~= N
error('invalid input');
end
m = zeros(n, n);
for i = 1:size(count,1)
for j = 1:count(i,2)
r = randi(N);
while m(r) ~= 0
r = randi(N);
end
m(r) = count(i,1);
end
end
disp(m);
Please note that when you address a 2D array using only one index, Matlab/Octave would use Column-major order.
There are a ton of ways to do this. Since you're using processing, one way is to create an IntList from all of the numbers you want to add to your array, shuffle it, and then add them to your array. Something like this:
IntList list = new IntList();
for(int i = 1; i <= 3; i++){ //add numbers 1 through 3
for(int j = 0; j < 3; j++){ add each 3 times
list.append(i);
}
}
list.shuffle();
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
array[i][j] = list.remove(0);
}
}
You could also go the other way: create an ArrayList of locations in your array, shuffle them, and then add your ints to those locations.
I'm doing an assignment and something is going wrong but I can't quite figure out what it is. We have to generate a random number between 1 and 25 and add it to an array. When adding the random number to the array, we have to make sure that it isn't already in the array, and if it is we have to generate another random number. Here's my code:
//Variables
Random rnd = new Random();
int rndNum;
int numbers[] = new int[20];
//adds random number to array
for (int index = 0; index < numbers.length; index++)
{
rndNum = rnd.nextInt(25) + 1; //generates random number
boolean same;
if (Arrays.binarySearch(numbers, rndNum) >= 0) //checks for number already in array
same = true;
else
same = false;
//gets another random number if needed
while (same == true)
{
rndNum = rnd.nextInt(25) + 1;
same = Arrays.asList(numbers).contains(rndNum);
}
numbers[index] = rndNum; //adds random number to array
Arrays.sort(numbers); //sorts array for checking purposes
}
//displays array
for (int index = 0; index < numbers.length; index++)
{
//prints numbers in table format
if (index == 4 || index == 9 || index == 14 || index == 19)
System.out.println(numbers[index]);
else
System.out.print(numbers[index] + "\t");
}
This is my output:
0 0 0 0 0
0 0 0 0 0
2 3 4 5 8
12 17 18 19 20
I went through and put break points to see where I was going wrong, but I couldn't see why I was getting a bunch of zeros. What have I done wrong?
The error could be following:
You do:
for (int index = 0; index < numbers.length; index++)
{
// some computation
numbers[index] = rndNum; //adds random number to array
Arrays.sort(numbers); //sorts array for checking purposes
}
You enter the new number and then sort the array. But after sorting, there could be a zero at the entry where you just added a non-zero number (because the array is initialized with zeros).
Try not to sort the array while iterating it.
If you need a set of random values, why wouldn't let a standard set to make all the job?
java.util.Random rnd = new java.util.Random();
java.util.Set<Integer> values = new java.util.LinkedHashSet<>();
while (values.size() < 20) {
values.add(rnd.nextInt(25) + 1);
}
System.out.println(values);
Then copy the set to an array if you prefer.