I
I
ilya7777412018-07-01 21:04:36
C++ / C#
ilya777741, 2018-07-01 21:04:36

How to construct another matrix from a given matrix using a formula?

Text of the problem:
Let the matrix A be given, dimension nx n. It is necessary to build a matrix B, and the elements of the matrix are built according to the following formula 5b3915fbe9e1c924546880.pngwhere the area is indicated in the figure (attached)
5b39162e7cec0557910011.png
My code:

int main()
{
  const int n=8;
  int a[n][n], b[n][n], l=0;

  for(int i=0; i<n; i++)
  {
    a[i][i]=i;
    b[i][i]=0;
  }

  b[0][0] = a[0][0];
  

  for(int i=0; i<n; i++)
  {
    for(int j=1; j<n; j++)
    {
      int min = a[0][0];

      for(int s=i; s<n; s++)
      {
        l=n/4;

        for(int d=j; d<n && n-l!=0; d++)
        {


          if(d<=n/2 && s<=n-l)
          {
            

            if(a[s][d] < min)
              min=a[s][d];	

          }

          
        }

        l++;

      }

      b[i][j]=min;

    }
  }



  for(int i=0; i<n; i++)
  {
    for(int j=0; j<n; j++)
    {
      cout<<b[i][j]<<" ";
    }
    cout<<endl;
  }

  return 0;
}

My program displays the following:
5b39177ebada6498246560.png
Please correct what is wrong in the code. I have been sitting with it for a very long time, I don’t understand what the problem is. Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FD4A, 2018-07-03
@FD4A

for(int i=0; i<n; i++)
  {
    a[i][i]=i;
    b[i][i]=0;
  }

First: here, obviously, not all array elements will be initialized. See how you print the two-dimensional array at the end:
for(int i=0; i<n; i++)
  {
    for(int j=0; j<n; j++)
    {
      cout<<b[i][j]<<" ";
    }
    cout<<endl;
  }

Similarly, it is necessary to carry out filling using two cycles. It’s also probably worth filling the matrix a with random integers (the rand() function) and outputting both matrices a and b.
Filling:
for(int i=0; i<n; i++){
    for(int j=0; j<n; j++){
         a[i][j]=rand();
         b[i][j]=-1;
    }
}

Further, in the second cycle, we start bypassing the columns from the second one.
Why not from the first one with index 0? After all, you need to get an answer for each element in the matrix b.
As soon as you get the correct filling, you need to take a piece of paper and think about how to get a minimum in the theta area. In the first column of the matrix b in the i-th row there is clearly an element that is less than all the others passed before it. It follows from this that it is possible to use an intermediate matrix C whose element i,j is the minimum in the given part of column j from its beginning to row i. And then if you need to get b (i, j) you just need to take the minimum of the elements on the "diagonal" border of the theta region in the matrix C.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question