Jump to content

displaying sums in matrix using recursion

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
adiga

adiga

    Newbie

  • Members
  • Pip
  • 3 posts
hello everyone,

i am trying to find all the sums possible in a matrix.
these sums should be linear and horizontal. for example in the next matrix:

{ { 1, 5, 3 },
{ 2, 7, 4 } ,
{ 9, 0, 6 } };

i will write some of the linear sums manually...

1+5+3=9
1+5+4=10
1+5+6=12
1+7+3=11
1+7+4=12
1+7+6=14
1+0+3=4
1+0+4=5
1+0+6=7

there are many more sums starting from 2 and 9.

now i want to write a function which will display all of them, or just put them in an array or stack. i think the function must be recursive...
i tried to write it a couple of times but i couldnt find a way.

can anyone help?

thanks,
adiga

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
I think you need to clarify: in what sense does 1+5+4 represent a horizontal sum?

Are you saying you want to find every sum where you pick one number from each column? If so, you can do this with nested for loops, one for each column.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
adiga

adiga

    Newbie

  • Members
  • Pip
  • 3 posts
the sum should contain one number from each column. no matter from which row it is.

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts

for(int i=0;i<3;i++)

  for(int j=0;j<3;j++)

    for(int k=0;k<3;k++)

      cout<<array[0][i]<<'+'<<array[1][j]<<'+'<<array[2][k]<<'='<<array[0][i]+array[1][j]+array[2][k]<<'\n';


Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#5
adiga

adiga

    Newbie

  • Members
  • Pip
  • 3 posts
yeah but im talking about any matrix in general... the code you just gave is specific to a matrix with 3 rows...


you just gave me an idea:


function1(.... , .... , ....,  j)

{

      if(j==mat.length(1)-1) return mat[i][j];

      for(int i=0........)

      {

               ............

              function1(.... , .... , .... , j+1)

      }

}



its just an algorithm, but i think it will work! i'll update you later