java : Sum of Vertical elements in a triangle - java

I want to calculate the sum of all vertical elements in an triangle for example, if the triangle is
Ex : Triangle size is 5
1
2 2
5 2 2
2 0 5 8
8 7 9 4 5
Then the sum should be
Sum1 = 1+2+5+2+8 = 18 (Sum of vertical elements from the first column)
Sum2 = 2+2+0+7 = 11
Sum3 = 2+5+9 = 16
Sum4 = 8+4= 12
Sum5 = 5 = 5
Note : The triangle size will vary, also the elements will be random.
Program I wrote, but it's only calculating the first row how do i calculate and store the 2nd, 3rd and upto the last ?
public class fsdhs
{
public static void main(String args[])
{
int arr[]={1,2,2,5,2,2,2,0,5,8,8,7,9,4,5};
int x,y,count=0,size=5,sum=0;
boolean flag=false;
for(x=0;x<size;x++)
{
for(y=0;y<=x;y++)
{
if(flag==false)
{
sum=sum+arr[count];
flag=true;
}
System.out.print(arr[count]+" ");
count++;
}
System.out.print("\n");
flag=false;
}
System.out.print("\nSum1="+sum);
}
}

You can simplify your code and calculate col sums using the following formula to get index of array by index of i-th row in triangle and j-th column (j<=i, zero-based):
index = i*(i+1)/2 + j
For example, in given triangle at row i=3, column j=2 value is 5, so
index = 3*4/2 + 2 = 8, arr[8] is also 5

A more intuitive approach may be to use a multidimensional jagged array to store the triangle data. This way you can reason over the coordinates directly without needing to calculate row based offsets:
int arr[][]={{1},{2,2},{5,2,2},{2,0,5,8},{8,7,9,4,5}};
int size=5;
for(int x=0; x < size; x++)
{
int sum = 0;
for(int y=x; y < size; y++)
{
sum += arr[y][x];
}
System.out.println("Column " + x + " Sum=" + sum + "\n");
}
You just need to be wary of the uneven row sizes of the jagged array
IdeOne Demo

int SIZE = 5; // The size of your triangle
int arr[]={1,2,5,2,8,2,2,0,7,2,5,9,8,4,5}; // Array of triangle items
int[] sums = new int[SIZE];
for (int i = 0; i < arr.length; i += SIZE, SIZE--) {
for(int j = i; j < i + SIZE; j++) {
sums[sums.length - SIZE] += arr[j];
}
}
// Show items
for (int i = 0; i < sums.length; i++) {
System.out.println("item " + i + ": " + sums[i]);
}

Related

How to randomly fill in 10% 2 dimensional array with int = 1?

I have little problem , im starting learn java .
I need to create 2dimensional array , and i need fill this array in 10% only int 1 of course my code need fill this array randomly .
Need some hints how to fill in 10% .
public static void main(String[] args) {
int maxX = 10;
int maxY = 10;
int[][] Arr = new int[maxX][maxY];
Random r = new Random();
// random ints
for (int x = 0; x < maxX; x++) {
for (int y = 0; y < maxY; y++) {
Arr[x][y] = r.nextInt(2);
}
}
// printing Arr
for (int i = 0; i < Arr.length; i++) {
for (int j = 0; j < Arr[i].length; j++) {
System.out.print(Arr[i][j] + " ");
}
System.out.println();
}
}
Make the array, take a random row and column, while the percentage is not exceeded, check if the position has 0, if yes fill it with 1.
int[][] array = new int[N][N];
int percentage = N*N/10;
int filled = 0;
while(filled <= percentage)
{
Random rand = new Random();
int i = rand.nextInt(N+1);
int j = rand.nextInt(N+1);
if(array[i][j] == 0)
{
filled++;
array[i][j] = 1;
}
}
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println();
}
You can take the following steps:
Suppose you need to fill an N * N array.
Create a List and add to it (N * N) / 10 1s and (N * N * 9) / 10 0s. list.addAll(Collections.nCopies(count,1 or 0)) can help you here.
Run Collections.shuffle on that List to obtain random order.
Iterate over the elements of the List. The first N elements will become the first row the the 2D array, the next N elements will become the second row of the array, and so on...
An alternative to shuffling is to pick 10% x N random positions and put a 1 (if a 0 was in the position, otherwise pick another position). In pseudo code:
int[][] array = new int[N][N]
apply N * N / 10 times {
index = random(0 .. N * N)
if array(index) = 0 then array(index) = 1
else retry with another index
}
You will need to convert the index from 0 to N*N into a pair of i,j in the 2D array.
I would use "double random = Math.random();"
And then an if to check if the variable random is less or equal to 0.1

