-2

I have this matrix and I want to find a algorithm that can find all values = 1 and give give me the count of how many there are.

My matrix look like this and have the size n x n:

44444444
4 4 1  4
4 4  444
4444  44
4   1 34   
444  444
44    44
44444444

Right now I don't know what kind of algorithm I have to use.

Eyal Schneider
  • 21,096
  • 4
  • 43
  • 73

1 Answers1

1

If it is a parsing problem then,

int count = 0;
for(int i=0;i<n;i++)
{
    for(int j=0;j<n;j++)
    {
        if(isdigit(matrix[i][j] && matrix[i][j]!='0')
        {
            int sum = 0;
            int tenPower = 1;
            for(;j<n && isdigit(matrix[i][j];j++)
            {
                sum = sum*tenPower+(matrix[i][j]-48);
                tenPower*=10;
            }
            if(sum == 1)count++;
            j--; 
         }
     } 
 }
 printf("%d\n",count);
Tahlil
  • 2,550
  • 4
  • 36
  • 71
  • Are you sure the second approach is faster?The time complexity for the second approach is O((n^2)logn ) – Pham Trung Apr 24 '14 at 09:22
  • no, it's not 2*n(log n), because every time you sorted a row with n element, the time complexity is O(nlogn), and you have n rows, which result in n*O(nlogn), which is O(n^2logn) – Pham Trung Apr 24 '14 at 09:26
  • You can never do better than n^2, because the number of character is n^2, how do you solve this problem with reading less than n^2 characters? Please think more carefully about this – Pham Trung Apr 24 '14 at 09:27