Adding Elements of an Array (sum of rows and columns) - java

I'm looking for a way to add up the elements of the rows of an array and get that sum. I have to get the column's sum as well.
The array looks something like this:
{{45.24, 54.67, 32.55, 25.61},
{65.29, 49.75, 32.08, 26.11},
{25.24, 54.33, 34.55, 28.16}};
For example, I would add 45.24, 65.29, and 25.24 to get the sum of that part of the columns. I would then have to add the other 3 columns up as well.
Same goes for the rows.
I keep getting errors concerning the variable types. Is there a way to do this? Thanks.

The logic Would be --->
for(i = 0; i < columns; i++)
{
for(j=0; j<rows; j++)
{
sum+=arr[j][i];
}
}
Opposite for Columns

I think you should define the type of numbers your array will handle, if I use float numbers I can have some code like the class bellow to do the type of operations you are asked for. You can also add some decimal formatting.
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
float myarray[][]= {
{45.24f, 54.67f, 32.55f, 25.61f},
{65.29f, 49.75f, 32.08f, 26.11f},
{25.24f, 54.33f, 34.55f, 28.16f}
};
float row[] = new float[3];
float column[] = new float[4];
for (int i=0; i < 3; i++) {
float rowvalue = 0f;
for (int j=0; j < 4; j++) {
System.out.print(myarray[i][j]+" ");
rowvalue+=myarray[i][j];
}
row[i]=rowvalue;
System.out.println("");
}
System.out.println("");
for (int i=0; i < 4; i++) {
float colvalue = 0f;
for (int j=0; j < 3; j++) {
System.out.print(myarray[j][i]+" ");
colvalue+=myarray[j][i];
}
column[i]=colvalue;
System.out.println("");
}
System.out.println("Rows answer:");
for (int i=0; i < 3; i++) {
System.out.println(row[i]);
}
System.out.println("Columns answer:");
for (int i=0; i < 4; i++) {
System.out.println(column[i]);
}
}
}

Suppose you have nxn matrix. The idea is to identify the pattern.
Row values
i j
0 0
0 1
0 2
Column values
i j
0 0
1 0
2 0
The position of i and j values is reversed.
Let's assume we have an array a[][]. The logic would be:
for (int i=0; i<n; i++) {
int row = 0, col = 0;
for (int j=0; j<n; j++) {
row += a[i][j];
col += a[j][i];
}
System.out.println("row" + i + " = " + row);
System.out.println("col" + i + " = " + col);
}
I assumed you wanted the sum of each row and column separately. You can modify it accordingly.

Related

Is there a way to fix my two dimensional array problem

How can I find the total sum for each two dimensional array row? I'm completely stuck...
public static void main(String[] args) {
int [][] grid = new int [10][10];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = (int)(Math.random()*99);
}
}
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
System.out.print("1.");
System.out.printf("%5d ", grid[i][j]);
}
System.out.println();
}
}
My current output is:
How can I show the total sum for each row in the end of the row and show column numbers
For the sum of a row, this should do. In a similar way within the i loop, if you need to count the column as well;
for(int i = 0; i < 10; i++) {
int jSum = 0;
for(int j = 0; j < 10; j++) {
jSum += grid[i][j];
System.out.print("1.");
System.out.printf("%5d ", grid[i][j]);
}
System.out.printf(" %5d", jSum);
System.out.println();
}
On the column numbering:
Either you just pust put a static print in the beginning (like print "1 2 3 4..."), or you put the following with the j loop:
if (i == 0) System.out.printf("%5d ", j); // only prints in first loop / row - print 1,2,3,4,5....

matrix column sum java

