Consider a square matrix A of size NxN and an integer x which is an element of matrix A. Find the number R and colunm number C of x in A. And also calculate the sum of R and C. If the sum is even, find the sum of the digits of all even numbers in the matrix, and if the sum is odd, then find the sum of digits of all odd numbers in the matrix.
Read the input from STDIN and print the output to STDOUT. Do not write arbitary strings while reading the input as these contribute to the standard output.
Constraints:
- 1<N<=35
- 0<=R,C<N
- x is always an element of A
- Elements of A are unique
Input Format:
The first line of input contains N
The next N lines of input contains N integers, each separated by a single white space.
The last line of input contains x
Output Format
The output contains S.
Sample Test Cases
Example1:
Input:
3
11 22 33
44 55 66
77 88 99
55
Output:
40
Explanation:
Here x=55 is present at the second row and second column of thegiven matrix A. so R=2 , C=2 therfore R+C=4
There fore S=(2+2)+(4+4)+(6+6)+(8+8)= 4+8+12+16= 40
Hence the output is 40
Example2:
input:
4
454 55 521 14
78 326 104 989
23447 174 87 845
25 81 53 11
104
Output:
122


Algorithm to solve
- Take the input from user that is Matrix A and the key element (x).
- Now with the help of nested for loop find the R and C values.
- Add R and C and divide sum by 2 if remainder is 0 the find the sum of the digits of even numbers as specified in below steps else find sum of digits of odd numbers.
- For even sum: take each and every element from matrix A using while loop keep dividing the number by 10 until it is less than 10 itself. parallely keep adding the remainder to sum variable.
- For odd sum : take each and every element from matrix and follow the same steps specified above to find the sum of digits of all odd numbers.
- Once gettinf the sum then print it to screen.
JAVA CODE
package arrayPrograms; import java.util.*; class Problem10 { public static void main(String[] args) { // Coded by VRASHIKESH PATIL int N=3; int[][] array1= {{454,55,521,14},{78,326,104,989},{23447,174,87,845},{25,81,53,11}}; int key=104; int R=0,C=0; int S=0; for(int i=0;i<array1.length;i++) { for(int j=0;j<array1[i].length;j++) { if(array1[i][j]==key) { R=i+1; C=j+1; } } } for(int i=0;i<array1.length;i++) { for(int j=0;j<array1[i].length;j++) { if(array1[i][j]%2==0 && (R+C)%2==0) { int rem=0; while(array1[i][j]!=0) { rem=array1[i][j]%10; array1[i][j]=array1[i][j]/10; S=S+rem; } } else if(array1[i][j]%2!=0 && (R+C)%2!=0){ int rem=0; while(array1[i][j]!=0) { rem=array1[i][j]%10; array1[i][j]=array1[i][j]/10; S=S+rem; } } } } System.out.println(S); } }
Watch complete explanation for above code
Similar off campus coding question you might like
Finding all substrings of given string in JAVA
SHL off campus coding question solved
Pingback: Saddle points in 2D array off campus problem solved - Is It Actually
Pingback: Count number of palindrome words in given sentance - Is It Actually