天天看點

細胞分裂模拟

功能:

        一種細胞在誕生(即上次分裂)後會在500~2000秒内分裂為兩個細胞,每個細胞又按照同樣的規律繼續分裂。

        本程式模拟了細胞分裂的過程,輸出了每個細胞分裂的時間。

環境:VS2010。

           控制台應用程式。

程式:

// cell_split_simulation_use_priority_queue.cpp : 定義控制台應用程式的入口點。
//細胞分裂模拟,輸出每個細胞分裂的時間
//一種細胞在誕生(即上次分裂)後會在500~2000秒内分裂為兩個細胞,
//每個細胞又按照同樣的規律繼續分裂。
//

#include "stdafx.h"
#include<queue>
#include<iostream>
#include<cstdlib>  //cstdlib是C++裡面的一個常用函數庫, 等價于C中的<stdlib.h>。提供一些函數與符号常量。
#include<ctime>

using namespace std;

const int SPLIT_TIME_MIN=500;
const int SPLIT_TIME_MAX=2000; //細胞分裂最短和最長時間

class Cell;
priority_queue<Cell>cellQueue;

class Cell   //細胞類
{
private:
	static int count;  //細胞總數
	int id;            //目前細胞編号
	int time;          //細胞分裂時間
public:

	Cell(int birth):id(count++)  //birth為細胞誕生時間
	{
		//初始化,确定該細胞分裂時間
		time=birth+(rand()%(SPLIT_TIME_MAX - SPLIT_TIME_MIN)) + SPLIT_TIME_MIN;
	}

	int getId()const
	{
		return id; //得到細胞編号
	}

	int getSplitTime()const
	{
		return time; //得到目前細胞分裂時間
	}

	bool operator < (const Cell & s) const
	{
		return time > s.time;  //定義“<”
	}

	void split()  //細胞分裂
	{
		Cell child1(time),child2(time);  //建立兩個子細胞
		cout<<time<<"s : Cell #"<<id<<" splits to #"<<child1.getId()<<"and #"<<child2.getId()<<endl;
		cellQueue.push(child1);//将第一個細胞壓入優先級隊列
		cellQueue.push(child2);//将第二個細胞壓入優先級隊列
	}
};

int Cell::count = 0;

int _tmain(int argc, _TCHAR* argv[])
{
	srand(static_cast<unsigned>(time(0)));
	int t;                   //使用者定義模拟細胞分裂的時間長度
	cout<<"Stimulation time:";
	cin>>t;

	cellQueue.push(Cell(0)); //将第一個細胞壓入優先級隊列

	while(cellQueue.top().getSplitTime() <= t)
	{
		cellQueue.top().split(); //模拟下一個細胞的分裂
		cellQueue.pop();         //将剛剛分裂的細胞彈出
	}

	int a;
	cin>>a;  //防止程式閃退

	return 0;
}

           

運作結果:

細胞分裂模拟

補充:

随機函數:rand()

時間函數:time() ,獲得一個以整數表示的目前時間(精确到秒)。

每個細胞按照産生的順序從小到大編号,

每個細胞對象有一個分裂時間:誕生時間+随機的時間差

細胞類Cell的“<”運算符:按照細胞分裂時間的反序定義的,即如果a對象比b象分裂時間要晚,那麼就有a<b。

繼續閱讀