Solução apenas com 2 ciclos

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
1.4 kB
4
Indexable
Never
#include <iostream>
#include <vector>
#include <math.h>

using namespace std;

int
main ()
{
  vector < int >board = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  int sizeVector = board.size ();
  int N = sqrt (board.size ());
  int horizontal[N][N];
  int vertical[N][N];
  int diagonal[2][N];

  cout << endl << "Board: " << N << "x" << N << " | Vector Size: " << sizeVector << endl;
  for (int i = 0; i < sizeVector; i += N)
    {
      for (int j = 0; j < N; j++)
	{
	  //cout << "i: "<<i<<", j: "<<j<<endl;
	  cout << board[i + j];
	}
      cout << endl;
    }
  cout << endl << "Solutions Vectors" << endl;

  for (int i = 0, x = 0; i < sizeVector; i += N)
    {
      for (int j = 0, y=0, jinv=N-1; j < N; j++, jinv--, y+=N)
        {
          horizontal[x][j]=board[i+j];
          cout<<"horizontal["<<x<<"]["<<j<<"]= "<<horizontal[x][j]<<" | ";
          vertical[x][j]=board[x+y];
          cout<<"vertical["<<x<<"]["<<j<<"]= "<<vertical[x][j]<<endl;
          if(x==j)
          {
            diagonal[0][x]=board[i+j];
          }
          if(x==jinv)
          {
            diagonal[1][x]=board[i+j];
          }
        }
      cout << endl;
      x++;
    }
    
    for(int i=0; i<2; i++)
    {
        cout<<"diagonal["<<i<<"]= ";
        for(int j=0; j<N;j++)
        {
            cout<<diagonal[i][j]<<" ";

        }
        cout<<endl;
    }
    

  return 0;
}