I am working just recently in Java. And I am still struggling a little bit with Java. The task is to sum the columns and the rows respectively the example looks like that.
I managed to get the sum of the columns, but I always end up having the first row repeated in my desired output, how can I delete that error. And just have the desired column sums.
How does it work for sum of rows respectively?
Thank you very much for your help in advance
The code looks like that:
public class MatrixColumnSums {
public static void main(String[] args) {
// TODO Auto-generated method stub
double [][] a = new double [2][3];
a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[1][0] = 4;
a[1][1] = 5;
a[1][2] = 6;
System.out.println( "A");
for (int i = 0; i < a.length; i++) {
String str = "";
for (int j = 0; j < a[i].length; j++) {
str += a[i][j] + "\t";
}
System.out.println(str);
}
// column sums
// creating another matrix to store the sum of columns matrices
double c[] = new double [a[0].length];
// Adding and printing addition of 2 matrices
System.out.println("C");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++)
{
c[j] += a[i][j];
System.out.print(c[j] + "\t");
}
System.out.println();
}
}
}
The output looks like the following:
A
1.0 2.0 3.0
4.0 5.0 6.0
C
1.0 2.0 3.0 ( <= I want to get this row deleted)
5.0 7.0 9.0 ( I just want to have this as my output)
**Matrix column sum **
doOneColumnSum method sum one column.
private static double doOneColumnSum(double[][] arr, int col){
double total = 0;
for (int row = 0; row < arr.length; row += 1){
total += arr[row][col];
}
return total;
}
doColumnSums method sum all column using doOneColumnSum method
public static double[] doColumnSums(double[][] arr)
{
int numColumns = arr[0].length;
double[] result = new double[numColumns];
for (int col = 0; col < numColumns; col += 1)
{
result[col] = findOneColumnSum(arr, col);
}
return result;
}
Don't print when summing the c matrix, just print once at the end:
// sum the columns first
for (int i=0; i < a.length; i++) {
for (int j=0; j < a[0].length; j++) {
c[j] += a[i][j];
}
}
// then iterate c[] once at the end and print it
for (int j=0; j < a[0].length; j++) {
System.out.print(c[j] + "\t");
}
Note that we could have added if logic to your original nested loop to only print c after the summation is complete, but what I wrote above seems more appealing from a separation of concerns point of view.

indexoutofbound error when shifting 2D array elements java

public static int[][] shift(final int[][] original, final int amount) {
int[][] shifted = new int[original.length][original[0].length];
for (int col = 0; col < original.length; col++) {
for (int row = 0; row < original[col].length; row++) {
shifted[col][row] = FILL_VALUE;
}
for (int cols = 0; cols < original.length + amount; cols++) {
for (int rows = 0; rows < original[cols].length; rows++) {
if (cols - amount < original.length) {
shifted[cols][rows] = original[cols - amount][rows];
}
}
}
}
return shifted;
}
Hi,
I am trying to write a method that will shift the elements in my 2-D array to the left by some arbitrary amount. I don't want to loop the values back around, but instead fill the empty arrays with some fill_value which is already predefined. And if the shift amount is more than the orignial length, I would just return an image with only fill_value. However, this function is throwing an arrayindexoutofbound Error. But I can't think of how I should change my for loop to fix the error. Any help is appreciated! Thank you!
I believe it's because in your second outer for loop, the condition is cols < length + amount, so it will continue past the edge of the array if amount > 0. You could step through your code with a debugger and see exactly where it's going out of bounds.
The error is occurring because of following line:
shifted[cols][rows] = original[cols - amount][rows];
When cols=0, rows=0, amount=2 (say), it is trying to access original[-2][0] which does not exist.
Instead you may use following:
public class overflow1 {
static int a[][] = {{1,2,3,4,5,6},{2,3,4,5,6,7},{3,4,5,6,7,8}, {4,5,6,7,8,9}, {5,6,7,8,9,10}, {6,7,8,9,10,11}};
static int b[][] ;
static int FILL_VALUE =0;
public static int[][] shift(final int[][] original, final int amount) {
int[][] shifted = new int[original.length][original[0].length];
for (int col = 0; col < original.length; col++) {
for (int row = 0; row < original[col].length; row++) {
shifted[col][row] = FILL_VALUE;
}
for (int cols = 0; cols < original.length ; cols++) {
for (int rows = 0; rows < original[cols].length; rows++) {
if (cols - amount >=0) {
shifted[cols][rows] = original[cols - amount][rows];
}
}
}
}
return shifted;
}
public static void main(String[] arggs) {
b=shift(a,2);
System.out.println("Original array:");
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();
}
System.out.println("After shift by 2 array:");
for(int i=0; i<b.length; i++){
for (int j=0; j<b[i].length; j++){
System.out.print(b[i][j]+ ":");
}
System.out.println();
}
}
}
Here is the output for the sample:
Original array:
1:2:3:4:5:6:
2:3:4:5:6:7:
3:4:5:6:7:8:
4:5:6:7:8:9:
5:6:7:8:9:10:
6:7:8:9:10:11:
After shift by 2, array:
0:0:0:0:0:0:
0:0:0:0:0:0:
1:2:3:4:5:6:
2:3:4:5:6:7:
3:4:5:6:7:8:
4:5:6:7:8:9:

