This question already has answers here:
Closed 10 years ago.
I need to reverse an array for example move what ever is in spot 5 to 0, 4 to1, 3 to 2.
int size, length;
System.out.print("how big of a list do you have: ");
size=reader.nextInt();
length=size-1;
int [] array = new int [size];
for (int count=0; count < array.length; count ++){
System.out.println("enter a number: ");
array [count] = reader.nextInt();
}
for (int count=length; count > 0; count --)
array [(length-count)];
}
}
I am doing this in eclipse and I keep getting an error in the last line saying that I am not using an operator/expression : array [(length-count)]; but I dont know why the minus sign is not working? or if my program will work in general it did not get past the build part.
int temp = 0;
for (int i = 0; i < array.length / 2; i++)
{
int temp = array[i];
array[i] = array[array.length - i--];
array[array.length - i--] = temp;
}
temp is used so that numbers don't overwrite each other. Think of it like getting food from a fridge. The milk is behind the water, and you want some milk. In order to get the milk, you take the water and put it in your hand (temp would be the hand). You then put the milk where the water was and the water where the milk was. Without the "hand", you would have lost your water (fallen on the floor, or in the case of temp, lost in memory) and only be left with milk.
Array[(length-count)] doesn't work because it's a value, it's the same as writing
0;
It is not a call to a procedure or an operation, so it is an error.
Try this:
int temp = 0 ;
for(int start=0, end = numbers.length -1 ; start < end; start++, end--){
//swap numbers
temp = array[start];
array[start] = array[end];
array[end] = temp;
}
Related
I am pretty new to java and am just learning 2D arrays. I am trying to get the top 5 numbers to display from a random list. I think this could work but am not sure why I am getting an error. One other thing is that I cannot use the sort function.
Code here:
public static void main(String[] args) {
//Random Number stuff
Random rand = new Random();
int[] large = new int [5];
int max = 0, index;
int[][] arrSize = new int [4][5];
for (int i = 0; i < arrSize.length; i++) {
for (int j=0; j< arrSize[i].length; j++) {
arrSize[i][j] = rand.nextInt(89) + 10;
System.out.print(arrSize[i][j] + " ");
}
System.out.println();
}
// Top 5
for (int p = 0; p < 5; p++) {
max = arrSize [0][0];
index = 0;
for (int i = 0; i < arrSize.length; i++) {
for (int j = 0; j < arrSize[i].length; j++) {
if (max < arrSize[i][j]) {
max = arrSize[i][j];
index = i;
}
}
}
large[p] = max;
arrSize[index] = Integer.MIN_VALUE; //Error here
System.out.println("Highest Number: " + large[p]);
}
}
}
Error text:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from int to int[]
at secondAssignment.BiggestNumbersRectangular.main(BiggestNumbersRectangular.java:47)
I am not sure why I am getting an error, any help would appreciated. If anyone else has any answers for how I could get the top 5 in a different way that would also be appreciated.
You declare your arrSize here
int[][] arrSize = new int [4][5];
and try to set it's value here
arrSize[index] = Integer.MIN_VALUE;
The Object at arrSize[index] is an array.
Remember that a 2D array basically looks like this:
arrSize
- arrSize[0]
- arrSize[0][0]
- arrSize[0][1]
- arrSize[1]
- arrSize[1][0]
- arrSize[1][1]
- arrSize[2]
- arrSize[2][0]
- arrSize[2][1]
- arrSize[3]
- arrSize[3][0]
- arrSize[3][1]
Because index is a single int, you are assentially calling arrSize[0], which contains arrSize[0][0] and arrSize[0][1].
The Integer.MIN_VALUE is not an array of integers. It is an int. You cannot assign int to int[].
As you can see in other parts of the code, to access values in 2D array arrSize, you need 2 indexes in your case (and usually) i and j.
You need to save both i and j after you find the highest number.
if (max < arrSize[i][j]) {
max = arrSize[i][j];
indexI = i;
indexJ = j;
}
and then
arrSize[indexI][indexJ] = Integer.MIN_VALUE;
As to why you got the error, arrSize[i] gets you a 1D array. It's still an array and you cannot set an array to an integer (Integer.MIN_VALUE). in Java represented as int[] in the error message.
The algorithm could be improved, instead of using a single integer max for saving the highest value, you could use a maxArr of the same size as the number of highest numbers you want (in your case 5) and check against all of the numbers in maxArr using a for in place of
if (max < arrSize[i][j]) {
max = arrSize[i][j];
index = i;
}
That would mean you could remove the index (or indexI and indexJ) and topmost for cycle (for (int p = 0; p < 5; p++)). But that's another topic, and one you should learn yourself.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I want to sort a 2d int array based on the 2nd element and this is what I came up with. But it doesnt seem to work. I understand there is a Arrays.sort(array, Comparator) which I can use, but I wanted to write my own sorting algorithm for the fun of it. Could anyone help me out please ?
ip = [[5,10],[2,5],[4,7],[3,9]]
Expected op = [[5,10],[3,9],[4,7],[2,5]]
void mergeSort(int[][] boxTypes){
int mid = boxTypes.length / 2;
int[][] left = new int[mid][2];
int[][] right = new int[boxTypes.length - mid][2];
for(int i = 0; i < mid; i++) left[i] = boxTypes[i];
for(int i = mid; i < boxTypes.length; i++) right[i - mid] = boxTypes[i];
mergeSort(left);
mergeSort(right);
merge(left, right, boxTypes);
}
void merge(int[][] left, int[][] right, int[][] boxTypes){
int i = 0; int j = 0; int k = 0;
while(i < left.length && j < right.length){
if(left[i][1] < right[j][1]){
boxTypes[k][0] = left[i][0];
boxTypes[k][1] = left[i++][1];
} else {
boxTypes[k][0] = right[j][0];
boxTypes[k][1] = right[j++][1];
}
k++;
}
while(i < left.length) boxTypes[k++] = left[i++];
while(j < right.length) boxTypes[k++] = right[j++];
}
You never stop the recursion:
in the first step you split boxTypes into two arrays of length 2.
in the second step you split the first array of length 2 into two arrays of length 1.
in the third step you split the first array of length 1 into an array of length 0 and one of length 1.
in the fourth (and every succeeding step) you try to split the array of length 0 into two arrays of length zero.
You need to stop the recursion as soon as the length of boxTypes is 1 or less (since an array of length 0 or 1 is trivially sorted):
void mergeSort(int[][] boxTypes){
if (boxTypes.length <= 1) return;
int mid = boxTypes.length / 2;
int[][] left = new int[mid][2];
int[][] right = new int[boxTypes.length - mid][2];
for(int i = 0; i < mid; i++) left[i] = boxTypes[i];
for(int i = mid; i < boxTypes.length; i++) right[i - mid] = boxTypes[i];
mergeSort(left);
mergeSort(right);
merge(left, right, boxTypes);
}
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.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I was trying to solve a problem in a coding trainer. But, I just could not figure this problem for the life of me.
Here is the problem:
You are given an m x n 2D image matrix where each integer represents a pixel. Flip it in-place along its horizontal axis.
Example:
Input image :
1 1
0 0
Modified to :
0 0
1 1
I tried swapping rows as I traversed 2d array down the row for test case:
1,2,3
4,5,6
7,8,9
But, I end up getting
4,5,6
7,8,9
1,2,3
instead of
{{7,8,9},
{4,5,6},
{1,2,3}}
Here is the answer code.
public static void flipHorizontalAxis(int[][] matrix) {
int r = matrix.length - 1, c = matrix[0].length - 1;
int temp = 0;
for(int i = 0; i <= r/2; i++){
for(int j = 0; j <= c; j++){
temp = matrix[i][j];
matrix[i][j] = matrix[r-i][j];
matrix[r-i][j] = temp;
}
}
}
I still do not understand the answer code. Specifically, why the outer loop has "i <= r/2" and the swap has "matrix[r-i]" in the index. Why r/2 and r-i? I really do not understand why and I am totally stuck.
Can someone explain those lines so I can understand the code?
Here is the expected output for test cases:
1
{{1}}
1,0,0
0,0,1
{{0,0,1},{1,0,0}}
1,0
{{1,0}}
1,2,3
4,5,6
7,8,9
{{7,8,9},{4,5,6},{1,2,3}}
1,0,1
1,0,1
{{1,0,1},{1,0,1}}
Focusing on only the double loop:
for (int i=0; i <= r/2; i++){
for (int j=0; j <= c; j++){
temp = matrix[i][j];
matrix[i][j] = matrix[r-i][j];
matrix[r-i][j] = temp;
}
}
The outer loop in i only ranges up to (and including) one half the height of the matrix because we want to swap each array with its "mirror" image on the other side of the median row. That is, for a 3x3 matrix we want to do the following:
1,2,3 i=0
4,5,6
7,8,9 r-i=matrix.length-1 = 3-1 = 2
(swap these rows, i=i+1)
7,8,9
4,5,6 i=1, r-i=1
1,2,3
(swap the median row with itself, nothing changes)
If we were to allow the outer loop to run the full height of the input matrix, then after the median row we would actually undo the swap already done, and would just end up the original input matrix.
The number of row swaps you need to do is matrix.length/2 - 1. You could have written:
for (int i = 0; i < matrix.length/2; i++)
instead of:
for(int i = 0; i <= r/2; i++)
for matrices with an odd number of rows, matrix.length/2 and r/2 are equal, which means that in the second form, because of the <=, you will swap the middle row with itself, which is useless, so I prefer the first form.
Now the index r-i will go downwards from the index of the last row (r = matrix.length-1). It's the index of the row that must be swapped with the one at index i.
Note that the the rows themselves are array, and it would be more efficient to swap the whole rows instead of each individual element, so here is a better solution:
public static void flipHorizontalAxis(int[][] matrix) {
int r = matrix.length-1;
for (int i = 0; i < matrix.length/2; i++) {
int[] temp = matrix[i];
matrix[i] = matrix[r - i];
matrix[r - i] = temp;
}
}
Or:
public static void flipHorizontalAxis(int[][] matrix) {
int r = matrix.length;
for (int i = 0; i < matrix.length/2; i++) {
--r;
int[] temp = matrix[i];
matrix[i] = matrix[r];
matrix[r] = temp;
}
}
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.)