2 simple array errors? - java

I created a method that needs to check the range of a multidimensional array and make sure each value in the 2D array is smaller than or equal to the length of the array.
public static boolean method(int[][] solution){
//check rows for 1-N
for (int i=0; i < solution.length; i++){
if (solution[i] > solution.length)
return false; //check rows
}
//check columns for 1 - N
for (int j = 0; j<solution.length; j++){
//get a column in the one dimensional array
int[] column = new int[solution.length];
for (int i=0; i < solution.length; i++){
column[i] = solution[i][j];
}
if (column[i] > solution.length)
return false; //check columns
}
return true;
}
However, the errors I receive are follows:
Program.java:99: error: bad operand types for binary operator '>'
if (solution[i] > solution.length)
^
first type: int[]
second type: int
Program.java:110: error: cannot find symbol
if (column[i] > solution.length)
^
symbol: variable i
location: class Program
2 errors
Perhaps for the first error i need to get the array value instead of comparing the array? Not sure..

First, you can't compare an array with an int value
if (solution[i] > solution.length) // solution is a 2-d array and thus solution[i] is a 1-d array
// which can't be compared with an int value
and second, the i was declared in the for loop, and thus it's not visible outside its scope.
for (int i=0; i < solution.length; i++){
column[i] = solution[i][j];
} // scope of i is over here
if (column[i] > solution.length) // that's why you can't access `i` here
return false;
You either need to use j or declare the i before the for, so that you can use it after it or probably, move the if inside the inner for loop(and that seems to be the right way for your problem as well).

You are using i outside the for loop, maybe you want to use j instead.

Its because, solution is a 2d array.
int[][] solution;
and to get this work it should be,
if(solution[][] > solution.length)

I suppose this much code should suffice
public static boolean method(int[][] solution) {
// check rows for 1-N
for (int i = 0; i < solution.length; i++) {
for (int j = 0; j < solution[i].length; i++) {
if (solution[i][j] > solution.length)
return false; // check rows
}
}
return true;
}

Related

nested for loops integers missing from array

Beginner here. I'm having problems running this series of for loops to find which integers are missing from an array.
public class FunWithArrays{
public static void main(String[] args){
String nString = args[0];
int n = Integer.parseInt(nString);
int inputArray [] = {1,2,4};
System.out.println(" The missing numbers are " );
findMissingNum(n, inputArray);
}
public static void findMissingNum(int n, int[] inputArray){
for (int i = 1; i <= inputArray.length; i++){
int count = 0;
for( int j = 0; j < n; j++){
if(inputArray[j] == i){
count ++;
}
if (count == 0){
System.out.println(i);
}
}
}
}
}
I get the answer I want, namely 3, however it doesn't print but rather shows up in a runtime error:
java.lang.ArrayIndexOutOfBoundsException: 3
at FunWithArrays.findMissingNum(FunWithArrays.java:17)
at FunWithArrays.main(FunWithArrays.java:9)
the method should take an input n from the user (when the program is run) as the largest value of the array and print all the ones missing
The logic is the outer for loop should traverse the array for numbers 1-n, and the inner loop should add to the count variable each time it finds a certain number. At the end of iteration it should print any numbers with a final "count" of 0. THIS IS LITERALLY DRIVING ME CRAZY!!! thanks in advance :)
First of all, you should traverse from 0 to (inputArray.length-1) index of inputArray. This will get rid of the ArrayIndexOutOfBoundsException, because java array indexing starts from 0 not 1.
And for inner loop, run from 0 to n, since n is the max number.
And Thirdly, it should be inputArray[i] == j, not inputArray[j] == i, same for printing the value. In you case I believe you have n>=4, so it was trying to access inputArray[3] via inputArray[j] call. That's why you are getting this out of bound error.
I think your code means like this: nest loop always run through inner loop first before run the outer loop.
public static void findMissingNum(int n, int[] inputArray){
for (int i = 1; i <= n; i++){
int count = 0;
for( int j = 0; j < inputArray.length; j++){
if(inputArray[j] == i){
count ++;
}
if (count == 0){
System.out.println(i);
}
}
}
}
I will just use a while loop instead:
int num =1;
while(num<=n){
for(int i = 0;i<inputArray.length;i++){
if(inputArray[i]!=num){
System.out.println(num);
}
}
num++;
}
The i incrementing to <= ipnutArray.length is not causing the error because i is never used as the index. What is causing the error is when n > length.
Also, you should not be checking n elements starting from the beginning because n is the max value, not the number of elements.

Finding index of an item within a 2D Array

After some research, I found out how to find the index of an item within a 2D Array. However, I'm after just one value, the row number and also what if the item you are looking for appeared more than once?
How would you store the row number of all those times?
for(int j = 0; j < size; j++)
{
if (arr[i][j] == 88)
{
return i; // The value i wanna store
break;
}
}
If the number 88 appears more than once, how can I store all the different locations and later retrieve it?
You could store the values you want in a List.
List<Integer> rows = new ArrayList<>();
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (arr[i][j] == 88) {
rows.Add(i); // The value i wanna store
break; // exit inner loop and continue with next row
}
}
}
i'm after just one value, the row number
But if 88 appears more than once, how can I store all the different
locations and later retrieve it?
Considering you don't know how many duplicated copies of the value you're looking for there could be, I'd suggest using an ArrayList to store the indexes.
create this before the loops:
List<Integer> indexList = new ArrayList<>();
then within the if block simply add the index value for the value you've found to the ArrayList:
if (arr[i][j] == 88){
indexList.add(i);
break;
}
you can then return the ArrayList if your method requires returning the data:
return indexList; // after the loops have finished processing
However, if the method return type is void then you can simply ignore the return indexList;

