How do you add adjacent cells in a 2d array? - java

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();
}
}
}

Related

Value in the method changes which I didn't expect to happen

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];
}
}
}

Issues with calculating the determinant of a matrix (in Java). It is alwys 0

I want to calculoate the determinant of a given NxN Matrix using the Laplace-Method. I already tried differnt approaches which always return a 0.
The class I used:
package Matrix;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class Matrix
{
double[][] array;
public static void init(Matrix a,int row , int column)
{
a.array = new double [row] [column];
for (int i = 0; i < row; i++)
{
for(int k = 0; k < column; k++)
{
a.array[i][k] = 0;
}
}
}
public static int getNRows(Matrix a)
{
return a.array.length;
}
public static int getNColumns(Matrix a)
{
return a.array[0].length;
}
public static void print(Matrix a)
{
for(int i = 0; i < getNRows(a);i++ )
{
for (int k = 0; k < getNColumns(a); k++)
{
System.out.print(a.array[i][k] + "\t");
}
System.out.println();
}
}
public static double det(Matrix a)
{
double det = 0;
det = a.array[0][0] * a.array[1][1] * a.array[2][2] + a.array[1][0] * a.array[2][1] * a.array[0][2] + a.array[2][0] * a.array[0][1] * a.array[1][2] - a.array[2][0] * a.array[1][1] * a.array[0][2] - a.array[1][0] * a.array[0][1] * a.array[2][2] - a.array[0][0] * a.array[2][1] * a.array[1][2];
return det;
public static Matrix transpose(Matrix a)
{
Matrix transposed = new Matrix();
Matrix.init(transposed, getNRows(a), getNColumns(a));
for(int i = 0; i < getNRows(a); i++)
{
for(int j = 0; j < getNColumns(a); j++)
{
transposed.array[j][i] = a.array[i][j];
}
}
return transposed;
}
public static Matrix subMatrix(Matrix a, int exclRow, int exclCol)
{
Matrix subMatrix = new Matrix();
Matrix.init(subMatrix, getNRows(a) - 1, getNColumns(a) - 1);
for(int i = 0; i < getNRows(a) - 1; i++)
{
for(int j = 0; j < getNColumns(a) - 1; j++)
{
if(i != exclRow && j != exclCol)
{
subMatrix.array[i][j] = a.array[i][j];
}
}
}
return subMatrix;
}
public static Matrix loadMatrix(String filename) throws Exception
{
Scanner sc = new Scanner(new BufferedReader(new FileReader(filename)));
Matrix result = new Matrix();
int row = 0;
int col = 0;
String[] line = sc.nextLine().trim().split("\t");
row = Integer.parseInt(line[0]);
col = Integer.parseInt(line[1]);
init(result, row, col);
int currentRow = 0;
while(sc.hasNextLine())
{
String[] line2 =sc.nextLine().trim().split("\t");
for(int i = 0; i < col; i++)
{
result.array[currentRow][i] = Double.parseDouble(line2[i]);
}
currentRow++;
}
return result;
}
/*public static double detN(Matrix a)
{
int colOfA = getNColumns(a);
int rowOfA = getNRows(a);
double value = 1;
if(colOfA != rowOfA)
{
return 0;
}
if(colOfA == 1 && rowOfA == 1)
{
return a.array[0][0];
}
else
{
for(int row = 0; row < rowOfA; row++)
{
value += Math.pow(-1, row) * a.array[row][0] * detN(subMatrix(a, row, 0));
}
}
return value;
}*/
public static double detN(Matrix a)
{
int colOfA = getNColumns(a);
int rowOfA = getNRows(a);
if(colOfA != rowOfA)
{
return 0;
}
if(rowOfA <= 3)
{
return det(a);
}
double value = 0;
for(int row = 0; row < rowOfA; row++)
{
if(row % 2 == 0)
{
value += a.array[row][0] * detN(subMatrix(a, row, 0));
}
else
{
value -= a.array[row][0] * detN(subMatrix(a, row, 0));
}
}
return value;
}
public static Matrix adjointN(Matrix a)
{
int rowOfA = getNRows(a);
int colOfA = getNColumns(a);
Matrix ret = new Matrix();
Matrix.init(ret, rowOfA, colOfA);
for(int row = 0; row < rowOfA; row++)
{
for(int col = 0; col < colOfA; col++)
{
ret.array[row][col] = detN(subMatrix(a, row, col));
}
ret = transpose(ret);
return ret;
}
return ret;
}
public static Matrix inverseN(Matrix a)
{
Matrix inverse = new Matrix();
Matrix.init(inverse, getNRows(a), getNColumns(a));
double pre = 1/detN(a);
inverse = adjointN(a);
for(int i = 0; i < getNRows(a); i++)
{
for(int j = 0; j < getNColumns(a); j++)
{
inverse.array[j][i] = inverse.array[i][j] * pre;
}
}
return inverse;
}
}
I have two versions for detN, which both yield the same result.
This isn't the entire class, because there are some functions that don't belong to this particular question
Here is an approach you could consider(the code is not fully debugged so take with a grain of salt). Finding the determinant is a recursive concept since you are always finding the determinant of a smaller matrix to get the final answer.
//Recursive base function
public static double det(int[][] matrix) {
if(matrix.length == 2)
return ((matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]));
double determinant = 0;
int mlength = matrix.length - 1;
int[][] newM = new int[mlength][mlength];
for(int i = 0; i < mlength + 1; i++) {
newM = newMatrix(matrix, i);
determinant = determinant + (Math.pow(-1, i) * matrix[0][i]) * det(newM);
}
return determinant;
}
//Format smaller matrix to use in further iteration of above det(int[][]) function
public static int[][] newMatrix(int[][] m, int column) {
int length = m.length - 1;
int[][] newMat = new int[length][length];
for(int i = 1; i < m.length; i++) {
for(int j = 0; j < column; j++)
newMat[i - 1][j] = m[i][j];
for(int k = column + 1; k < m.length; k++)
newMat[i - 1][k - 1] = m[i][k];
}
return newMat;
}
You can adapt to however your Matrix class works.
subMatrix is not really excluding the given row and column - it is just making them zero (not copying) and removing the last row and column...
Printing the matrix will help debug that.
one way: use additional indices for the destination matrix (the sub matrix). Only increment this if a value is really copied. Example: sub.array[k++][l++] = a.array[i][j] inside the if
loop over original matrix
Alternative: if one index is greater than or equal to the index that must be skipped, add 1 to the reading index:
var k = (i>=exclRow) ? i+1 : i;
var l = (j>=exclCol) ? j+1 : j;
sub.array[i][j = a.array[k][l];
code not intended to be complete, just ideas how to solve the problem

Direction Array: reducing complexity

I have a m*n matrix where every element is unique. From a given starting point I have to move to the smallest point(up, down, left, right)and then have to do the same process again. When all other surrounding point is greater than the existing one I have to stop and print the position from start. suppose I have a matrix(5*5)
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
and starting point is (2,2) then the output will be 13,8,3,2,1.
I have solved this problem my way, But the problem is its complexity. I do not think my solution is efficient. Can anyone suggest me any better solution?
N.B: Except scanner pkg, I am not allowed to import any other pkg. Here is my code:
import java.util.Scanner;
public class DirectionArray {
public static void main(String [] args) {
Scanner in = new Scanner(System.in);
int row = in.nextInt();
int col = in.nextInt();
int[][] ara = new int[row][col];
int[] ara2 = new int[4];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
ara[i][j] = in.nextInt();
}
}
System.out.println("Give starting point(x) ");
int x= in.nextInt();
System.out.println("Give starting point(y) ");
int y= in.nextInt();
int sx=x;
int sy =y;
int [] fx={+1,-1,0,0};
int [] fy={0,0,+1,-1};
int p=0;
int l=0;
int v=0;
int r=0;
int [] result=new int[row*col] ;
int min=ara[x][y];
boolean swap=true;
for(int i=0;i<(row*col)-1;i++) {
for (int k = 0; k < 4; k++) {
int nx = x + fx[k];
int ny = y + fy[k];
if (nx >= 0 && nx < row && ny >= 0 && ny < col) {
if (min > ara[nx][ny]) {
ara2[p] = ara[nx][ny];
p++;
}
}
}
p=0;
while(swap) {
swap=false;
r++;
for (int q = 0; q < ara2.length-r; q++) {
if(ara2[q]>ara2[q+1]){
int temp = ara2[q];
ara2[q]=ara2[q+1];
ara2[q+1]=temp;
swap=true;
}
}
}
for(int j=0;j<ara2.length;j++) {
if(ara2[j]!=0)
{
v=ara2[j];
result[l]=v;
l++;
break;
}
}
min=v;
for(int o=0;o<ara2.length;o++) {
ara2[o]=0;
}
for(int m=0;m<row;m++){
for(int n=0;n<col;n++){
if(ara[m][n]==v) {
x = m;
y = n;
}
}
}
I think you need to split up your code in more methods. It would make it easier to read.
For example this is how I would reorganize it:
private static final int[][] COORDINATES_TO_TRY = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int row = in.nextInt();
int col = in.nextInt();
int[][] array = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
array[i][j] = in.nextInt();
}
}
System.out.println("Give starting point(x) ");
int x = in.nextInt();
System.out.println("Give starting point(y) ");
int y = in.nextInt();
findMinimum(array, x, y);
return;
}
private static int[] findMinimum(int[][] array, int x, int y) {
for (int i = 0; true; i++) {
if (i > 0) {
System.out.print(",");
}
System.out.print(array[x][y]);
int[] coordinates = findLocalMinimum(array, x, y);
if (x == coordinates[0] && y == coordinates[1]) {
return coordinates;
}
x = coordinates[0];
y = coordinates[1];
}
}
private static int[] findLocalMinimum(int[][] array, int x, int y) {
int min = array[x][y];
int minX = x;
int minY = y;
for (int[] coordinates : COORDINATES_TO_TRY) {
int i = x + coordinates[0];
int j = y + coordinates[1];
if (i >= 0 && i < array.length && j >= 0 && j < array[i].length) {
if (array[i][j] < min) {
minX = i;
minY = j;
min = array[i][j];
}
}
}
return new int[]{minX, minY};
}

