I tried searching for the solution to this problem for a while now and couldn't find anything. How do I sum the elements above the secondary diagonal in a matrix (just with loops, nothing fancy) in Java?
This is what I tried:
public static void Page106Ex3$H(int[][] mat) {
int sum = 0;
for (int i = 1; i < mat.length; i++) {
for (int j = i-1; j >= 0; j--) {
sum += mat[i][j];
}
}
System.out.println("Sum: " + sum);
}
For square matrix of any order you can use this code,
This code has answer for both primary and secondary diagonals and are separated by comments in the code
private static void calcDiagonalSumMatrix(int[][] mat) {
int sum = 0, leftDiagonal = 0, rightDiagonal = mat[0].length - 1;
//This loop is for primary diagonal
for (int[] ints : mat) {
sum += ints[leftDiagonal++];
}
//This loop is for secondary diagonal
for(int [] intArray: mat) {
sum += intArray[rightDiagonal--];
}
//This loop is what you have to use
for(int x = 0; x < matrix.length; x++) {
rightDiagonal--;
for(int y = rightDiagonal; y >=0; y--) {
sum += mat[x][y];
}
}
System.out.println(sum);
}
Explanation :
Three integers variables are declared one to calculate sum then the leftDiagonal is to calculate the index of top left to bottom right diagonal and the rightDiagonal is used as index of top right to bottom left diagonal.
Then using the enhanced for loops or foreach loops, calculate the sum of the leftDiagonal and that same of right diagonal.
In each for loop for left diagonal the loop first picks the first set of array then the leftDiagonal variable which acts as the index will start from 0 and increase by one for each loops and the same goes for the rightDiagonal except the right diagonal starts from the order - 1 which is the index of the top right element.
Then the third loop actually has two loop, the outer loop will be taking the int array elements then the innermost loop will loop through the elements that the first loop took and adds up the elements from each int[] set excluding the secondary diagonal elements.
If the elements on the secondary are not included, the number of columns in the nested loop should be decremented with indexes starting from 0.
public static int sumOver2ndDiagonal(int[][] arr) {
int sum = 0;
for (int i = 0, n = arr.length - 1; i < n; i++) {
for (int j = 0, m = arr[i].length - 1 - i; j < m; j++) {
sum += arr[i][j];
}
}
return sum;
}
Test:
System.out.println(sumOver2ndDiagonal(
new int[][]{
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12},
{13, 14, 15, 16}
}
));
// 1 + 2 + 3 + 5 + 6 + 9
// -> 26
The secondary diagonal element in row i is present at (mat.length-i-1). In a row all the elements before the element present at secondary diagonal comes above the secondary diagonal we need to add them.
The below solution is considering indexing start from 0.
public static void Page106Ex3$H(int[][] mat) {
int sum = 0;
int n = mat.length;
for (int i = 0; i < n; i++) {
int j = n - i - 2; // index of element just before the
// secondary diagonal element in row i
while(j >= 0){
sum += mat[i][j];
j--;
}
}
System.out.println("Sum: " + sum);
}
Related
I am trying to understand the SelectionSort for arrays.
If I understand it correctly, it compares the element[minimum] with the next elements element[i] and swaps positions if element[i] < element[minimum]. Then it repeats this with element[i + 1] until the list is sorted.
Now when I try it with the following code, I get an incorrect sort and can't figure out what I'm doing wrong.
public static void SelectionSort1(int[] list){
for (int i = 0; i < (list.length - 1); i++){
int min = i;
for (int j = i + 1; j<list.length; j++){
if(list[j] < list[min]){
min = j;
}
int smallernumber = list[i];
list[i] = list[min];
list[min] = smallernumber;
}
}
}
public static void main (String [] args){
int[] list = {5,4,2,1,3};
System.out.println("Before Sort" + Arrays.toString(list));
SelectionSort1(list);
System.out.println("After Sort " + Arrays.toString(list));
}
My output is:
Before Sort[5, 4, 2, 1, 3]
After Sort [2, 3, 1, 4, 5]
Can anyone point me in the right direction?
Your understanding is almost correct, it compares the element[minimum] with the next elements element[j] and if element[j] < element[minimum] then the minimum index is equal to j. Then it repeats until j reaches the end of the array. After it swaps the index at element[i] with element[minimum].
What this is doing is swapping element[i] with the smallest number to the right of index i. Then moving index i to the next spot. Repeating this gives you a sorted array.
TLDR:
Move the swapping outside of the second for loop. It should be:
public static void SelectionSort1(int[] list){
for (int i = 0; i < (list.length - 1); i++){
int min = i;
for (int j = i + 1; j<list.length; j++){
if(list[j] < list[min]){
min = j;
}
}
int smallernumber = list[i];
list[i] = list[min];
list[min] = smallernumber;
}
}
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();
}
I'm just a beginner. I came across this question for which my code fails to satisfy all/most of the test cases.
Question:
Given an array of numbers, find the number of non-empty sub-arrays in which the minimum and maximum element are identical.
Example:
Input: Array = [1, 1, 3]
Output: 4
Explanation:
The required sub-arrays are [1], [1], [3], [1,1]
My solution:
Sort the array and solve the problem.
Code:
for(int i = 0; i < testCases; i++){
int arraySize = in.nextInt();
int array[] = new int[arraySize];
for(int j = 0; j < arraySize; j++){
array[j] = in.nextInt();
}
temp[i] = (findSubArrays(array));
}
for(int i = 0; i < testCases; i++){
System.out.println(temp[i]);
}
private static int findSubArrays(int[] array) {
Arrays.sort(array);
//Since each element can form a sub-array of its own
int noOfSubArrays = array.length;
for(int i = 0; i < array.length-1; i++){
if(array[i] == array[i+1]){
noOfSubArrays++;
}
}
return noOfSubArrays;
}
So you're sorting the array to keep begin points and end points adjacent so you don't need a nested traversal. That makes sense. The problem is that you're counting adjacent duplicates, but what you really need is T(n), or the triangle number of consecutive duplicates. Consider a simple scenario:
[1, 1, 1]
Your algorithm returns 5, but there are actually 6 subsets (by start & end index):
0, 0
0, 1
0, 2
1, 1
1, 2
2, 2
So let's update the algorithm to calculate the triangle number of each sequence:
private static int findSubArrays(int... array) {
Arrays.sort(array);
int sequenceCount = 0;
int total = 0;
for (int i = 0; i < array.length + 1; i++) {
if (i == array.length || (i > 0 && array[i] != array[i - 1])) {
total += triangle(sequenceCount);
sequenceCount = 0;
}
sequenceCount++;
}
return total;
}
private static int triangle(int n) {
return (n * (n + 1)) / 2;
}
Now calling findSubArrays(1, 1, 1) returns 6 and findSubArrays(1, 1, 3) returns 4.
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]);
}
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 .