I am trying to create an nxn array full of random integers between 1 and 10. When I try to print it out, I am getting an odd number of integers not filling an array, and never up to the correct number of integers (for instance, a supposed 5x5 array is returning 17 integers). Code snippet follows, assume all variable are declared correctly unless contained in here and java.util.Random is imported.
if (choice==1){
Random rand = new Random();
System.out.println("Please input a power n for (nxn array) between 1-6");
int power = kb.nextInt();
int[][] randMatrix = new int[power-1][power-1];
if (power < 1 || power > 6){
System.out.println("Invalid power");
}else{
for (i=0; i<randMatrix.length; i++){
for (j=0; j<randMatrix.length; j++){
randMatrix[i][j] = rand.nextInt(9);
}
}for (i=0; i<randMatrix.length; i++){
for (j=0; j<randMatrix.length; j++){
System.out.println(randMatrix[i][j]);
}
}
}
}
It doesn't print 17 integers, it prints 16. This is because 16 is 4 * 4 and you should have done
new int[power][power]
rather than
new int[power-1][power-1]
The comments are also correct that it should be
for (j = 0; j < randMatrix[i].length; j++)
but this does not explain your problem, as the array is square.
Related
I have n inputs.
these inputs are numbers from 1 to 100.
I want to output the number that appears less than the other ones; also if there are two numbers with the same amount of appearance, I want to output the number that is less than the other one.
I wrote this code but it doesn't work!
Scanner scanner = new Scanner(System.in);
int n=scanner.nextInt(), max=0 , ans=-1;
int[] counter = new int[n];
for(int i=0; i<n; i++)
counter[scanner.nextInt()]+=1;
for(int j=1; j<=100; j++){
if(counter[j]>max)
max=counter[j];
}
for (int i=1; i<=max; i++){
if(counter[i]>0)
if(ans==-1 || counter[ans]>counter[i] || (counter[ans] == counter[i] && i<ans))
ans=i;
}
System.out.print(ans);
There’s a couple of problems with your code, but the main one is the last for loop: You are trying to find the first (ie lowest) number whose counter is equal to max, so your loop should be from 1 to n, not 1 to max.
Another problem is if you are using the number, which is in the range 1-n, as your array index, you need an array of size n+1, not n.
I pinched this from another question regarding the title of yours:
i = input.nextInt (); while (i != 0) { counts [i]++; i = input.nextInt (); } That method increments the number at the position of the user input in the counts array, that way the array holds the number of times a number occurs in a specific index, e.g. counts holds how often 3 occurs.
counter array should contain frequency values for the numbers from 1 to 100 inclusive.
That is, either a shift by 1 should be used when counting the frequency:
int[] counter = new int[100];
for (int i = 0; i < n; i++) {
counter[scanner.nextInt() - 1]++;
}
or 101 may be used as the length of counter array thus representing values in the range [0..100], without shifting by 1.
int[] counter = new int[101];
for (int i = 0; i < n; i++) {
counter[scanner.nextInt()]++;
}
The minimal least frequent number can be found in a single loop (assuming that the counter length is 101).
int minFreq = 101, answer = -1;
for(int j = 1; j <= 100; j++) {
if (counter[j] > 0 && counter[j] < minFreq) { // check valid frequency > 0
minFreq = counter[j];
answer = j;
}
}
System.out.println(answer);
For a wider range of input values (e.g. including negative values) of a relatively small count it is better to use a hashmap instead of a large sparse array.
I want to fill an array of size X with random integers from 0 to X with no duplicates. The catch is I must only use arrays to store the collections of int, no ArrayLists. How do I go about implementing this?
I don't understand why I can't seem to get this. But this is my most recent bit of code that fills the list but allows for duplicates.
System.out.print("Zero up to but excluding ");
int limit = scanner.nextInt();
// create index the size of the limit
int [] index = new int[limit];
for(int fill=0;fill<limit;fill+=1){
index[fill] = (limit);
}
int randomNumber = 0;
Random rand = new Random();
int [] randoms = new int[limit];
boolean flag = true;
// CODE TO NOT PRINT DOUBLES
for (int z=0;z<limit;z+=1){
randomNumber = rand.nextInt(limit);
int i=0;
while (i<limit){
if (index[i] == randomNumber){
flag = true;
}
else {
flag = false;
break;
}
i+=1;
}
if (flag == false){
randoms[z] = randomNumber;
index[z] = randomNumber;
}
}
System.out.println("Randoms: "+java.util.Arrays.toString(randoms));
Here's one way to do it:
Create an array of length N
Fill it from 0 to N-1
Run a for loop and swap randomly 2 indices
Code:
// Step 1
int N = 10;
int[] array = new int[N];
// Step 2
for(int i=0; i < N; i++)
array[i] = i;
// Step 3
for(int i=0; i < N; i++) {
int randIndex = (int) (Math.random() * N);
int tmp = array[i];
array[i] = array[randIndex];
array[randIndex] = tmp;
}
Why not rephrase the problem to shuffling an array of integers. First fill the array monotonically with the numbers 0 to X. Then use the Random() function to select one of the X numbers to exchange with the number in position 0. Repeat as many times as you may like. Done.
Here is your bug:
while (i<limit){
if (index[i] == randomNumber){
flag = true;
}
else {flag = false;break;} <--- rest of the array is skipped
i+=1;
}
after you generated a new number, you start to check for equality , however once you find that randomNumber!=index[i] (else statement) you break out of the while. look this: actual array is 3,4,5,1 your new number is 5, you compare it to 3 just to find out that they different so flag is set to false and break out happens.
Consider using another array filled with elements in order from 0 to X. Then, with this array, shuffle the elements around. How do you go about this? Use a loop to traverse through every single element of the array, and for each iteration, choose a random number from 0 to array.length - 1 and switch the elements at the index you're currently on and the random index. This is how it would look like,
In your main, you would have an array initialized by doing this,
int[] arr = new int[10];//10 can be interchangeable with any other number
for(int i = 0; i < arr.length; i++){
arr[i] = i;
}
shuffleArray(arr);
And the shuffle method would look like this,
public int[] shuffleArray(int[] arr){
Random rand = new Random();
for(int i = 0; i < arr.length; i++){
int r = rand.nextInt(arr.length);//generate a random number from 0 to X
int k = arr[i];
arr[i] = arr[r];
arr[r] = k;
}
}
This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
Here is part of my code. I want to assign random number to the matrix population[][] first, then compare the random number to a specific number ranP, if population[][] < ranP, then re-assign population[][] to 1, otherwise 0. But it shows
arrayindexoutofboundsexception 0
Need help on the issue. Thanks!
randGen = new Random();
double randNum = randGen.nextDouble();
for ( int i = 0; i < 11; i++){
for (int k = 0; k < inipopulationsize; k++){
for (int j = 0; j < 25; j++){
ranP = 0.5;
//TMaxtrix[i][j] = matrix[i][j];
System.out.println(matrix[i][j] + " ");
population = new double[k][j];
System.out.println("randNum: " + randNum);
population[k][j] = randNum;
if (randNum <= ranP){
population[k][j] = 1;
}
else
population[k][j] = 0;
System.out.println("population: " + population[k][j]);
}//j loop
}//k loop
}//i loop
I am learning this by myself, and not taking any classes. If this really bothers you "experts", why dont you just ignore and save your time go home watching a movie or spending more time with your family? Appreciate the help from nice people here. But shame on you who only knows sarcasm. Here is what works finally:
randGen = new Random();
population = new int[inipopulationsize][25];
for ( int i = 0; i < population.length; i++){
for (int j = 0; j < population[i].length; j++){
double randNum = randGen.nextDouble();
ranP = 0.5;
if (i < 11){
//System.out.println(matrix[i][j] + " ");
}
if (randNum <= ranP){
population[i][j] = 1;
}
else
population[i][j] = 0;
//System.out.println("population index: " + i + " Dieasease index: " + j + " DI on (1) or off (0): " + population[i][j] + "");
}//j loop
}//i loop
Is the third loop because you want i 2d arrays? If so you should probably look at ArrayLists of 2d arrays.
int inipopulationsize = 25;
double[][] population;
Random randGen = new Random();
double randNum = randGen.nextDouble();
double ranP = 0.5;// outside loops
population = new double[inipopulationsize][25]; // out
for (int k = 0; k < inipopulationsize; k++){
for (int j = 0; j < 25; j++){
randNum = randGen.nextDouble();//i assume you want new random every time
if (randNum <= ranP){
population[k][j] = 1;
}
else
population[k][j] = 0;
}//j loop
}//k loop
System.out.println(Arrays.deepToString(population));
I don't see a reason for having 3 loops with a 2d array.
Random randGen = new Random();
double randNum;
for(int i=0; i<population.length; i++){
for(int j=0; j<population[i].length; j++){
randNum = ranGen.nextDouble();
if(randNum<0.5) population[i][j] = 0;
else population[i][j] = 1.0;
}//j loop
}//i loop
Your issue is that you are referring to an item outside the bounds of your 2D array.
Let's take a look at your code. This line: population = new double[k][j]; declares a new 2D arrays of size kxj. Then in this line: population[k][j] = randNum; you try to reference the item in the kth column and jth row of this same 2D array. This is not legal in Java arrays.
Java arrays are 0-indexed, which means with an array of size k, your indexes range from 0 to k-1. There is no item at index k. This is why you are receiving an index out of bounds error.
Please look at this link instructing you on the basic use of Java Arrays.
The exact error arrayindexoutofboundsexception 0 appears because on your first iteration, you create a population of size 0 by 0. Then you try to access the item in column 0 and row 0, that is to say, the first item. However as your population array has 0 size, it has no space, and even the index 0 is out of bounds.
However, I am not even sure this is what you want to be doing.
You are declaring a 2D array on each iteration of your loop. If all you are trying to do is make a single array of size inipopulationsizeby25 (these are the initial values of k and j) then you need to declare this outside of these two nested loops. Perhaps even outside of the third loop, as I am not even sure what that loop is doing.
Take a loop at anaxin's answer for how to effectively assign 0's and 1's to your population array randomly. (With randP set to 0.5 you are giving each a 50% chance of appearing.)
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.