Wednesday, August 1, 2018

#codingexercise
1) We were discussing a technique to count subsets of an array divisible by m:
For {1,2,3} set, we have the dp table as : 
    0  1 2 3 4 5 6 
0  1   
1  1  1 
2  1  1 1 1 
3  1  1 1 2 1 1 1 
count = 3 
Solution: The possible subsets are {1} {2} {3} {1,2} {2,3}, {1,3} and {1,2,3} with sums as 1,2,3,3,5,4 and 6 respectively. Therefore count is 3. 
int GetCountSubseqSumDivisibleBy(List<int> A, int m)  
 
var dp = new int[ A.Count() + 1, A.Sum() + 1];  
for (int i = 0; i < A.Count(); i++){  
     dp[i, 0]++;  
 
for (int i = 1; i <= A.Count(); i++) {  
     dp[i, A[i-1]]++;  
     for (int j = 1; j <= A.Sum(); j++){  
         if (dp[i-1, j] > 0) {  
             dp[i, j]++;  
             if (j + A[i-1] <= A.Sum()) {  
                 dp[i, j + A[i-1]]++;  
             }  
         }  
     }  
 
int count = 0;  
for (int j = 1; j <= A.Sum(); j++) {  
     if (dp[A.Count(), j] > 0 && j % m == 0)  
         count += dp[A.Count, j];  
}   
return count;  
 


No comments:

Post a Comment