Harshad Matrix Infosys springboard coding question with solution

Problem Statement :

Given a m x n matrix inmatrix of positive integers, write a program to print outmatrix based on the below logic:

• Identify all 2×2 sub-matrix/matrices in inmatrix where each element is a Harshad number A number is a Harshad number if it is divisible by sum of its digits 

If such matrix/matrices exist(s), print them in the order of their occurrence in inmatrix ie. row wise from left to right.

If no such matrix exists, print -1

Assumption:

• m and n will be greater than 1

Question :

Code Solution :

				
					def DigitsSum(n):
    L=[int(i) for i in str(n)]
    return sum(L)
    
def IsHarshad(L):
    for x in L:
        for y in x:
            if (y% DigitsSum(y)!=0):
                return False
    return True
    
m=int(input())
L=[]
for i in range(m):
    L1=[int(i) for i in input().split(",")]
    L.append(L1)
n=len(L[0])
flag=False
for i in range(m-1):
    for j in range(n-1):
        R=[]
        R1=L[i][j:j+2]
        R2=L[i+1][j:j+2]
        R.extend([R1,R2])
        if (IsHarshad(R)==True):
            flag=True
            print(*R[0],sep=",")
            print(*R[1],sep=",")
            
if (flag==False):
    print(-1)
				
			

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published.