Compare elements in 2d array java? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
If I have a two-dimensional array in Java:
1 0 0
0 1 0
1 0 1
And I have another of smaller or equivalent size:
1 0
0 1
How would I find matches where an area of values inside the first array is equal to the second array?
For example, if we split the first array into multiple different small arrays that each have the same dimensions as the second...
This would be the top left corner:
1 0
0 1
Here's the top right corner:
0 0
1 0
And so on...
How can I check if one of the first array's splits is equal to the second array
This is the code I use to define arrays:
public static void main(String argv[])
{
int a[][] = { {1,0,0}, {0,1,0}, {1,0,1} };
int element[][] = {{1,0}, {0,1}};
}
And then I try to use Arrays.deepEquals(Array1, Array2) to compare them.

You can cut the array at x and y by looking at the values in [x, y] to [x + 1, y + 1].
public static int[][] cut(int[][] source, int x, int y)
{
return new int[][]{
new int[]{ source[x][y], source[x + 1][y] },
new int[]{ source[x][y + 1], source[x + 1][y + 1] }
};
}
Note this function assumes your array is square. Then iterate over the large array, cutting and comparing. Since our cut function takes a 2x2 array, we stop before x and y get to the edge of the large array (Hence the x < large.length - 1).
public static boolean test(int[][] large, int[][] small)
{
for (int x = 0; x < large.length - 1; x++)
for (int y = 0; y < large[0].length - 1; y++)
{
int[][] part = cut(large, x, y);
if (Arrays.deepEquals(part, small))
return true;
}
}

Related

How the 'NOT' operator(!) works when used with methods in Java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
This is an example of using access modifiers to avoid generating exceptions:
class FailSoftArray {
private int a[];
private int errval;
public int length;
public FailSoftArray(int size, int errv) {
a = new int[size];
errval = errv;
length = size;
}
public int get(int index) {
if(indexOK(index)) return a[index];
return errval;
}
public boolean put(int index, int val) {
if(indexOK(index)) {
a[index] = val;
return true;
}
return false;
}
private boolean indexOK(int index) {
if(index >= 0 & index < length) return true;
return false;
}
}
public class TestMethod {
public static void main(String[] args) {
FailSoftArray333 fs = new FailSoftArray(5, -1);
int x;
System.out.println("\nError access message.");
for(int i = 0; i < (fs.length * 2); i++)
if(!fs.put(i, i*10))
System.out.println("Index " + i + " outside the range of the array");
for(int i =0; i < (fs.length * 2); i++) {
x = fs.get(i);
if(x != -1) System.out.print(x + " ");
else
System.out.println("Index " + i + " outside the range of the array");
}
}
}
I don't understand why in this case I have to use the operator (!) for the code to work correctly:
System.out.println("\nError access message.");
for(int i = 0; i < (fs.length * 2); i++)
if(!fs.put(i, i*10))
System.out.println("Index " + i + " outside the range of the array");
When I print it with (!) the results are what you would expect:
Error access message..
Index 5 outside the range of the array
Index 6 outside the range of the array
Index 7 outside the range of the array
Index 8 outside the range of the array
Index 9 outside the range of the array
0 10 20 30 40 Index 5 outside the range of the array
Index 6 outside the range of the array
Index 7 outside the range of the array
Index 8 outside the range of the array
Index 9 outside the range of the array
Without (!):
Error access message..
Index 0 outside the range of the array
Index 1 outside the range of the array
Index 2 outside the range of the array
Index 3 outside the range of the array
Index 4 outside the range of the array
0 10 20 30 40 Index 5 outside the range of the array
Index 6 outside the range of the array
Index 7 outside the range of the array
Index 8 outside the range of the array
Index 9 outside the range of the array
Can someone explain to me how exactly the operator (!) works in this case? Why is it needed and how does it affect the method?
The put function of FailSoftArray returns a boolean value true/false whether it was able to successfully put the new value val at index index within array a
The ! signifies a logical NOT
By using if(!fs.put(i, i*10)), you are effectively telling the compiler
if(put was NOT able to place i*10 at index i)
System.out.println("Index " + i + " outside the range of the array");
Leaving the ! out would be like saying
if(put succeeded)
//Print error
which is obviously not intended

