Combine 2D Arrays - java

I need to figure out how to turn the 3x3 array
{{7,2,3},
{0,4,8},
{5,6,1}}
into a 9x9 array where each 3x3 section is the original array o, but each value n is n+(9*c) where c is the corresponding section. In other words, section 0, 0 (top left) should have each of its values changed to originalValue+(9*7) since the top-left section of the original array is 7. Similar with the bottom-right, but the formula would be originalValue+(9*1) since the bottom-right section of the original array is 1.
The new array should look like (just including the two sections mentioned)
{{70,65,66,0,0,0,0,0,0},
{63,67,70,0,0,0,0,0,0},
{68,69,64,0,0,0,0,0,0},
{00,00,00,0,0,0,0,0,0},//leading zeros added for easy legibility
{00,00,00,0,0,0,0,0,0},
{00,00,00,0,0,0,0,0,0},
{0,0,0,0,0,0,16,11,12},
{0,0,0,0,0,0,09,13,17},
{0,0,0,0,0,0,14,15,10}}
Now here is the hard part: I then need to repeat the process, but using this 9x9 array as the original array to get a 27x27 array, and then repeat it even more times to get a bigger array each time (81x81 then 243x243, etc.).
I have been able to get the method addAllValues() but I am stuck from going further.
public static int[][] addAllValues(int[][] data, int value2){
int value = value2 * 9;
int[][] temp = data.clone();
int[][] newData = temp.clone();
for (int i = 0; i < temp.length; i++) {
for (int j = 0; j < temp[0].length; j++) {
newData[i][j] = temp[i][j] + value;
}
}
return newData;
}
Can anyone help me with this? Thanks in advance!
Here is what I have tried:
public static int[][] gen(int amount) {
if (amount == 0) {
return normal;
} else {
int[][] newArray = gen(amount-1);
int[][] temp = new int[newArray.length*3][newArray.length*3];
int[][][][] newArrays = {{addAllValues(newArray,7),addAllValues(newArray,2),addAllValues(newArray,3)},{addAllValues(newArray,0),addAllValues(newArray,4),addAllValues(newArray,8)},{addAllValues(newArray,5),addAllValues(newArray,6),addAllValues(newArray,1)}};
for (int i = 0; i < temp.length; i++) {
for (int j = 0; j < temp.length; j++) {
int x=0,y=0;
if (0 <= i && i < 3){
x = 0;
} else if (3 <= i && i < 6){
x = 1;
} else if (6 <= i && i < 9){
x = 2;
}
if (0 <= j && j < 3){
y = 0;
} else if (3 <= j && j < 6){
y = 1;
} else if (6 <= j && j < 9){
y = 2;
}
temp[i]
[j] = newArrays[x]
[y]
[i]
[j];
}
}
return temp;
}
}

Ok this is pretty basic.
You have a square matrix A.
[a b c]
A = [e f g]
[h i j]
You copy the matrix 3 times to the right (horizontally) to get [A A A], and then you copy the strip 3 times to the bottom (vertically) to get a square strip of matrices
[A A A]
B = [A A A]
[A A A]
The new matrix is 3 times bigger per dimension, or totally 9 times bigger (per "area"). Now what you need to do is modify each submatrix -- add the corresponding element from the original matrix. You need to find the indices of the submatrix (the indices of the subsections), and use those same indices in the original matrix to get the corresponding scalar.
[9*A(0,0)+A 9*A(0,1)+A 9*A(0,2)+A]
[9*A(1,0)+A 9*A(1,1)+A 9*A(1,2)+A]
[9*A(1,0)+A 9*A(1,1)+A 9*A(1,2)+A]
The last link we need to set is to know which element in the new matrix B corresponds to which section.
B is 3 times bigger, e.g. B[0..8, 0..8] so if we divide the indices of element in B by 3 (integer division) we get it's section and this the indices of the scalar in A.
We say an element B(r,c) lays in section (i,j)=(r/3, c/3) and thus this element shall be modified with A(i,j). This last sentence pretty much sums it up.

Related

How can I print an multidimensional array element by specifying the array position with an index?