Java - Multidimensional Arrays How to test an array for all unique values

I'm trying to test a multidimensional array to see if contains any duplicate values. If it does I would like the method to return false. Otherwise I would like it to return true.
Here is my current code. Where is my logic wrong?
public static boolean isUnique(int[][] array2, int num) {
for (int i = 0; i < array2.length - 1; i++) {
for (int j = i + 1; j < array2.length; j++) {
if (array2[i] == array2[j]) {
return false;
}
}
}
return true;
}
Your current implementation is checking whether two rows are the same (this is a reference based check, rather than a value.) This means that it asks 'Are array2[i] and array2[j] the same address in memory, rather than do they contain the same things.
If you want to see whether the rows are unique you'd use array2[i].equals(array2[j]) instead of array2[i] == array2[j].
If you wanted to check for unique elements (array[i][j] != array2[i+m][j+n] where !(m == n == 0)) you'd need to iterate through both levels in a
for (int i = 0; i < array2.length; i++) {
for (int j = 0; j < array2[i].length; j++) {
// compare array2[i][j] to all other array2[m][n] here.
}
}
Right now your code is checking whether any of the arrays inside array2 are the same. array2[i] and array2[j] are both referring to arrays, because array2 is an array of arrays.
Instead, you want to look at the values inside of each of those arrays. Since you want to fail on any repeated value anywhere in the grid, you're effectively trying to flatten the structure into one collection, and check for duplicates in that.
A HashSet is the best data structure to use in this case. Traverse the entire grid, row-by-row, adding values into your new struture. If you encounter a duplicate, return false:
public static boolean isUnique(int[][] array2) {
Set<Integer> values = new HashSet<>();
for (int i = 0; i < array2.length; i++) {
for (int j = 0; j < array2[i].length; j++) {
if (!values.add(array2[i][j])) {
return false;
}
}
}
return true;
}
Some things to note here:
The set's add method will return false if you attempt to add a duplicate to the collection, so that's wrapped in an if statement for a simple, fail-fast stopping condition.
The sizes of each of the inner arrays are completely independent from the size of the outer array, so you still want to loop from 0 to the length of the array (when you're using <, you don't need the length - 1).

Java integer array, I cant do simple maths it seems

I have the code below:
int lines = 0;
while(lines < 2)
{
int[] oldarr = parr;
for(int i = 0; i < arrsize; i++)
System.out.print(" " + oldarr[i]);
System.out.println();
for(int i = 0; i < arrsize; i++)
{
if(i == 0)
parr[i] = 0;
else
parr[i] = Math.abs(oldarr[i] - oldarr[i-1]);
}
lines++;
}
parr is an array of integers of size [arrsize]. Each time through this loop I want to print the value of each index in parr, then set each index to the difference between the index before it and itself. Currently it gives me the correct (hardcoded) originally parr. But the next(first) iteration of changing parr gives me unexpected values; they are not even close to the difference between the two neighboring values..
Any ideas?
You aren't copying your array with this line:
int[] oldarr = parr;
The two variables are still pointing at the same array.
To get a copy, you can do:
int[] oldarr = Arrays.copyOf(parr, parr.length);
In your second for loop, you are setting the new value to the difference of the current value and the previous value, but the previous value was already changed in the previous iteration of the for loop.
Change your second for loop iteration to iterate through the array backwards, so your calculations don't depend on previous calculations.
for(int i = arrsize - 1; i >= 0; i--)

Checking rows of 2d ArrayList for specific values

I am trying to scan every row of a 2d array (100x100 sizes) and make sure that every row (and later column) will have only 1 instance of every integer 1 through 100. In the following code I am trying to make sure every row only has one instance of every integer 1 through 100, but obviously the syntax does not work. Is there any method that could push this through or what am I missing?
Thanks for any assistance
for(int i = 0; i<100; i++) {
for (int j=0; j<100 ; j++) {
if(2dARR.get(i).get(j).contains(1) && 2dArr.get(i).get(j).contains(2)(.....)) {
System.out.println("FK");
}
}
}
Dump it into a Set, check that the size of the Array and Set are Equal. If they aren't, there are duplicates. If you get past that test, run a loop through the array and check that all values are greater than 0 and less than 101 (1-100).
for(int i = 0; i<100; i++) {
Set<Integer> numbersInRow = new HashSet<Integer>();
for (int j=0; j<100 ; j++) {
int num = 2dARR.get(i).get(j);
if (num < 1 || num > 100) {
// out of bounds, handle error
}
else {
numbersInRow.add(num);
}
}
// At this point we have the set of numbers found in the row, all guaranteed to be >=1 and <= 100
if (numbersInRow.size() != 100) {
// at least one number appeared more than once
}
}

Categories