I have a possible logic error while reversing an array [closed]

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 4 months ago.
Improve this question
I've been trying to reverse an array using a for loop while not creating a new temporary array however the array only reverses halfway.
public void reverse() {
int y = 0;
int[] values = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
for (int x = values.length - 1; x >= 0; x--) {
int placeholder = values[x];
values[y] = placeholder;
y++;
System.out.print(values[y] + " ");
}
}
Right now the method returns the values of the array. However, the value is
"1 2 3 4 5 5 4 3 2 1"
The desired output is,
"1 2 3 4 5 6 7 8 9 10".
You're reassigning some of the previously overwritten values back to the array (so you lose half of the values). Instead, you should loop to half the length of the array and swap corresponding elements.
for (int i = 0, j = values.length - 1; i < j; i++, j--) {
int temp = values[i];
values[i] = values[j];
values[j] = temp;
}
System.out.println(java.util.Arrays.toString(values));
Instead of x >= 0, the loop should be terminated as soon as x and y meet or surpass each other, or swapped values would be swapped one more time and back into their original slots.
Also did you forget to assign values[y] to values[x] within the loop body?
public void reverse(int[] values)
{
if (values.length == 0) return;
int x = values.length - 1;
int y = 0;
while (x > y)
{
// swapping
int temp = values[x];
values[x] = values[y];
values[y] = temp;
// moving ptrs
x--;
y++;
}
}
Yes,you are not supposed to directly assign, you should swap, otherwise the value to the left of the equal sign will be overwritten.Another way is to find a variable to record the value on the left side of the equal sign and assign it to the right side.

What is the efficient way of calculating sum of Bitwise AND of all subsets of an array in Java? [closed]

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 4 years ago.
Improve this question
For [1, 2, 3], all possible subsets are {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}
The sum of AND of these subsets are, 1 + 2 + 3 + 0 + 1 + 2 + 0 = 9.
this is what i have tried:
public class Main
{
static void printSubsets(int set[])
{
int n = set.length;
int total=0;
for (int i = 0; i < (1<<n); i++)
{
int sum=1;
for (int j = 0; j < n; j++)
if ((i & (1 << j)) > 0)
sum = sum & set[j];
total= total+sum;
}
System.out.print(total);
}
public static void main(String[] args)
{
int set[] = {1, 2, 3};
printSubsets(set);
}
}
but its not giving correct output
You may sum up the contribution for each bit.
Lets start with the least significant bit. To remove the contribution from other bits, we calculate number AND bit for all numbers in the set. For your example the result will be [1,0,1]. Any subset of this that contain a 0 will not give any contribution. All nonempty subset that only consist of 1’s will give 1 in contribution. In total there will be 2^n - 1 such subset each giving 1 in contribution. Same goes for the the other bit. We get [0,2,2], 3 subset each giving 2. Total 3*1 + 3*2 = 9
static void printSubsets(int[] set) {
long total = 0;
for (int bit=1; bit!=0; bit<<=1) {
int numbersWithBitSet = 0;
for (int i : set) {
if ((i&bit)!=0) numbersWithBitSet++;
}
long subsets = (1L<<numbersWithBitSet)-1;
total += bit * subsets;
}
System.out.println("Result: " + total);
}

Access a 2d array index without coordinates in Java

Lets say we have a 8 x 8 2d integer array named grid and trying to select the element 0 at [5][5]
int[][] grid = new int{{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,0,1,1},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1}};
Now the question is, is it possible to access the index of element 0 without using coordinates and just use a single number?
example: access the element 0 with the number 45, like a 1d array
I tried approaching this problem with a for loop but it is giving me out of range errors.
int x = 0;
int y = 0;
for (int i = 0;i<45;i++) {
x += 1;
if (x > grid[y].length) {
x = 0;
y += 1;
}
The code above is supposed to add x and y until it reaches the target element.
Eventually you would have to use the two indexes.
You could calculate the x and y given just a single number.
public static int getAt(int[][] matrix, int position) {
int columns = matrix[0].length; // column size, matrix has to be at least 1x1
return matrix[position / columns][position % columns];
}
public static void setAt(int[][] matrix, int position, int value) {
int columns = matrix[0].length; // column size, matrix has to be at least 1x1
matrix[position / columns][position % columns] = value;
}
Also in your example:
1) You don't need to use a for loop (and again eventually to access or modify the matrix you would have to use both indexes).
2) When y is greater or equal than the row size (8 in this case) you will receive an out of bounds exception because you only have 8 columns.
Finally the only way to access it with one index is if you transform the matrix to a 1d array.
Here you can see how:
how to convert 2d array into 1d?