I'm trying to print an element of a 2D array by designating it's location with an index. Say, I want to print location 3 which would be String[1][0] for my array.
String[][] fruit = new String[2][2];
fruit[0][0] = "apple"; //position 1
fruit[0][1] = "banana"; //position 2
fruit[1][0] = "pear"; //position 3
fruit[1][1] = "melon"; //position 4
I would like to call fruit[1][0] position 3 so when I ask to print "position 3" it gives me "pear".
What you're looking for is obviously the literal position of a cell since arrays start from an index value of 0. You also need to keep in mind that a 2D Array can possibly have different number of columns for any given row. The first and second rows for example may have 4 columns, the fifth row might have 6 columns, and the sixth, seventh row may have 4 columns again. Unless you know for sure that all columns within the Array are indeed fixed to a specific length (a "square" 2D Array), I can't see an advantage to this scheme.
Never the less, this can be easily done with two for loops (one nested within the other), for example:
String[][] array = {
{"cell 1", "cell 2"}, // Row 1 (index 0)
{"cell 3", "cell 4", "cell 5"}, // Row 2 (index 1)
{"cell 6", "cell 7"}}; // Row 3 (index 2)
int yourDesiredCell = 5;
int cellCount = 0;
boolean found = false;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
cellCount++;
if (cellCount == yourDesiredCell) {
System.out.println(array[i][j]);
found = true;
break;
//return array[i][j];
}
}
if (found) {
break;
}
}
You could also place this into a class method, for example:
public static String getCellData(String[][] array, int yourDesiredCell) {
int cellCount = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
cellCount++;
if (cellCount == yourDesiredCell) {
return array[i][j];
}
}
}
return null;
}
Another method that could be handy is retrieving the total number of actual cells contained within the 2D Array (if you don't already know):
public static int getTotalCellCount(String[][] array) {
int cellCount = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
cellCount++;
}
}
return cellCount;
}
What I got from your question was that there is a multi-dimensional array A of size say nxm where n is number of rows and'mis number of columns. You want to get let say 1st element which will beA[0][0], but you don't know how to convert 1` into indices for the array.
Lets do this for a 2d array A of size nxm, then you can extend it to 3d etc too. Remember that each A[i] is an array of'melements, hence the position of row where the element isx/m, i=x/m. No need to make it 0-indexed because the integer division of java does that for you. If i>=n`, then we should say element is not present.
Now you have to decide the position of the element in m elements. Hence j or position of the column is x%m. This will give you index b/w 0 and m-1 which is correct range of j, but for an element in the first place it should give 0, but it's giving 1. Hence it js not 0-indexed. So j= x%m -1 but for (m-1)th element its giving
-1 as x would be divisible by m or x%m=0. So use ternary operator here, j = x%m-1 < 0 ? m-1 : x%m-1.
i = x/m ;
if(i<n){
j = x%m -1 < 0 ? m-1 : x%m -1 ;
}else{
System.out.println("Element " +m+" does not exist") ;
}
I would like to suggest another approach with a time complexity O(n).
public String getByPosition(int pos,String[][] mulArr){
int row,col;
int temp = pos;
while(temp % mulArr.length != 0)temp++;
row = (temp / mulArr.length) - 1;
col = ((pos % mulArr[0].length) - 1 < 0) ? mulArr[0].length - 1 : (pos % mulArr[0].length) - 1;
return mulArr[row][col];
}

Java: Get two arrays and if length of one is smaller than the length of the other, replace missing values with 1

