# Demo entry 6783543

Homework

Submitted by Alexey on Feb 15, 2019 at 23:16
Language: C++. Code size: 2.8 kB.

```#include <iostream>
#include <vector>
using namespace std;
struct Topo {
int N,Nz;
vector<int> IA, JA;
};
class Grid {
public:
Grid() {NE = nullptr; EN = nullptr;}
~Grid();
void generate(int nx,int ny, int K3, int K4);
void print();
private:
int nodesAmount;
void ENtoNE();
Topo *NE,*EN;
};

vector<int> getElementVertices(int nx, int ny, int curr)
{
vector<int> result;
result.push_back(curr/nx*(nx+1)+curr%nx);
result.push_back(result.back()+1);
result.push_back(result.front()+nx+2);
result.push_back(result.back()-1);
return result;
}

Grid::~Grid() {
if (EN!=nullptr) {
delete NE;
delete EN;
}
}

void Grid::generate(int Nx,int Ny, int K3, int K4) {
if (EN!=nullptr) {
delete EN;
}
EN = new Topo;
EN->N = 0;
EN->Nz = 0;
EN->IA.push_back(0);
for(int curr=0; curr<Nx*Ny; curr++) {
vector<int> vertices;
vertices = getElementVertices(Nx, Ny, curr);
if (curr%(K3+K4)/K3 == 0) {
//divide into triangles
EN->N+=2;
EN->Nz+=6;
EN->IA.push_back(EN->IA.back()+3);
EN->IA.push_back(EN->IA.back()+3);
EN->JA.push_back(vertices[0]);
EN->JA.push_back(vertices[1]);
EN->JA.push_back(vertices[3]);
EN->JA.push_back(vertices[1]);
EN->JA.push_back(vertices[2]);
EN->JA.push_back(vertices[3]);
}
else {
EN->N+=1;
EN->Nz+=4;
EN->IA.push_back(EN->IA.back()+4);
EN->JA.push_back(vertices[0]);
EN->JA.push_back(vertices[1]);
EN->JA.push_back(vertices[2]);
EN->JA.push_back(vertices[3]);

}
}
nodesAmount = (Nx+1)*(Ny+1);
ENtoNE();
}

void Grid::ENtoNE() {
if (NE!=nullptr)
delete NE;
NE = new Topo;
NE->N = nodesAmount;
NE->IA.assign(NE->N+1,0);
for (auto i: EN->JA)
NE->IA[i+1]++;
for (int i=1; i<NE->N+1 ;i++)
NE->IA[i]+=NE->IA[i-1];
NE->Nz = EN->Nz;
NE->JA.assign(NE->Nz,0);
for (int i=0, currElem=0; i<EN->Nz; i++) {
int offset;
offset = NE->JA[NE->IA[EN->JA[i]+1]-1];
NE->JA[NE->IA[EN->JA[i]]+offset] = currElem;
if(NE->IA[EN->JA[i]]+offset+1<NE->IA[EN->JA[i]+1])
NE->JA[NE->IA[EN->JA[i]+1]-1]++;
if (i==EN->IA[currElem+1]-1)
currElem++;
}
}

void Grid::print() {
cout<<endl<<"E->N     IA"<<endl;
for (auto i: EN->IA)
cout<<i<<' ';
cout<<endl<<"E->N     JA"<<endl;
for (auto i: EN->JA)
cout<<i<<' ';
cout<<endl<<"N->E     IA"<<endl;
for (auto i: NE->IA)
cout<<i<<' ';
cout<<endl<<"N->E     JA"<<endl;
for (auto i: NE->JA)
cout<<i<<' ';
cout<<endl;
}

int main(int argc, char**argv) {
Grid grid;
int Nx,Ny,K3,K4;
do {
cout<<"Enter natural Nx, Ny, K3, K4"<<endl;
cin>>Nx>>Ny>>K3>>K4;
} while(Nx<=0 || Ny<=0 || K3<=0 || K4<=0);
grid.generate(Nx,Ny,K3,K4);
grid.print();
return 0;
}
```

This snippet took 0.02 seconds to highlight.

Back to the Entry List or Home.