to output all elements of square matrix in a spiral

The task is following:
a square matrix A of order M is given. Starting with the element A0,0 and moving clockwise, you should output all its elements in a spiral: the first row, the last column, the last row in reverse order, the first column in reverse order, the remaining elements of the second row and so on.
public class Pres10Task8 {
public static void main(String[] args) {
int m =4;
int [][] a=new int [m][m];
Random rand = new Random();
for(int i =0;i<a.length;i++){
for(int j =0;j<a[i].length;j++){
a[i][j]=rand.nextInt(100);
System.out.print(a[i][j]+" ");
}
System.out.println();
}
for(int k=0;k<m/2+1;k++){
for(int j = k; j<m+1-k;j++){
System.out.println(a[k][j]);
}
int j =m+1-k;
for(int i=k+1;i<m+1-k;i++){
System.out.println(a[i][j]);
}
for(int j=m-k;j>k;j--){
j =k ;
System.out.println(a[i][j]);
}
for(int i =m-k;i>k+1;i-- ){
i =m+1-k;
System.out.println(a[i][j]);
}
}
}
}
Would you be so kind to look through my code and say what is wrong with it? How should I rewrite my code in order to get the right output?
You couldn't use a variable in your loop already exist before your method :
int j = m + 1 - k;
// ^--------------------------------------Already exist
for (int i = k + 1; i < m + 1 - k; i++) {
System.out.println(a[i][j]);
}
for (int j = m - k; j > k; j--) {
// ^---------You can't declare a variable already exist,
//you can just use it or initialize it
So instead use this without int j:
for (j = m - k; j > k; j--) {
Second
System.out.println(a[i][j]);
// ^-----The i is not exist so you have to
//create it and inisialize it so you can use it
You have made many mistakes as YCF_L mentioned in the answer and also After solving few of them I was still getting other errors. You can solve this problem by a simple logic that Divide Square Matrix into smaller squares and then follow the same pattern to print each of the squares.
For Example,
Suppose I have a matrix of order 5 then we can have 3 squares here for distinct dimensions.
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
Here each number represents that to which square the element belongs.So all outer elements belongs to first square then the next layer's elements belongs to second square and so on.
Now you have made your problem easier by dividing it into smaller sub-problems which can be solved in same way. Now you need to make logic of print the elements of each of the squares.
So for this, Consider the most outer square.
1 1 1 1 1 1 2 3 4 5
1 1 Thier Printing Order 16 6
1 1 ================> 15 7
1 1 14 8
1 1 1 1 1 13 12 11 10 9
So notice that we start from the first element and move into the same row into the right direction.
Then move in same column into down direction.
Then again in the same row in left direction.
At last in the same column but in the up direction.
After printing the outer square move to the inner square and do the same for each of the squares.
Code for the same:
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args) {
int m =4;
int [][] a=new int [m][m];
Random rand = new Random();
for(int i =0;i<a.length;i++){
for(int j =0;j<a[i].length;j++){
a[i][j]=rand.nextInt(100);
System.out.print(a[i][j]+" ");
}
System.out.println();
}
int squares=m/2; //Calculating total number of squares
for(int i=0;i<squares;i++)
{
int low=i; //Set the dimension of the square
int high=m-i-1;
for(int j=low;j<=high;j++) //First Row --> (Right Direction)
System.out.println(a[low][j]);
for(int j=low+1;j<=high;j++) //Last Column --> (Down Direction)
System.out.println(a[j][high]);
for(int j=high-1;j>=low;j--) //Last Row --> (Left Direction)
System.out.println(a[high][j]);
for(int j=high-1;j>low;j--) //First Column --> (Up Direction)
System.out.println(a[j][low]);
}
if(m%2==1) //If Matrix is of odd order then print the middle element.
System.out.println(a[mid][mid]);
}
}
Why you use jagged array [][] instead of 2-dimensional [,] ???
May give a simple sample:
public void CountDiag(int size)
{
// initialize straight order
int[,] ar2 = new int[size, size];
int count = 0;
// initialize spiral way
int y = 0;
int x = 0;
int top = 0;
int bot = ar2.GetLength(0)-1;
int left = 0;
int right = ar2.GetLength(1)-1;
do
{
//topleft to right
for (; y < right; y++)
{
ar2[x, y] = count + 1;
count++;
}
ar2[x, y] = count + 1;
right--;
//topright to bottom
for (; x < bot; x++)
{
ar2[x, y] = count + 1;
count++;
}
ar2[x, y] = count + 1;
top++;
//botright to left
for (; y > left; y--)
{
ar2[x, y] = count + 1;
count++;
}
ar2[x, y] = count + 1;
left++;
//botleft to top
for (; x > top; x--)
{
ar2[x, y] = count + 1;
count++;
}
ar2[x, y] = count + 1;
bot--;
} while (count < ar2.Length-1);
}
AND you print it out like this:
public void PrintArray(int[,] array)
{
int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1; // for padding
for (int i = 0; i < array.GetLength(0); i++) // 0 - length rows
{
for (int j = 0; j < array.GetLength(1); j++) // 1 length columns
{
Console.Write(array[i, j].ToString().PadLeft(n, ' '));
}
Console.WriteLine();
}
Console.ReadLine();
}