Hi so the question is: if array1 is smaller than array2 replace the missing values with number 1, so that array1 missing values can be multiplied by array2 as if they were the number 1?
Here is my idea of how one could go about it... help with the correct syntax? Best way to go about it?
public addMissingNumber(int[] array1, int[] array2){
for (int 1 = array1.length; i > 0; i--)
for(int j = array2.length; j > 0; j--){
if(array1[i] < array2[j]) {
array1[i].[j] = 1;
/*what I want to say here is that the empty position of the array1[i] that is equivalent to the position of array2[j] that contains a number should become the number 1. How can this be done?*
}
}
}
Here is the original exam question, the second part is what I'm having trouble with:
Write a method called add that takes two arrays v, w of type double as its parameters. The method should return a new array of double formed by adding the corresponding elements of the input arrays. That is to say, element i of the output array should be equal to v[i]+w[i].
If the lengths of v and w are different, the output array should have as length the maximum of (v.length, w.length).
The missing elements of the shorter array should be assumed to be one in the calculation of the output.
Try this:
public double[] addMissingNumber(double[] array1, double[] array2){
double[] arraynew = new double[max(array1.length,array2.length)];
int i = 0;
int j = 0;
int k = 0;
while ( i < array1.length && j < array2.length) {
arraynew[k] = array1[i] + array2[j];
i++;
j++;
k++
}
while(i < array1.length) {
arraynew[k] = array1[i]+1;
i++;
k++;
}
while(j < array2.length){
arraynew[k] = array2[j]+1;
j++;
k++;
}
return arraynew;
}
You don't need to put 1 into the array. Just traverse through both the arrays till they are equal and store the sum . After that the longer array is traversed and 1 is added to it everytime.

Find node neighbors in 2d array

Assume that I have the following (n * n) array:
1 2 3 4
5 6 7 8
9 a b c
d e f g
I want to write a function that finds the neighbor nodes of a given node. For example, for node 1, it will return an array with 2, 6, and 5. For node "a", it will return a vector with node 5, 6, 7, b, f, e, d, and 9. The order does not matter. I tried to do this with only using if-statements, but it turned into a nightmare really quick.
Whats the best way to approach this problem?
// assume (x,y) is position in array you want to get neighbours from
// assume 'array' is your array with x first and then y
// assume T is type of your array stuff
ArrayList<T> list = new ArrayList<T>();
for (int i = x - 1; i <= x + 1; i++) {
for (int j = y - 1; j <= y + 1; j++) {
// check if (i,j) is in array bounds
if (i >= 0 && j >= 0 && i < array.length() && j < array[i].length()) {
// the point isn't its own neighbour
if (i != x && j != y)
list.add(array[i][j]);
}
}
}
return list.toArray();
EDIT: As your Array is n*n big you don't have to use array.length(), but this way it will work for all kind of array.
you can use for loops, let assume that (i,j) is the location of your element, mat is your array
mat[n][n]
int res[8];
int x = 0;
for (int k = i - 1 ; k < 2 ;k++)
for(int t = j-1 ; j <2 ;j++)
if ((k > 0) && (t > 0) && (t<n) && (k < n))
res[x++] = mat[k][t];

Comparing two arrays. Wrong return value (1)

I made this method that compares the numbers of two arrays and then returns how many numbers are equal to each other, but no matter how many numbers are equal, the method returns the value 1 every time.
(both arrays are the same length).
public static void main(String[] args) {
int a [] = {1, 4, 6, 7, 8, 10, 13};
int b [] = {1, 2, 3, 4, 5, 6, 7};
equal(a,b);
}
public static int equal(int[] a, int[] b){
int j = 0;
for(int i = 0; i< a.length-1;i++){
if(a[i] == b[i]){
j++;
}
}
System.out.println(j);
return j;
}
Your code is finding the number that are equal at the same index.
There are several ways you can find the size of the intersection.
A simple but O(m*n) implementation would be to iterate over all elements of b for each element of a.
If the arrays are sorted, you could use separate indexes for the two arrays, advancing each when it can no longer match. This would be O(m+n). (If they're not sorted, you could sort them first, for a cost of O(m log m + n log n ).
If each array has no duplicate members, another way is to compute the size of the intersection is from the size of the set difference. An example of this is at http://ideone.com/6vLAfn. The key part is to convert each array to a set, and determine how many members are in common by removing one set from another.
int aSizeBefore = setA.size();
setA.removeAll( setB );
int aSizeAfter = setA.size();
return aSizeBefore - aSizeAfter;
You should use a nested for loop if you want to check if any single number in array a is also in array b.
e.g.
int numMatches = 0;
for (int i = 0; i < a.length; ++i)
{
for (int j = 0; j < b.length; ++j)
{
if (a[i] == b[j])
++numMatches; //Naive, as obviously if the same number appears twice in a it'll get counted twice each time it appears in b.
}
}
The current code just checks the elements at the same index match i.e
1 == 1 // Yes, increment j
4 == 2 // Nope
6 == 3 // Nope
7 == 4 // Nope
8 == 5 // Nope
10 == 6 // Nope
13 == 7 // Nope
Elements with same values might be in different indexes. You can write as following, assuming the arrays are sorted:
public static int equal(int[] a, int[] b) {
int count = 0;
for(int i = 0; i < a.length - 1; i++) {
for(int j = 0; i < b.length - 1; j++) {
if (a[j] < b[j]) {
// we came to the part where all elements in b are bigger
// than our selected element in a
break;
}
else if (a[j] == b[j]) {
count++;
}
}
}
System.out.println(count);
return count;
}
If you can't guarantee that the arrays are sorted, you can remove the if-block and remove the else-if's else from the loop.
If you want to know how many numbers are present in both arrays and there is a guarantee that they are ordered, you should try the following:
public static int equal(int[] a, int[] b) {
int j, result = 0;
int lastFound = 0;
for (int i = 0; i < a.length - 1; i++) {
for (j = lastFound; j < b.length; j++) {
if (a[i] == b[j]) {
result++;
lastFound = j;
break;
} else {
if (a[i] < b[j]) break;
}
}
}
return result;
}
Using the variable lastFound will speed your loops, but it is only helpful if the arrays are ordered, as your example indicates.

Java Sudoku Squares 3x3 Checking Validity

I'm working on a Java program that checks if a sudoku puzzle is solved or not. I have finished the horizontal and vertical number check part. But when trying to check squares, I can't do anything. Here is how my check system works.
This is what I want to make. Hope someone helps because I'm on a hard situation with square check.
int[][] SudokuBoard = new int[9][9];
// I didn't wrote the sudoku board completely hope you understood how sudoku table looks like.
public static boolean checkSquares(int[][] SquareBoard) {
int retr = false;
int loop = 0;
int[] extraboard = new int[9];
int[] truelist ={1,2,3,4,5,6,7,8,9};
for(int i = 1; i <=9 ; I++) {
//here , extraboard will have the numbers in " i " numbered sudoku square.( i is like first //,second)
Arrays.sort(extraboard);
for(int j = 0; j < 9; j++) {
if(extraboard[j] == truelist[j])
loop += 1;
}
extraboard = new int[9];
}
if(loop == 81)
retr == true;
return retr;
}
You could do
int count = 0;
for(int k = 0; k < 9; k++) {
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
extraboard[count++] = SquareBoard[i+3*k/3][j+k%3*3];
}
}
Arrays.sort(extraboard);
for(int j = 0; j < 9; j++) {
if(extraboard[j] == truelist[j])
loop += 1;
}
extraboard = new int[9];
count = 0;
}
The actual formula to calculate the location in the box is quite simple. As the board is split into rows and column, getting the location of the row and column needs to get offset based on the location of the box in the full area.
i here counts the index within the box of the row. As each row of boxes has a length of 3 in a 9x9 sudoku we need to increase the row number by 3 each time we get 3 boxes in. To figure out and only add 3 we can use some integer division.
For example:
i+i.length*k/i.length
This is obviously an syntax error as i doesn't have length but can consider it as the limit of i in the loop (in this case 3).
This would then get the current row in the box (the first i) and add that to the offset of boxes in the sudoki. That is for every 3 boxes k/i.length becomes 1 more, and we then multiply that with 3 to get the offset of 3.
In the column part we have a bit of an bigger issue as we need to offset it for every 3 we move left in the array and reset it when we get back to boxes on the far left.
So the forumla would become
j + (k%i.length)*j.length
This would give us the column in the box we are in, then we offset by the box location with k%i.length. The reason we use the i.length and not the j.length is that we need to calculate the offset by rows and then offset it by the length of the box column wise.
With this you can then apply to this to any size board. 2x2, 2x3, 3x2, 3x3 or bigger even.
public static boolean checkSquares(int[][] SquareBoard) {
int i=0, extraboard=0;
for (;i<9;i++,extraboard=0) {
for (int j=0;j<9;j++)
extraboard+=1<<(SquareBoard[i/3*3+j/3][i%3*3+j%3]-1);
if (extraboard!=(1<<9)-1) // 511, binary(511) = 111111111
break;
}
return i==9;
}
This is a solution i came up with. it uses 4 nested loops but the time complexity is still O(n^2). Basically i check the first 3 boxes on top, then the 3 boxes in the middle, then the last 3 boxes.
for (int l = 0; l < 9; l+= 3){
for (int i = 0; i < 9; i += 3){
HashSet<Character> set = new HashSet<>();
for (int j = l; j < l+3; j++){
for (int k = i; k < i+3; k++){
if (!set.contains(board[j][k])){
if (board[j][k] != '.')
set.add(board[j][k]);
}
else
return false;
}
}
}
}
return true;
and note that the sudoku might not be complete, and the missing numbers are replaced by ' . '

Categories

Resources