Calculate sum of rows above and below a point, and also sum of columns left and right a point

Hey guys I am doing a question where I have to find a point in a Matrix A of N x M rows such that
the sum of rows above the point is equal to the sum of row
Consider this example
/**
* A[0][0] = 2 A[0][1] = 7 A[0][2] = 5
* A[1][0] = 3 A[1][1] = 1 A[1][2] = 1
* A[2][0] = 2 A[2][1] = 1 A[2][2] = -7
* A[3][0] = 0 A[3][1] = 2 A[3][2] = 1
* A[4][0] = 1 A[4][1] = 6 A[4][2] = 8
* #param matrix
* #return
*/
In this example the if we look at the point A[1][1], it can be said that the row above (sum = 14) is equal to the sum of rows below the point.
Can anyone help me on this?
I have so far gotten this far. But I know this is a sucky approach.
public int solution(int[][] matrix) {
int rows = matrix[0].length;
int columns = matrix.length;
int sumabove = 0;
int sumbelow = 0;
for( int i = 1; i < rows; i++ ) {
for (int j = 0; j < columns; j++) {
sumabove += matrix[i - 1][j];
sumbelow += matrix[i + 1][j];
}
}
return 0;
}
The idea is to calculate sum for every row (int[] rowsSum) and sum for all rows (totalRowsSum). And then to iterate through rows, comparing sum of previous rows (currentSum) with sum of next rows (totalRowsSum - currentSum - rowsSum[i]).
Code example.
public static int solution(int[][] matrix)
{
int foundRowNumber = -1;
int rows = matrix.length;
int columns = matrix[0].length;
int[] rowsSum = new int[rows];
int totalRowsSum = 0;
for (int i = 0; i < rows; i++)
{
int rowSum = 0;
for (int j = 0; j < columns; j++)
{
rowSum += matrix[i][j];
}
rowsSum[i] = rowSum;
totalRowsSum += rowSum;
}
int currentSum = 0;
for (int i = 0; i < rows; i ++)
{
if (currentSum == totalRowsSum - currentSum - rowsSum[i])
{
foundRowNumber = i;
break;
}
currentSum += rowsSum[i];
}
return foundRowNumber;
}
i'd say:
1st: get the sum of the whole matrix
2nd: divide by 2 and store in a var (mid)
3rd: loop it to go down a row each time and it will get the sum of that row and subtract it from the total sum, if it is smaller than the remaining then keeps going, if the remaining number is smaller then (mid) then you went over the middle and you start checking the columns for the row you are in and before in another loop using the same concept
something like this (pseudo code):
int sum = matrix.sum();
int mid = sum/2;
int topsum = 0;
int botsum = sum;
int counter=0;
bool fail = false;
while(topsum!=botsum && !fail) //either break when both top and bottom are same or if there is no middle gorund
{
int rowsum; //use loop to get the sum of the row
for(int i=0; i>colLength(); i++) rowsum=+ matrix[counter][i];
topsum =+ rowsum;
botsum=-rowsum;
counter++;
if(botsum>mid) //if you go over the middle
{
botsum=-rowsum; //take it back before last addition acction
counter --; //go back to the last row;
//loop
//here you will start checking columns to get to the middle.
}
}
this was made so that it would get you the cell and not row, but you can change it to your liking.
Ok I was able to do make a solution. But I think I made a mess of the complexity. I was supposed to do in a linear complexity. Anyways my solution is
public class MainClass {
static int matrix[][] = {{2, 7, 5}, {3, 1, 1}, {2, 1, -7}, {0, 2, 1}, {1, 6, 8}};
public static void main(String[] args) {
System.out.print(solution(matrix));
}
/**
* A[0][0] = 2 A[0][1] = 7 A[0][2] = 5
* A[1][0] = 3 A[1][1] = 1 A[1][2] = 1
* A[2][0] = 2 A[2][1] = 1 A[2][2] = -7
* A[3][0] = 0 A[3][1] = 2 A[3][2] = 1
* A[4][0] = 1 A[4][1] = 6 A[4][2] = 8
* #param matrix
* #return
*/
public static int solution(int[][] matrix) {
int columns = matrix[0].length;
int rows = matrix.length;
int sumRowsAbove = 0;
int sumRowsBelow = 0;
int sumColLeft = 0;
int sumColRight = 0;
int equilibrium = 0;
for( int i = 0; i < rows; i++ ) {
for (int j = 0; j < columns; j++) {
sumRowsBelow = getSumRowsBelow(i);
sumRowsAbove = getSumAbove(i);
sumColLeft = getSumColumnLeft(j);
sumColRight = getSumColumnRight(j);
if(sumRowsAbove == sumRowsBelow && sumColLeft == sumColRight) {
equilibrium++;
}
int x = 2;
x+=2;
}
}
return equilibrium;
}
public static int getSumRowsBelow(int rowNum) {
int columns = matrix[0].length;
int rows = matrix.length;
int sumBelow = 0;
for( int i = rowNum; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if((i+1) < rows){
sumBelow += matrix[i + 1][j];
}
}
}
return sumBelow;
}
public static int getSumColumnRight(int column) {
int columns = matrix[0].length;
int rows = matrix.length;
int sumBelow = 0;
for (int j = column; j <= columns; j++) {
for( int i = 0; i < rows; i++) {
if((j+1) < columns){
sumBelow += matrix[i][j + 1];
}
}
}
return sumBelow;
}
public static int getSumColumnLeft(int column) {
int columns = matrix[0].length;
int rows = matrix.length;
int sumBelow = 0;
for (int j = column; j >= 0; j--) {
for( int i = 0; i < rows; i++) {
if((j-1) >= 0){
sumBelow += matrix[i][j - 1];
}
}
}
return sumBelow;
}
public static int getSumAbove(int rowNum) {
int columns = matrix[0].length;
int rows = matrix.length;
int sumBelow = 0;
for( int i = rowNum; i >= 0; i--) {
for (int j = 0; j < columns; j++) {
if((i-1) >= 0){
sumBelow += matrix[i - 1][j];
}
}
}
return sumBelow;
}
}
This is a codility question regarding find the number of points (equilibriums) such the sum of elements in rows above the selected point is equal to the sum of rows below the point. And also sum of columns from the left of the selected point is equal to the sum of columns to the right of the point.