Static methods and Jagged Arrays

I am trying to write a static method that returns an integer, takes a 2-dimensional array of integers as a parameter and return the index of the row in the 2-d array (jagged arrays) that has the largest sum of all its elements. Something went wrong along the line and im still trying to figure out. Help please?
Here is the code:
public static int findMaxRow(int[][] maxRows){
newI= 0;
newJ= 0;
for(int i=0; i< maxRows.length; i++) {
newI += i;
for(int j=0; j< maxRows.length; j++) {
newJ += j;
`` if( newI > newJ){
return newI;
else {
}
}
}
}
You never define the type for newI or newJ, that can be fixed by preceding their declaration with their intended type (i.e int). You also have two " ` " before your if statement, and your missing a closing bracket " } " before your else statement. But those are just syntactical errors. Once you fix those errors you're going to notice that your method is not returning the desired results.
Looking at your code, specifically the for loops.
for(int i=0; i< maxRows.length; i++) {
newI += i;
for(int j=0; j< maxRows.length; j++) {
newJ += j;
// other stuff
}
}
Let's say that maxRows.length equals 3. That means the outer loop is going to run from 0 to 2, so newI will equal 3. Meanwhile for each iteration the outer loop makes, the inner loop iterates 3 times. So newJ will end up equalling 9. Which is not the right way to go about summing the elements of an array. A better way to go about it, is to iterate over the arrays in the outer loop and sum the elements in the inner loop, then make a comparison completing the outer loop. Like so:
int largestRow = 0;
int largestSum = 0;
int sum;
// iterate over each array
for(int i=0; i< maxRows.length; i++) {
sum = 0; // set and reset sum to zero
// iterate over each element
for(int j=0; j< maxRows[i].length; j++) {
sum += maxRows[i][j];
}
// if sum is > the previous largest sum then set largest
// sum to this new sum and record which row
if(sum > largestSum) {
largestRow = i;
largestSum = sum;
}
}
return largestRow;
Here is an example of what you're trying to accomplish.
public class RowSums {
public static void main(String[] args) {
int[][] test = { {1, 5, 7, 0, 9} , {2, 4, 5, 6, 7} , {9, 2, 0, 12, 8, 3} };
System.out.println(printRows(test));
System.out.println("The row with the largest sum is row "
+ findMaxRow(test));
}
public static int findMaxRow(int[][] maxRows){
int largestRow = 0;
int largestSum = 0;
int sum;
// iterate over each array
for(int i=0; i< maxRows.length; i++) {
sum = 0; // set and reset sum to zero
// iterate over each element
for(int j=0; j< maxRows[i].length; j++) {
sum += maxRows[i][j];
}
// if sum is > the previous largest sum then set largest
// sum to this new sum and record which row
if(sum > largestSum) {
largestRow = i;
largestSum = sum;
}
}
return largestRow;
}
public static String printRows(int[][] rows) {
StringBuilder s = new StringBuilder("Rows and their sums:\n");
int sum;
for(int x = 0; x < rows.length; x++) {
s.append("Row [" + x + "] = [ ");
sum = 0;
for(int y = 0; y < rows[x].length; y++) {
s.append(rows[x][y] + " ");
sum += rows[x][y];
}
s.append("]\n");
s.append("Row [" + x + "]'s sum is " + sum + "\n");
}
return s.toString();
}
}
Output:
Rows and their sums:
Row [0] = [ 1 5 7 0 9 ]
Row [0]'s sum is 22
Row [1] = [ 2 4 5 6 7 ]
Row [1]'s sum is 24
Row [2] = [ 9 2 0 12 8 3 ]
Row [2]'s sum is 34
The row with the largest sum is row 2
Modifying your program, the following example will return the index of the row that has the largest sum of elements in it.
Let us suppose our array to be passed is:
int [][] maxRows = {{1,2,3}, {1,2,3,4,5}, {9,9,9,9}, {1,2}};
passing this array in the method
public static int findMaxRow(int[][] maxRows){
int sum = Integer.MIN_VALUE;
int biggestIndex= 0;
for(int i = 0; i<maxRows.length; i++){
int temp = 0;
for(int ir : maxRows[i]){
temp+=ir;
}
if(temp>sum){
sum = temp;
biggestIndex = i;
}
}
return biggestIndex;
}
The above program will return the index of the inner array which has the largest sum of elements, in above case, it will return 2 .

how to calculate the sum of elements after the diagonal in 2D array in java?

I have a function that I need to calculate the sum of elements after the diagonal in the 2D array, but the problem is that the function return the sum of the elements in the diagonal.
What I need is that if I have a matrix like this:
1 2 3
4 5 6
7 8 9
The elements of the diagonal are = 1 5 9
What I need is to calculate the numbers that follow after these diagonal numbers, so it will be like this:
1 2 3
4 5 6
7 8 9
sum = 2+3+6 = 11
I would appreciate it if someone could help me to fix my problem.
this my code:
public int calculate(){
int sum = 0;
for(int row = 0; row <matrix.length; row++){
for(int col = 0; col < matrix[row].length; col++){
if(row == col){
sum = sum + row+1 ;
}
}
}
System.out.println("the sum is: " + sum );
return sum;
}
public static void main(String[] args) {
int[][] ma = new int[2][2];
Question2 q2 = new Question2(2, 2, ma);
q2.fill();
q2.calculate();
}
the output is:
2 1
2 1
the sum is: 3
You want col to go through all elements, being always bigger than the diagonal.
Therefore try:
int sum = 0;
for(int i = 0 ; i < a.length ; ++i) {
for(int j = i + 1 ; j < a[i].length ; ++j) {
sum += a[i][j];
}
}

Calculate adjacency matrices in java

Basically I need to query the user for a matrix. Then I need to find A^2, A^3, A^4... and so on (where A is the matrix). Then I need to find the sum A + A^2 + A^3 ... etc up to 6.
So far this is what I've done
public class Driver {
public static void main(String[] args) {
int i, j, l, k, sum = 0 ;
int matrixAColumnSize ;
int matrixARowSize ;
double numberOfNodes ;
// Querying user for matrix size
matrixARowSize = Tools.queryForInt("Enter the row size of Matrix A: ") ;
matrixAColumnSize = Tools.queryForInt("Enter the column size of Matrix A: ") ;
// Creating Matrices
double matrixA[][] = new double[matrixARowSize][matrixAColumnSize] ;
double finalMatrix[][] = new double [matrixARowSize][matrixAColumnSize] ;
double tempMatrix[][] = new double[matrixARowSize][matrixAColumnSize] ;
numberOfNodes = Tools.queryForInt("Enter by how much you'd like to raise to the power: ") ;
// Creating Matrix A
for (i = 0; i < matrixARowSize; i++) {
for (j = 0; j < matrixAColumnSize; j++) {
matrixA[i][j] = Tools.queryForInt("Enter element in Matrix A" + (i+1) + "," + (j+1) + ": " ) ; }}
// Math
for (i = 0; i < matrixARowSize; i++)
{
for (j = 0; j < matrixAColumnSize; j++)
{
{
sum += Math.pow(matrixA[i][j], numberOfNodes) ;
}
finalMatrix[i][j] = sum ;
sum = 0;
}}
//Printing out matrix
System.out.println("Final: ") ;
for (i = 0; i < matrixARowSize; i++) {
for (j = 0; j < matrixAColumnSize; j++)
System.out.print(finalMatrix[i][j] + "\t") ;
System.out.println();
}
}
}
And its not working... :( lol
PS: Tools.queryForInt is a method I created to query the user...
The program itself IS working, but I am getting incorrect results. For instance,
2 2 * 2 2 = 8 8
2 2 2 2 8 8
The program would give me
4 4
4 4
So when I raise to the power of 2 it simply raises everything in the array by 2...
The way you are calculating the matrices is incorrect. Actually you are calculating powers of individual matrix element.
Before multiplying a matrix, you should check their dimensions. for AxB number of columns in A should be equal to number of columns in B. Since you are multiplying a matrix to itself, it should be a square matrix.
This is the code i use to multiply two matrices. you may modify this code to suit your requirement. I would suggest to call this module recursively or iteratively
for(int i=0;i<row;i++){
for(int j=0;i<col;i++){
for(int k=0;i<row;i++){
matrix[i][j]+=(A[i][k]*B[k][j]);
}
}
}

Categories