delete
delete

Reputation:

How can I get the sum of numbers from a diagonal line?

Here is the sum for a diagonal top-left to bottom-right:

public int sumarDiagonal()
{
    int x = 0;
    for (int F = 0; F < Filas; F++)
    {
        for (int c = 0; c < Columnas; c++)
        {
            if (F == c)
            {
                x += m[F,c];
            }
        }
    }
    return x;
}

How can I go from top-right to bottom-left?

Upvotes: 1

Views: 2696

Answers (5)

   public int diagX()
        {
            int x;
            x = 0;

        for (f = 1; f <= filas; f++)
          {
           for (c = columnas; c >= 1; c--)
               {
                   if (f > c || f < c)
                   {
                       x += a[f, c];
                   }
                   else
                   {
                       continue;
                   }
                }
          }
        return x;
        }

for example this code : if you have 1 , 2 3 , 6 and you want to across diag you must take a[2, 1] you will get 2. and at the looping you've give continue on the else because after get value 2. it will be a[2, 2] because f == c as false then you break not come back to first loop. why f==c is false because if you want search across diag of matrix you cant get value from f == c. for example: if matrix above we loop but can equals f and c. we can get: (a[2, 1] = 2) + (a[2, 2] = 6) = 8 nah! you can see the big false at this code.

Upvotes: 0

Lo&#239;c F&#233;vrier
Lo&#239;c F&#233;vrier

Reputation: 7750

You don't actually need to look at every coefficient :

public int sumarDiagonal()
    {
        int x = 0;
        int length = Math.Min(Filas,Columnas); // Can deal with rectangular cases
        for (int i = 0; i < length; i++)
            x += m[i,length-1-i];
        return x;
    }

Upvotes: 1

Henrik
Henrik

Reputation: 23324

Your original code with two nested loops is not very efficient. Better do it like this:

public int sumarDiagonal() 
{ 
 int x = 0; 
 for (int i = 0; i < Math.Min(Filas,Columnas); ++i) 
  x += m[i,i]; 
 return x; 
} 

public int sumarAntiDiagonal() 
{ 
 int x = 0; 
 for (int i = 0; i < Math.Min(Filas,Columnas); ++i) 
  x += m[Filas - 1 - i,i]; 
 return x; 
} 

Upvotes: 2

Pedro
Pedro

Reputation: 12328

How about replacing

if (F == c)

with

if (F + c + 1 == Filas)

Edit: Updated to account for 0-based array

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630559

Just reverse your indexes, like this:

public int sumarDiagonal()
{
   int x = 0;
   for (int F = 0; F < Filas; F++)
   {
      x += m[F,Filas-F-1];
   }
   return x;
}

This assumes a square array, so for say 10x10, the first point is [0, 9], the second [1, 8], etc.

Upvotes: 0

Related Questions