Manipulating adjacent matrix

I have a network graph with nodes and edges and i managed to construct an adjacent matrix of my graph.
sample adjacent matrix with edge weight
Nodes -> {A, B, C, D}
Edges -> {[A->B = 2] , [A->D = 5] , [C->A = 1] , [C->B = 4] , [D->B = ] , [D->C = 2]}
my adjacent network is like this
0 2 0 2
0 0 0 0
4 4 0 0
0 6 6 0
so i want to change the adjacent matrix to be like this with labels of the nodes and average of each column by considering non zero cells
A B C D
A 0 2 0 2
B 0 0 0 0
C 4 4 0 0
D 0 6 6 0
X 4 4 6 2 <- Mean of non zero column
here is my the code i used to create adjacent matrix,
Node.java
public class Node
{
public char label;
public Node(char l)
{
this.label=l;
}
}
Graph.java
public class Graph
{
public ArrayList nodes=new ArrayList();
public double[][] adjacentMatrix;
int size;
public void addNode(Node n)
{
nodes.add(n);
}
public void addEdge(Node start,Node end,int weight)
{
if(adjacentMatrix==null)
{
size=nodes.size();
adjacentMatrix=new double[size][size];
}
int startIndex=nodes.indexOf(start);
int endIndex=nodes.indexOf(end);
adjacentMatrix[startIndex][endIndex]=weight;
}
public static void printAdjacentMatrix(double matrix[][]) {
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
}
Main.java
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Defining nodes
Node nA=new Node('A');
Node nB=new Node('B');
Node nC=new Node('C');
Node nD=new Node('D');
//Creating adjacent matrix
Graph g=new Graph();
g.addNode(nA);
g.addNode(nB);
g.addNode(nC);
g.addNode(nD);
g.addEdge(nA, nB, 2);
g.addEdge(nA, nD, 2);
g.addEdge(nC, nA, 4);
g.addEdge(nC, nB, 4);
g.addEdge(nD, nB, 6);
g.addEdge(nD, nC, 6);
g.printAdjacentMatrix(g.adjacentMatrix);
}
}
so i ask for help to display the second matrix with average and labels...Thank you in advance
Not a very nice solution but that will do.
public class Graph {
public ArrayList nodes = new ArrayList();
public int[][] adjacentMatrix;
int size;
public void addNode(Node n) {
nodes.add(n);
}
public void addEdge(Node start, Node end, int weight) {
if (adjacentMatrix == null) {
size = nodes.size();
adjacentMatrix = new int[size][size];
}
int startIndex = nodes.indexOf(start);
int endIndex = nodes.indexOf(end);
adjacentMatrix[startIndex][endIndex] = weight;
}
public static void printAdjacentMatrix(int matrix[][]) {
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
public static void convertMatrix(int matrix[][]) {
int row = matrix.length + 2;
int column = matrix[0].length + 1;
String newMatrix[][] = new String[row][column];
initializeFirstRow(newMatrix);
initializeFirstColumn(newMatrix);
copyMatrix(matrix, newMatrix);
addMean(matrix, newMatrix);
printAdjacentMatrix(newMatrix);
}
private static void initializeFirstColumn(String[][] newMatrix) {
newMatrix[1][0] = "A";
newMatrix[2][0] = "B";
newMatrix[3][0] = "C";
newMatrix[4][0] = "D";
newMatrix[5][0] = "X";
}
private static void printAdjacentMatrix(String[][] newMatrix) {
for (int row = 0; row < newMatrix.length; row++) {
for (int column = 0; column < newMatrix[row].length; column++) {
System.out.print(newMatrix[row][column] + " ");
}
System.out.println();
}
}
private static void addMean(int[][] matrix, String[][] newMatrix) {
int mean = 0;
int sum = 0;
int divident = 0;
for (int j = 0; j < matrix[0].length; j++) {
sum = 0;
divident = 0;
for (int i = 0; i < matrix.length; i++) {
if (matrix[i][j] != 0) {
sum += matrix[i][j];
divident++;
}
}
if (sum != 0) {
mean = sum / divident;
}
newMatrix[5][j + 1] = "" + mean;
}
}
private static void copyMatrix(int[][] matrix, String[][] newMatrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
newMatrix[i + 1][j + 1] = "" + matrix[i][j];
}
}
}
private static void initializeFirstRow(String[][] newMatrix) {
newMatrix[0][0] = " ";
newMatrix[0][1] = "A";
newMatrix[0][2] = "B";
newMatrix[0][3] = "C";
newMatrix[0][4] = "D";
}
}
Also add following line in Main.java
g.convertMatrix(g.adjacentMatrix);

Categories

Resources