Comparing int array element values Java - java

Trying to compare the elements of an array. For instance, would like to return a boolean if array[0][0] was equal to array[0][1]. I figured seeing if two elements were not equal would be easier. So
boolean rowAlike = true;
for(int row = 0; row<size; row++)
{
for(int col = 0;col<size;col++)
{
nextNum = col + 1;
if(!square[row][col].equals(square[row][nextNum]))
rowAlike=false;
}
if(rowAlike)
System.out.println("All digits are the same in row " +row++);
Since arrays are reference variables I know that == will compare the memory locations rather than the values of those elements. I tried it they way above and also tried
Arrays.equals(square[row][col],(square[row][nextNum])
I either get a false false or a compiler error.
EDIT: the false false I receive is when using == I get a compiler error using .equals
ExploreMatrix.java:89: error: int cannot be dereferenced
And when using Arrays.equals
ExploreMatrix.java:89: error: no suitable method found for equals(int,int)

Primitives (such as int) are tested by values with == and/or != (as appropriate). You need to define the rowAlike in the loop body (or it won't reset on the next row). Accessing col + 1 when col == size - 1 will result in an ArrayIndexOutOfBounds. I suggest you start at 1 and then compare to the previous. Next, you can break in your loop when you first find a value that doesn't match. Finally, for display, you shouldn't modify the value of row (or you will skip a row). Putting it all together,
int[][] square = new int[size][size];
//
// ... Setup values in square ...
//
for (int row = 0; row < size; row++) {
boolean rowAlike = true;
for (int col = 1; col < size; col++) {
if (square[row][col - 1] != square[row][col]) {
rowAlike = false;
break;
}
}
if (rowAlike) {
System.out.printf("All digits are the same in row %d%n",
row + 1);
}
}

if(!square[row][col].equals(square[row][nextNum]))
The code above will work if your square is an array of String.
Unfortunately, you did not define square in your question.
Use == for comparing primitive types like int and .equals for comparing String

There are multiple issues in your code:
Most likely, an ArrayIndexOutOfBoundsException occurs (which is a
RuntimeException) here:
for(int col = 0;col<size;col++){
nextNum = col + 1;
if(!square[row][col].equals(square[row][nextNum]))
//...
}
In the last iteration, colwill be size-1, which means nextNumwill be equal to the arrays size. An array of size x has
indices 0to x-1.
You increment rowtwice (for-loop and SYSOUT)
I know that == will compare the memory locations
This does not apply for primitive types. According to your Exception, you try to compare int-values. Go for ==.
Check the JavaDoc of Arrays#equals() method.

Related

How to find first instance of element array

I'm a pretty basic programmer and I'm coding a 'Master-mind' style guessing game program.
Now the part I'm stuck with is that I want to go through an array and increase the pointer when I come across a specific number.
Now thats pretty easy and stuff, but what I want to do is ONLY increase the counter if the number is encountered for the first time. So, for example if there are two numbers (189, 999), I want the counter to increase only once, instead of 3 times, which is what my code is doing. I know why its doing that, but I can't really figure out a way to NOT do it (except maybe declaring an array and putting all the repeated numbers in there and only incrementing it if none of the numbers match, but that's super inefficient) Here's my code:
for (int i = 0; i < mString.length(); i++) {
for (int j = 0; j < nString.length(); j++) {
if (mString.charAt(i) == nString.charAt(j)) {
correctNumbers++;
}
}
}
Thanks for taking the time to read! I'd prefer it if you wouldn't give me a direct answer and just point me in the right direction so I can learn better. Thanks again!
Your question is quite unclear. I suppose 989 and 999 will return 1. Because you only deal with number, so the solution is:
Create a boolean array with 9 element, from 0-9, named isChecked
Initialize it with false.
Whenever you found a matching number, say 9, turn the boolean element to true, so that you don't count it again (isChecked[9] = true).
Here is the code:
var isChecked = [];
function resetArray(input) {
for (var i = 0; i < 10; i++) {
input[i + ''] = false;
}
}
resetArray(isChecked);
var firstNumber = '989',
secondNumber = '999',
correctNumbers = 0,
fNum, sNum;
for (var i = 0; i < firstNumber.length; i++) {
fNum = firstNumber.charAt(i);
// Skip already checked numbers
if (isChecked[fNum]) {
continue;
}
for (var j = 0; j < secondNumber.length; j++) {
sNum = secondNumber.charAt(j);
if (fNum == sNum && !isChecked[sNum]) {
correctNumbers++;
isChecked[sNum] = true;
}
}
}
console.log(correctNumbers);
Tested on JSFiddle.
If you find anything unclear, feel free to ask me :)
(except maybe declaring an array and putting all the repeated numbers in there and only incrementing it if none of the numbers match, but that's super inefficient)
That approach is a good one, and can be made efficient by using a HashSet of Integers. Everytime you encounter a common digit, you do a contains on the set to check for that digit (gets in HashSets are of constant-time complexitiy - O(1), i.e. super quick), and if it's present in there already, you skip it. If not, you add it into the set, and increment your correctNumbers.
I believe this would help
int found=0; for (int i = 0; i < mString.length(); i++) {
for (int j = 0; j < nString.length(); j++) {
if (mString.charAt(i) == nString.charAt(j)) {
if(found==0){
correctNumbers++;
}
}
}
}
You could try making another 1D array of
int size = nstring.length() * mstring.length();
bool[] array = new bool[size];`
and then have that store a boolean flag of whether that cell has been updated before.
you would find the unique index of the cell by using
bool flag = false
flag = array[(i % mString.length()) + j)];
if(flag == true){
<don't increment>
}else{
<increment>
array[(i % mString.length()) + j)] = true;
}
you could also do this using a 2d array that basically would act as a mirror of your existing table:
bool[][] array = new bool[mstring.length()][nString.length()];
Why not just use the new stream api? Then it's just that:
Arrays.stream(mString).flatMapToInt(s -> s.chars()).distinct().count();
I'll explain:
Arrays.stream(mString) -> Create stream of all strings.
flatMapToInt -> create single concatenated stream from many IntStreams
s -> s.chars() -> Used above to create streams of characters (as ints)
distinct -> remove all duplicates, so each character is counted only once
count -> count the (unique) characters

Iterating through the subdiagonal of a 2D Array

I am trying to iterate through a randomly generated 2d array of 0s, and 1s. In this method which I am stuck on I am trying to see if the subdiagonal has all the same numbers, all 1s, all 0s, or different numbers.
sub diagonal meaning:
110
101
011
The 0s are the subdiagonal.
this is the code I have as of now. I am trying to iterate starting at the last row and counting up to the first row diagonally.
int firstValue= matrix[matrix.length-1][0];
int result = -1;
for(int row = matrix.length-1; row > 0; row--)
{
int column = row;
if(firstValue == matrix[row][column])
{
result = firstValue;
continue;
}
else
{
result = -1;
break;
}
}
if(result== 1)
{
System.out.println("All " + firstValue + "s on the subdiagonal");
}
else if (result == 0)
{
System.out.println("All " + firstValue + "s on the subdiagonal");
}
else
{
System.out.println("Numbers on subdiagonal are different");
}
}
I'm almost certain my issue is with the firstValue and/or the for loop counting up the diagonal.
Any help would be appreciated, thanks much
Your issue seems to be at the following line,
for(int row = matrix.length-1; row > 0; row++) {
...
}
you are doing a
row = matrix.length-1; // row = array length - 1
row++ //this will increase the row's value beyond your array length
Then you will be accessing a index that does not exist causing a ArrayIndexOutOfBoundsException
Edit
what you'd want to do is,
for(int row = matrix.length-1; row >= 0; row--) {
....
}
This way you'd be able to iterate though your array from largest index to the smallest (0).
Edit 2
Let's say Staring array called arr has 4 elements. It'll be structured as below,
arr[0] = "test1";
arr[1] = "test2";
arr[2] = "test3";
arr[3] = "test4";
Array indexes always starts from 0, so the highest index in the above array is 3.
So if you want to iterate from smallest index to the largest, you'd do
for(int i = 0; i < arr.length; i++) {
//i's initial value is 0 and itll increment each time the loop runs
//loop will terminate when i is no longer < 4
System.out.println(arr[i]);
}
and to iterate through the array in reverse order you'd do,
for(int i = (arr.length - 1); i <= 0; i--) {
//i's initial value is (4 - 1) and it'll decrement each time the loop runs
//loop will terminate when i smaller or equal to 0
System.out.println(arr[i]);
}
So we want to check if all of the values in the subdiagonal are the same value, and if they are then we want to print the value that is the same. First we set aside a comparison to check the other indices
int checkValue = arr[0][arr[0].length-1];
This is the last value in the first row. Then we set a flag to catch whenever our index that we are checking matches our first value. We'll set it to false because we'll assume that the values don't match.
boolean flag = false;
Now that we have that, we need to iterate through each row in our array. We will start with the second row (arr[1]) and then we need to check the value one down and one over compared to the last value we checked (arr[1][arr.length - 1 - i]). If our first value (we assigned it's value to checkValue) and the value we are checking are the same, change the flag to true.
for (int i = 1; i < arr.length; i++)
if (arr[i][arr.length - 1 - i] != checkValue)
flag = true;
That'll run through all of the rows in the array. Now we have to check the state of our flag and print out the appropriate response. If the flag is true, print out that the values on the row are the same. Else we will say that the subdiagonal does not match all the way through.
if (!flag)//remember our flag is set to false, double negative equals true.
System.out.println("All of the values on the subdiagonal are the same");
else
System.out.println("All of the values on the subdiagonal are not the same");

Putting data into Java arrays

I have a fundamental question about how arrays store data and how to properly put data into an array.
THIS PART ANSWERED
In this code the method spinWheel() is just calling an integer from 0-36.
for(cntr=0; cntr<99; cntr++)
{
spunNum=spinWheel();
all99Spun[0]=spunNum;
}
How do I adjust the array all99Spun[] so that the next time the loop executes it would put spunNum into all99Spun[1] and so forth?
Another question I have about arrays is how to check equality between 1 integer and all the integers stored in an array.
for example I have an array that stores all the red numbers of a roulette wheel.
int redNumbers[] = new int[] {1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36};
How would I check the equality of a number stored in the all99Spun array with that of the integers in the array of rednumbers?
Just change
all99Spun[0]=spunNum;
to
all99Spun[cntr]=spunNum;
To answer the second question, I think you just want to see if any one number from the spun array exists in the read array. If you want to check that just one number exists in the read array you can loop through until you find that number:
int num = all99Spun[0];
int index = -1;
for(int i = 0; i < redNumbers.length ; i++)
{
if(redNumbers[i] == num)
{
index = i;
break;
}
}
if at the end index does not equal -1, then the number was in the redNumbers array.
If you want to check it for the entire array:
for(int i = 0 ; i < all99Spun.length ; i++)
{
for(int j = 0; j < redNumbers.length; j++)
{
if(redNumbers[j] == all99Spun[i])
{
//doWork
}
}
}
Just change
all99Spun[0]=spunNum;
to
all99Spun[cntr]=spunNum;
Given the way I understand your first question, I think #Gregory's answer is right.
So I will try to answer your second question.
Another question I have about arrays is how to check equality between 1 integer and all the integers stored in an array.
There are 2 easy ways to see if an array of integers are equal.
Iterate through with a loop, keeping a reference to the previous number. The minute you find one that does not equal the previous one, you know they are not all equal.
Since you are using Java, you can add them all to a Set, which guarantees uniqueness. If they are all equal, then after adding them all to the set, the set should contain only 1 element.
Example of first:
for (int i = 0; previous = redNumbers[i]; i < redNumbers.length; i++) {
if (redNumbers[i] != previous) {
// they are not all equal.
}
previous = redNumbers[i];
}
Example of second:
Set<Integer> distinct = new TreeSet<>(Arrays.asList(redNumbers));
if (distinct.size() > 1) {
// they are not all equal.
}

analyzing a 2D array by columns

I have the following 2D array and I want to compare all the columns with each other.
int [][] myarray={{1,2,3},{1,2,3},{1,2,3}};
So what I want to see is if column 1 (all 1's) is equal to the values in column 2 (all 2's).
Ps. the array size is not just limited to this.
It's not quite clear from your question whether you want to compare all columns to each other, or just a single column to another single column (for example column 1 to column 2). Assuming you meant the latter, you could do this.
public boolean columnsIdentical(int[][] array, int colIndex1, int colIndex2) {
for (int row = 0; row < array.length; row++ ) {
if (array[row][colIndex1] != array[row][colIndex2]) {
return false;
}
}
return true;
}
for (int i=0;i<myarray[0].length;i++) {
int comp=myarray[0][i];
for (int j=1;j<myarray.length;j++) {
if (myarray[j][i] != comp) {
// no match
} else {
// match
}
}
}
To test all pairs of columns you need 3 loops
Innermost compares elements of columns A and B
Middle loops through B, skipping columns already checked
Outermost loops through A for all columns

Finding Duplicate Array Elements

I've been struggling to create a function to essentially find all the indices of duplicate elements in a multi-dimensional array(unsorted), in this case a 5x5 array, and then using the indices found changing the parallel elements in a score array. But only find duplicates within columns and not comparatively to the other columns in the array Here is what I've done so far, with research online. The main problem with this code is that it will find all the duplicate elements but not the originals. For example: if the array holds the elements:
{{"a","a","a"},{"b","b","b"},{"a","c","a"}}, then it should change the parallel score array to: {{0,1,0},{1,1,1},{0,1,0}}. But instead it only recognizes the last row and top the top row's duplicates.
Code:
public static void findDuplicates(String a[][])
{
System.out.println("*Duplicates*");
Set set = new HashSet();
for(int j = 0; j<a.length; j++)
{
for(int i=0; i < a[0].length; i++)
{
if(!set.contains(a[i][j]))
{
set.add(a[i][j]);
}
else
{
System.out.println("Duplicate string found at index " + i + "," + j);
scores[i][j] -= scores[i][j];
}
}
set = new HashSet();
}
}
I know my explanation is a bit complicated, but hopefully it is understandable enough. Thanks,
Jake.
Your logic is incorrect. Your outer loop is j and inner loop is i but you're doing:
set.add(a[i][j]);
It should be the other way around:
set.add(a[j][i]);
Technically you could get an out of bounds exception if the array isn't NxN. But you can state that as a precondition.
For some reason you're also setting to 0 with:
scores[i][j] -= scores[i][j];
Why not just:
scores[i][j] = 0;
But to find duplicates within columns:
public static void findDuplicates(String a[][]) {
for (int col=0; col<a[0].length; col++) {
Map<String, Integer> values = new HashMap<String, Integer>();
for (int row=0; row<a.length; row++) {
Integer current = values.put(a[row][col], row);
if (current != null) {
scores[row][col] = 0;
scores[current][col] = 0;
}
}
}
}
How does this work?
I've renamed the loop variables to row and col. There's no reason to use i and j when row and col are far more descriptive;
Like you I assume the input array is correct as a precondition. It can be NxM (rather than just NxN) however;
I use a Map to store the index of each value. Map.put() returns the old value if key is already in the Map. If that's the case you've found a duplicate;
The current (row,col) and (current,col) are set to 0. Why subtract the score from itself rather than simply setting to 0?
if the value "a" is found 3+ times in a column then scores[current][col] will be set to 0 more than once, which is unnecessary but not harmful and makes for simpler code.
I've declared the Map using generics. This is useful and advisable. It says the Map has String keys and Integer values, which saves some casting;
It also uses auto-boxing and auto-unboxing to convert an int (the loop variable) to and from the wrapper class Integer.

Categories

Resources