signed

QiShunwang

“诚信为本、客户至上”

生成一个随机生成的二维颗粒模型

2021/5/14 21:10:49   来源:

说明:
1.最大半径=15,最小半径=5
2.最小间距=5
3.整体尺寸为300*500
4.长边为周期性边界

C++代码如下:

#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;
//nx>ny
const int nx = 500;
const int ny = 300;
const int rmin = 5;
const int rmax = 15;
const int minmedium = 5;
int matrix[nx][ny]{ 0 };

class Particle {
public:
	Particle(int x_, int y_, int r_) :x(x_), y(y_), r(r_) {}
	int x, y, r;
};

int generate(vector<Particle>& particles) {
	int count = 0;
re:	
	int x = rand() % ny + (nx - ny) / 2;
	int y = rand() % ny;
	int r = rand() % (rmax - rmin) + rmin;
	for (const auto& particle : particles) {
		if (sqrt((particle.x - x) * (particle.x - x) + (particle.y - y) * (particle.y - y)) < particle.r + minmedium + r||
			sqrt((particle.x - x) * (particle.x - x) + (particle.y - (y + ny)) * (particle.y - (y + ny))) < particle.r + minmedium + r|| 
			sqrt((particle.x - x) * (particle.x - x) + (particle.y - (y - ny)) * (particle.y - (y - ny))) < particle.r + minmedium + r) {
			count++;
			if (count > 1000) {
				return -1;
			}
			goto re;
		}
	}

	Particle newParticle(x, y, r);
	particles.push_back(newParticle);
	return 0;
}

template <int X,int Y>
void makematrix(vector<Particle>& particles, int(&matrix)[X][Y]) {
	for (auto const& ele : particles) {
		int cx = ele.x, cy = ele.y, radius = ele.r;
		for (int i = 0; i < X; i++) {
			for (int j = 0; j < Y; j++) {
				if (sqrt((i - cx) * (i - cx) + (j - cy) * (j - cy)) < radius||
					sqrt((i - cx) * (i - cx) + ((j + ny) - cy) * ((j + ny) - cy)) < radius||
					sqrt((i - cx) * (i - cx) + ((j - ny) - cy) * ((j - ny) - cy)) < radius) {
					matrix[i][j] = 1;
				}
			}
		}
	}
}

template <int X, int Y>
void out_file(const string& str,int(&matrix)[X][Y]) {
	ofstream outfile;
	outfile.open(str);
	for (int i = 0; i < X; i++) {
		for (int j = 0; j < Y; j++) {
			outfile << matrix[i][j] << " ";
		}
		outfile << endl;
	}
	outfile.close();
	return;
}

int main() {
	vector<Particle> particles;
	particles.push_back(Particle(nx / 2, ny / 2, (rmin + rmax) / 2));

	srand(time(NULL));
	for (int i = 0; i < 300; i++) {
		if (generate(particles) == -1) {
			cout << "wrong!!!" << endl;
		}
	}

	for (const auto& ele : particles) {
		cout << ele.x << " " << ele.y << " " << ele.r << endl;
	}

	makematrix(particles, matrix);

	out_file("../demo.txt", matrix);

	return 0;
}

生成一个由0和1组成的文件,截图如下
随机颗粒图