How to print an int array into a horizontal arrow?

Having an array such as int[] arr = new int[]{9, 6, 5, 2, 1, 2, 6, 3, 2, 7, 3, 8, 1, 5, 4, 7}; I want to print it like this:
* Output:
* 9
* 6 1
* 5 2 2
* 2 6 7 1
* 3 3 5
* 8 4
* 7
Without the * basically that's what I am trying to do. I intended to go over the array and just use System.out.println();until I reached then "end" which would be the 7 and then go to the next line but that didn't work.
I also tried printing 9 then 6 and 1 and so on but I couldn't make it to work either, I'm at a loss here and would appreciate guidance as to how can I think this through please.
EDIT
The intermediate step I have is making the array a "block" like this:
* Intermediate Step:
* 9 6 5 2
* 1 2 6 3
* 2 7 3 8
* 1 5 4 7
It should work for an array of any size.
I think this should work
You iterate 2 times. first you get the first row and all the diagonal rows below it, and then the last row and all the diagonal rows above it. You have to create a second array though to hold this info. I assumed that the array is same size for both X and Y. 7x7, 4x4 etc. tested with 4x4 data (your data)
String[][] array2 = new String[array.length*2][array.length];
for (int mb = 0; mb < array.length; mb++) {
String p1 = array[0][mb];
array2[mb][0] = p1;
int count = 0;
for (int i=1;i<=mb;i++) {
count++;
String p2 = array[i][mb-i];
array2[mb][count] = p2;
}
}
int counter = -1;
for (int mb = array.length -1; mb > 0; mb--) {
counter++;
String p1 = array[array.length -1][mb];
array2[mb+array.length -1][counter] = p1;
for (int i=0;i<counter;i++) {
String p2 = array[array.length -2 - i][array.length -counter + i];
array2[mb+array.length -1][i] = p2;
}
}
Well lets think you have two-dimensional array (you can change your one-dimension to two-dimensional easily)
PseudoCode :
whereToGo = RIGHT;
i = 0;
j = 0;
maxX = WIDTH;
maxY = HEIGHT;
minX = 0;
minY = 0;
while (somethingLeft){
addNumberToPyramid(array[i][j]);
if (whereToGo == RIGHT){
i++;
if (maxX == i) {
whereToGo = DOWN;
minY++;
}
} else if (whereToGo == DOWN){
//Same as if you go RIGHT, but increasing "j", at the end, you decrease maxY and then goLeft
} //... other two directions
}
This is how to parse input. Similar way for adding it to pyramid. I would prefer creating another 2D array, put that directly there as pyramid and then write method for printing this array correctly :
public class Pyramid{
//initialize minX, maxX etc.
int[][] array;
whereToGo = DOWN;
int i = 0, j = 0;
//initialize array size in constructor
public void addNumberToPyramid(int value){
if (whereToGo == DOWN){
array[i][j] == value;
j++;
if (j == maxY){
whereToGo = UPRIGHT;
maxY -= 2;
} else if (whereToGo == UPRIGHT){
} //... other else if directions
}
}
}
OK, first of all: You can't print a triangle like that for every length of an array. Say for example you had that array but missing the last entry; then your triangle would be missing one element at some point. In fact, you can print such a triangle if and only if the number of elements is the square of a natural number; in your example 16 = 4^2. Now, that 4 is also the length of your longest row.
OK, now how to do it. If you look at the intermediate step
9 6 5 2
1 2 6 3
2 7 3 8
1 5 4 7
and call that arr2, you want to print arr2[0][0] in the first row, arr2[1][0] and arr2[0][1] in the second row and so on until row 4 (which is of course the root of the length of the initial array). So you can write a nested loop that counts up like that.
Then you want to print arr2[1][3], arr2[2][2] and arr2[3][1] in the next row, then arr2[2][3] an arr2[3][2] and finally in the last row just arr2[3][3]. That is most easily done in a second nested loop.
I won't give you the exact code of course as this is obviously a learning task. But I will tell you that if you have a counter i for the outer loops and a counter j for the inner ones, the indexes in the intermediate array will depend on both i and j.

Categories

Resources