How should I understand a "for" statement in a tilemap?

I'm following a tutorial online and I'm having troubles understanding the code which is written there.
public Tilemap() {
int[][] tilemap = new int[30][50];
System.out.println("New Tilemap created.");
Random r = new Random();
int rows = tilemap.length;
int columns = tilemap[1].length;
printTiles(rows, columns, tilemap, r);
}
public void printTiles(int rows, int columns, int[][] tilemap, Random r) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
tilemap[i][j] = r.nextInt(5);
System.out.print(" " + tilemap[i][j]);
}
System.out.println(" ");
}
}
I understand everything up until the for statement:
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
tilemap[i][j] = r.nextInt(5);
System.out.print(" " + tilemap[i][j]);
}
System.out.println(" ");
}
The tutorial doesn't explain one bit about them. So if anyone could help me understand, what is the purpose of most of the lines in the for statement, I'd appreciate that.
It looks like it's iterating through the entire 2D array and placing random integers at every index.
I've commented the code below. Hopefully this explains it.
for (int i = 0; i < rows; i++) { //iterate through every row
for (int j = 0; j < columns; j++) { //iterate through every column
tilemap[i][j] = r.nextInt(5); //place an integer between 0 (inclusive) and 5 (exclusive) at the specified location in the 2d array
System.out.print(" " + tilemap[i][j]); //print the integer that was just placed with a preceding space
}
System.out.println(" "); //print a new line since we've reached the end of the row
}

Fill double array with random numbers and then print even and odd numbers from that array

So here's my problem. I have to write a program that will fill array with random numbers(and it's ok), then it's necessary to print only even index numbers or only odd value numbers(j). Tried like this but when i put if statement and it shows every even number (index and value-the second in array) so it wrong. What should i do so?
import java.util.Random;
public class Array {
public static void main(String[] args)
{
int rows = 5;
int colu = 2;
Random r = new Random();
int [][] array = new int [rows][colu];
for(int row = 0; row < array.length; row++)
{
for(int col = 0; col < array[row].length; col++)
{
array[row][col] = r.nextInt(10);
}
}
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
if(array[i][j]%2 == 0){
System.out.print(array[i][j] + " ");
}
}
}
System.out.println();
}
}
Thanks
I'm going to take a stab at this but I'm not sure if I quite understand yet.
int array[][] = new int[row][col];
// ... populate the array with random numbers, works fine...
// Let's traverse the first column.
for (int i = 0; i < row; i++) {
int value = array[i][0]; // col 0 means first column
if (value % 2 == 0) {
// ...
}
}
// Let's traverse the second column.
for (int i = 0; i < row; i++) {
int value = array[i][1]; // col 1 means second column
// ...
}
Is this what you mean? If it is, do you see the pattern and how you could generalize this and make the code a bit smaller?
Just implement this formula in your "if" statement :
(Number × 2 )/4 ==0. You will always get even numbers. You can handle the rest :D

Categories