so I'm trying to make a program that rotates a cube shaped grid 90 degree to the right.
The problem I encountered is that temp values (temp1, temp2, temp3, temp4) that I declared in the method keep changes during the process of method.
Assume there is a cube grid,
1 2 3
4 5 6
7 8 9
as I declared
int[] temp1 = grid[0]; in the method
temp1 should be fixed as {1, 2, 3}.
However, when this part of code executes,
//rotate 90 degree to right
//row 0 ==
for (int i = 0; i < grid[0].length; i++)
{
grid[0][i] = temp2[i];
}
temp1's value changes as {7, 4, 1} which I didn't not expect
It is really confusing because temp value usually don't change.
Can anyone give me advice to fix this issue?
import java.util.Scanner;
public class a
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int numLine = Integer.parseInt(input.nextLine());
int[][] grid = new int[numLine][numLine];
String[] lines = null;
for (int i = 0; i < numLine; i++)
{
lines = input.nextLine().split(" ");
for (int j = 0; j < numLine; j++)
{
grid[i][j] = Integer.parseInt(lines[j]);
}
}
rotate(grid);
for (int[] i : grid)
{
for (int j : i)
{
System.out.print(j + " ");
}
System.out.println("");
}
input.close();
}
public static void rotate(int[][] grid)
{
//row 0
int[] temp1 = grid[0];
//column 0
int[] temp2 = new int[grid[0].length];
int c = 0;
for (int i = grid[0].length-1; i >= 0; i--)
{
temp2[c] = grid[i][0];
c++;
}
c = 0;
//row last
int[] temp3 = grid[grid[0].length-1];
//column last
int[] temp4 = new int[grid[0].length];
for (int i = grid[0].length-1; i >= 0; i--)
{
temp4[c] = grid[i][grid[0].length-1];
c++;
}
c = 0;
//rotate 90 degree to right
//row 0 ==
for (int i = 0; i < grid[0].length; i++)
{
grid[0][i] = temp2[i];
}
//column last ==
for (int i = 0; i < grid[0].length; i++)
{
grid[i][grid[0].length-1] = temp1[i];
}
//row last ==
for (int i = 0; i < grid[0].length; i++)
{
grid[grid[0].length-1][i] = temp4[i];
}
//column 0 ==
for (int i = 0; i < grid[0].length; i++)
{
grid[i][0] = temp3[i];
}
}
}
Related
I have a piece of program that i have to fill. It is supposed to count adjacent numbers in a 5 by 5 binary matrix. For example a matrix like this:
0 1 1 1 0
1 0 0 0 1
1 0 0 0 0
1 0 0 1 0
0 1 0 1 0
Should return 8, you can only move horizontally or vertically.
Here is the code that generates these said matrices and it can't have any modifications after i'm done.
import java.util.Random;
public class Test {
public static void main(String[] args) {
final Random r = new Random();
for (int kerrat = 0; kerrat < 10; kerrat++) {
int[][] alkioTaulukko = new int[5][5];
System.out.println("Matriisin");
for (int i = 0; i < alkioTaulukko.length; i++) {
System.out.print("");
for (int j = 0; j < alkioTaulukko[i].length; j++) {
alkioTaulukko[i][j] = r.nextInt(2);
System.out.print("" + alkioTaulukko[i][j] + " ");
}
System.out.println("");
}
System.out.print("suurimman yhtenäisen alueen koko on ");
System.out.println(laskeSuurinAlue(alkioTaulukko));
System.out.println("");
}
}
}
And finally here is my solution to the problem.
static int laskeSuurinAlue(int[][] matriisi) {
int vierekkaiset = 0;
int rivi = matriisi.length;
int palkki = matriisi[0].length;
for (int r = 0; r < rivi; r++)
{
for (int p = 0; p < palkki; p++)
{
if ((p+1 < palkki) && (matriisi[r][p] == matriisi[r][p+1]))//loops through the rows
vierekkaiset++;
if ((r+1 < rivi) && (matriisi[r][p] == matriisi[r+1][p]))//loops through the columns
vierekkaiset++;
}
}
return vierekkaiset;
}
What happens is that my solution always brings up too big results and i'm failing to see any pattern between each run. However if i use a smaller matrix like this:
int[][] array = {{1, 0, 1}, {0, 1, 1}, {0, 1, 0}};
The result is correctly 4.
And if i use a bigger one like this:
int[][] arr = {{1,0,1,1,0},
{0,0,1,0,0},
{0,0,1,0,1},
{1,1,1,0,1},
{0,0,1,0,0}
};
The result is always 20.
Finally here is my code at its current state:
import java.util.Random;
import static java.util.Arrays.deepToString;
public class Test {
public static void main(String[] args) {
final Random r = new Random();
int[][] array = {{1, 0, 1}, {0, 1, 1}, {0, 1, 0}};
int[][] arr = {{1,0,1,1,0},
{0,0,1,0,0},
{0,0,1,0,1},
{1,1,1,0,1},
{0,0,1,0,0}
};
for (int kerrat = 0; kerrat < 10; kerrat++) {
int[][] alkioTaulukko = new int[5][5];
System.out.println("Matriisin");
for (int i = 0; i < alkioTaulukko.length; i++) {
System.out.print("");
for (int j = 0; j < alkioTaulukko[i].length; j++) {
alkioTaulukko[i][j] = r.nextInt(2);
System.out.print("" + alkioTaulukko[i][j] + " ");
}
System.out.println("");
}
System.out.print("suurimman yhtenäisen alueen koko on ");
System.out.println(laskeSuurinAlue(arr));//Change to arr,array or alkioTaulukko to run the code with different matrices
System.out.println(deepToString(arr));
System.out.println("");
}
}
static int laskeSuurinAlue(int[][] array) {
int counter = 0;
int rowLimit = array.length;
int colLimit = array[0].length;
for (int r = 0; r < rowLimit; r++)
{
for (int c = 0; c < colLimit; c++)
{
if ((c+1 < colLimit) && (array[r][c] == array[r][c+1]))
counter++;
if ((r+1 < rowLimit) && (array[r][c] == array[r+1][c]))
counter++;
}
}
return counter;
}
}
You're couting the same entry more than once.
Use this code
static int laskeSuurinAlue(int[][] array) {
int counter = 0;
int rowLimit = array.length;
int colLimit = array[0].length;
for (int r = 0; r < rowLimit; r++)
{
for (int c = 0; c < colLimit; c++)
{
if (array[r][c] == 0) {
continue;
}
int sum = array[r][c];
sum += (r + 1 < rowLimit) ? array[r+1][c] : 0;
sum += (c + 1 < colLimit) ? array[r][c+1] : 0;
sum += (r - 1 >= 0 ) ? array[r-1][c] : 0;
sum += (c - 1 >= 0) ? array[r][c-1] : 0;
if (sum > 1) {
counter++;
}
}
}
return counter;
}
I'm using a four dimensional array write a Sudoku solver in Java, where the dimensions describe the location of the cell on the board and the values assigned to them are the possible numbers that the cell can be. Sudoku Wikipedia, for reference
I have written methods for printing a Unicode art representation of the board for clarity, as well as a method to print all of the choices for each cell on the board. These methods work. However, my method to eliminate singletons from other cells in the single's row, column, and box does not work as intended (removing from unknown cells all known cells in the same row/column/box). Note that the top left cell (choiceArray[0][0][0][0]) should be the string 467 but is instead 23478. Here is the code I wrote. Sudoku boards are entered as 81-character strings, where 0's represent empty cells in the initial board.
(In addition to answering this question, stylistic/procedural advice from more experienced programmers than myself would be appreciated, as I'm very much a beginner)
public class SudokuSolver {
public static void main(String[] args) {
String initialBoard = "020501090800203006030060070001000600540000019002000700090030080200804007010907060";
//Parsing the input to make sure that it is valid
if (!(initialBoard.matches("[0-9]+") && initialBoard.length() == 81)) {
System.err.println("Input board was not valid.");
System.exit(0);
}
//Generating the sudoku board
printBoard(initialBoard);
//Generating an array for the given information
String[][][][] choiceArray = new String[3][3][3][3];
for(int i = 0; i < 3; i++) { //row of box
for(int j = 0; j < 3; j++) { //column of box
for(int k = 0; k < 3; k++) { //row in box
for(int l = 0; l < 3; l++) { //column in box
int cellNumber = 27 * i + 3 * j + 9 * k + l;
char cellContents = initialBoard.charAt(cellNumber);
if(cellContents == '0') {
choiceArray[i][j][k][l] = "123456789";
}
else {
choiceArray[i][j][k][l] = Character.toString(cellContents);
}
}
}
}
}
//Removing singletons
while(!(puzzleIsSolved(choiceArray))) {
boolean boardChanges = false;
for(int i = 0; i < 3; i++) { //row of box
for(int j = 0; j < 3; j++) { //column of box
for(int k = 0; k < 3; k++) { //row in box
for(int l = 0; l < 3; l++) { //column in box
if(choiceArray[i][j][k][l].length() == 1) {
String solvedCell = choiceArray[i][j][k][l];
//Removing choice from row (i, k constant)
for(int a = 0; a < 3; a++) {
for(int b = 0; b < 3; b++) {
if(a != j && b != l) {
if(choiceArray[i][a][k][b].contains(solvedCell)) {
choiceArray[i][a][k][b] = removeChoice(choiceArray[i][a][k][b], solvedCell);
boardChanges = true;
}
}
}
}
//Removing choice from column (j, l constant)
for(int a = 0; a < 3; a++) {
for(int b = 0; b < 3; b++) {
if(a != i && b != k) {
if(choiceArray[a][j][b][l].contains(solvedCell)) {
choiceArray[a][j][b][l] = removeChoice(choiceArray[a][j][b][l], solvedCell);
boardChanges = true;
}
}
}
}
//Removing choice from box (i, j constant)
for(int a = 0; a < 3; a++) {
for(int b = 0; b < 3; b++) {
if(a != i && b != j) {
if(choiceArray[a][b][k][l].contains(solvedCell)) {
choiceArray[a][b][k][l] = removeChoice(choiceArray[a][b][k][l], solvedCell);
boardChanges = true;
}
}
}
}
}
}
}
}
}
if(!boardChanges) {
break;
}
}
System.out.println(choiceArray[0][0][0][0]);
//expected: 467
//actual: 23478
}
//Printing the current state of the sudoku
public static void printBoard(String input) {
String rowA = "╔═══╤═══╤═══╦═══╤═══╤═══╦═══╤═══╤═══╗";
String rowB = "╟───┼───┼───╫───┼───┼───╫───┼───┼───╢";
String rowC = "╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣";
String rowD = "╚═══╧═══╧═══╩═══╧═══╧═══╩═══╧═══╧═══╝";
input = input.replaceAll("0", " ");
System.out.println(rowA);
for(int row = 0; row < 9; row++) {
for(int box = 0; box < 3; box++) {
System.out.print("║");
for(int cell = 0; cell < 3; cell++) {
System.out.print(" " + input.charAt(9 * row + 3 * box + cell) + " ");
if(cell != 2) {
System.out.print("│");
}
}
}
System.out.println("║");
if(row % 3 == 2 && row != 8) {
System.out.println(rowC);
}
else if(row != 8){
System.out.println(rowB);
}
else {
System.out.println(rowD);
}
}
}
//Print all possible choices in all cells in sudoku (good for debugging)
public static void printAllChoices(String[][][][] choiceArray) {
for(int i = 0; i < 3; i++) { //row of box
for(int k = 0; k < 3; k++) { //row in box
for(int j = 0; j < 3; j++) { //column of box
for(int l = 0; l < 3; l++) { //column in box
int cellNumber = 27 * i + 3 * j + 9 * k + l + 1;
System.out.println(cellNumber + ": " + choiceArray[i][j][k][l]);
}
}
}
}
}
//Check if all cells only have one choice left
public static boolean puzzleIsSolved(String[][][][] choiceArray) {
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
for(int k = 0; k < 3; k++) {
for(int l = 0; l < 3; l++) {
if(choiceArray[i][j][k][l].length() > 1) {
return false;
}
}
}
}
}
return true;
}
//Removing choice from cell
public static String removeChoice(String initialChoices, String choiceToRemove) {
String finalChoices = "";
for(int i = 0; i < initialChoices.length(); i++) {
if(initialChoices.charAt(i) != choiceToRemove.charAt(0)) {
finalChoices += initialChoices.charAt(i);
}
}
return finalChoices;
}
}
I need to have each cell in the firstArray become the sum of all adjacent cells then dump that answer into secondArray.
Example:
Initial array with random numbers:
3 5 11
5 9 14
1 2 8
Computed array:
19 42 41
20 49 48
33 62 44
3 spot([0][0]) is 5 + 9 + 5 = 19, and so on. Here's what I have:
public class ProcessArray {
private int rows;
private int columns;
private int [][] firstArray;
private int [][] secondArray;
public ProcessArray(int rows, int columns) {
this.rows=rows;
this.columns=columns;
firstArray = new int[rows][columns];
secondArray = new int[rows][columns];
initializeArray(firstArray, secondArray);
randomlyFillArray(firstArray);
System.out.println("Initial array with random numbers: ");
printArray(firstArray, secondArray, rows, columns);
getFirstArray(firstArray);
System.out.println("Computed array:");
computeArrayValues(firstArray);
}
private void initializeArray(int firstArray[][], int secondArray[][]){
for(int i = 0; i <firstArray.length; i++){
for (int j =0; j<firstArray[i].length; j++){
firstArray[i][j] = (0);
}
}
for(int i = 0; i <secondArray.length; i++){
for (int j =0; j<secondArray[i].length; j++){
secondArray[i][j] = (0);
}
}
}
public void randomlyFillArray(int firstArray[][]){
for(int i = 0; i <firstArray.length; i++){
for (int j =0; j<firstArray[i].length; j++){
firstArray[i][j] = (int)(Math.random()*15);
}
}
}
//here's where I try to have it add, I don't know what loop to have it run to go to each spot in the `firstArray`:
public void computeArrayValues(int firstArray[][]){
int x=1;
int y=1;
int sum;
int topLeft = firstArray[x-1][y-1];
int top = firstArray[x][y-1];
int topRight = firstArray[x+1][y-1];
int midLeft = firstArray[x-1][y];
int midRight = firstArray[x+1][y];
int botLeft = firstArray[x-1][y+1];
int bot = firstArray[x][y+1];
int botRight = firstArray[x+1][y+1];
secondArray[0][0]= (bot+botRight+midRight);
for (x=0; x<firstArray.length; x++){
for(y=0; y<firstArray.length; y++){
secondArray[x][y] = (topLeft+top+topRight+midLeft+midRight+botLeft+bot+botRight);
}
}
System.out.println(secondArray[x][y]);
}
public void printArray(int firstArray[][], int secondArray[][], int rows, int columns){
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
System.out.printf(String.format("%4s", firstArray[i][j]));
}
System.out.println();
}
}
public int[][] getFirstArray(int array[][]){
array = firstArray;
return array;
}
public int[][] getSecondArray(int array[][]){
array = secondArray;
return array;
}
}
Presuming you are looking for suggestions on alternative approaches, I would suggest encapsulating cell coordinates and using streams of cells instead of iteration. This assumes java 8 (naturally):
class Cell {
private final int row;
private final int col;
private Cell(int row, int col) {
this.row = row;
this.col = col;
}
public static Stream<Cell> streamCells(int rows, int cols) {
return IntStream.range(0, rows)
.flatMap(row -> IntStream.range(0, cols)
.flatMap(col -> new Cell(row, col)));
}
public Stream<Cell> streamAdjacentCells(int rows, int cols) {
return IntStream.range(row - 1, row + 1)
.flatMap(row -> IntStream.range(col - 1, col + 1)
.flatMap(col -> new Cell(row, col)))
.filter(cell -> cell.row >= 0 && cell.col >= 0)
.filter(cell -> cell.row < rows && cell.col < cols)
.filter(cell -> cell.row != this.row && cell.col != this.col);
}
public int getValue(int[][] array) {
return array[row][col];
}
public void setValue(int[][] array, int value) {
array[row][col] = value;
}
}
Then the code to set adjacent values quite simple:
int[][] destination = new int[rows][cols];
Cell.streamCells(rows, cols)
.forEach(cell -> setValue(
destination,
cell.streamAdjacentCells(rows, cols)
.mapToInt(adj -> getValue(source, adj))
.sum()));
This will fulfill the stated requirement, but running the program with the example data will output:
19 42 28
20 49 35
16 37 25
That would be the correct output for a sum of all adjacent cells (let me know if I misunderstood the question).
public class ArraySum {
static int[][] sum(int array[][]) {
// Asuming square arrays
int size = array.length;
int result[][] = new int[size][size];
// For every cell in the table
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
// Iterate the neighbors
for (int n = -1; n <= 1; n++) {
for (int m = -1; m <= 1; m++) {
// Discard the cell
if (n == 0 && m == 0) {
continue;
}
int ii = i - n;
int jj = j - m;
// Check if the neighbor coordinates are
// inside of the array bounds
if (ii >= 0 && ii < size && jj >= 0 && jj < size) {
result[i][j] += array[ii][jj];
}
}
}
}
}
return result;
}
public static void main(String... args) {
int a[][] = { {3, 5, 11},
{5, 9, 14},
{1, 2, 8} };
int r[][] = sum(a);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.printf("%d ", r[i][j]);
}
System.out.println();
}
}
}
Yesterday I asked a very similar question and I kind of messed up with asking it.
I need to pass an array to a method and inside of that method I need to swap the rows around so if it's
1 2 3
3 2 1
2 1 3
it needs to be
3 2 1
1 2 3
3 1 2
With the code I have right now it swaps the last column to the first column spot correctly then it puts the column that's supposed to be last.
3 1 2
1 3 2
3 2 1
Also, it needs to stay a void because I need to be modifying the original array so I can't set it as a temp array but I can use a temp integer to store.
Here is the code I have right now that's sort of working
public static void reverseRows(int[][] inTwoDArray)
{
for (int row = 0; row < inTwoDArray.length; row++)
{
for (int col = 0; col < inTwoDArray[row].length; col++)
{
int tempHolder = inTwoDArray[row][col];
inTwoDArray[row][col] = inTwoDArray[row][inTwoDArray[0].length - 1];
inTwoDArray[row][inTwoDArray[0].length - 1] = tempHolder;
}
}
}
any help would be great, I'm running out of hair to pull out! Thanks!
First, how to reverse a single 1-D array:
for(int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
}
Note that you must stop in half of your array or you would swap it twice (it would be the same one you started with).
Then put it in another for loop:
for(int j = 0; j < array.length; j++){
for(int i = 0; i < array[j].length / 2; i++) {
int temp = array[j][i];
array[j][i] = array[j][array[j].length - i - 1];
array[j][array[j].length - i - 1] = temp;
}
}
Another approach would be to use some library method such as from ArrayUtils#reverse():
ArrayUtils.reverse(array);
And then again put into a cycle:
for(int i = 0; i < array.length; i++){
ArrayUtils.reverse(array[i]);
}
I guess this the easiest approach, tried and tested
For instance, you have
1 2
3 4
and you want
2 1
4 3
You can reverse the loop, without any extra space or inbuilt function.
Solution:
for(int i =0;i<arr.length;i++) //arr.length=no of rows
{
for(int j = arr[i].length-1;j>=0;j--)//arr[i].length=no of col in a ith row
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
Not sure if I didn't confuse what array stores the rows and which one the columns.... but this should work (long time since I've done Java last, so be nice to me when spotting any errors please ^^):
public static void reverseRows(int[][] array)
{
for (int i = 0 ; i < array.length ; i++) { // for each row...
int[] reversed = new int[array[i].length]; // ... create a temporary array that will hold the reversed inner one ...
for(int j = 0 ; j < array[i].length ; j++) { // ... and for each column ...
reversed[reversed.length - 1 - j] = array[i][j]; // ... insert the current element at the mirrored position of our temporary array
}
array[i] = reversed; // finally use the reversed array as new row.
}
}
Java Code :-
import java.util.Scanner;
public class Rev_Two_D {
static int col;
static int row;
static int[][] trans_arr = new int[col][row];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
row = m;
int n = sc.nextInt();
col = n;
int[][] arr = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
arr[i][j] = sc.nextInt();
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
for (int j = 0; j < arr.length; j++) {
for (int i = 0; i < arr[j].length / 2; i++) {
int temp = arr[j][i];
arr[j][i] = arr[j][arr[j].length - i - 1];
arr[j][arr[j].length - i - 1] = temp;
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Reverse of two D array - Print your two D array in reverse order
public void reverse(){
int row = 3;
int col = 3;
int[][] arr = new int[row][col];
int k=0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++,k++) {
arr[i][j] = k;
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
for (int i = arr.length -1; i >=0 ; i--) {
for (int j = arr.length -1; j >=0 ; j--) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int [][] a={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a.length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
System.out.println("***************************");
for(int i=0 ; i<a.length;i++)
{
for(int j=a.length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
}
Reverse 2 D Array
public static void main(String[] args) {
int a[][] = {{1,2,3},
{4,5,6},
{8,9,10,12,15}
};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a[i].length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
for(int i=0 ; i<a.length;i++)
{
for(int j=a[i].length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
I need to write a short program on how to add two matrices.. The first matrix should look like this:
1 2 3 4 5 6 7 8 9 10
11 12 13.......19 20
21................30
31................40
41................50
etc..
91...............100
But I don't really come to a solution how to increment the first array.. :S
Here is what I got so far:
package uebung05;
public class MatrixAddition
{
public static void main(String[] argv)
{
int firstArray[][] = new int[10][10];
int secondArray[][] = new int[10][10];
int ergArray[][] = new int[10][10];
System.out.println("Matrix 1\n----------------------------");
// Inkrementieren der ersten Matrix
for(int row = 0; row < firstArray.length; row++)
{
for(int column = 0; column < firstArray[row].length; column++)
{
// Increment Array here???
System.out.print(firstArray[row][column] + " ");
}
System.out.println();
}
System.out.println("\nMatrix 2\n----------------------------");
// Dekrementieren der zweiten Matrix
for(int row = 0; row < secondArray.length; row++)
{
for(int column = 0; column < secondArray[row].length; column++)
{
// Array mit Werten befüllen
secondArray[row][column] = column + 1;
System.out.print(secondArray[row][column] + " ");
}
System.out.println();
}
System.out.println("\nAddition beider Matrizen\n----------------------------");
// Addition firstArray & secondArray
for(int row = 0; row < ergArray.length; row++)
{
for(int column = 0; column < ergArray[row].length; column++)
{
// Addition
ergArray[row][column] = firstArray[row][column] +
secondArray[row][column];
System.out.print(ergArray[row][column] + " ");
}
System.out.println();
}
}
}
Method to add the first and second matrices together:
public static int[][] matrixAdd(int[][] A, int[][] B)
{
// Check if matrices have contents
if ((A.length < 0) || (A[0].length < 0)) return B;
if ((B.length < 0) || (B[0].length < 0)) return A;
// create new matrix to store added values in
int[][] C = new int[A.length][A[0].length];
for (int i = 0; i < A.length; i++)
{
for (int j = 0; j < A[i].length; j++)
{
C[i][j] = A[i][j] + B[i][j];
}
}
return C;
}
But I don't really come to a solution how to increment the first array.
// Inkrementieren der ersten Matrix
for(int row = 0; row < firstArray.length; row++)
{
for(int column = 0; column < firstArray[row].length; column++)
{
firstArray[row][column] = 1+ row*10 + column;
System.out.print(firstArray[row][column] + " ");
}
System.out.println();
}
Sum two matrices in the new one and return:
public int[][] addMatrixes(int[][] src1, int[][] src2){
int[][] dst = new int[src1.length][src1[0].length];
for(int i=0;i<src1.length;i++){
for(int j=0;j<src1[0].length;j++){
dst[i][j] = src1[i][j] + src2[i][j];
}
}
return dst;
}
Not very generic, but you can define your first matrix with only one easy loop :
int dim = 10;
int size = dim*dim;
int firstArray[][] = new int[dim][dim];
int row, column;
for (int index = 0; index < size; index++ ){
row = index/dim;
column = index%dim;
firstArray[row][column]=row*10+column+1;
System.out.print(String.valueOf(firstArray[row][column])+"\t");
if (column == 9){ System.out.println("");}
}