有n个人围成一圈,顺序排号。 从第一个人开始报数(从1到3报数), 凡报到3的人退出圈子,问最后留下的是原来第几号的那位。

我的想法是先创建一个Person类包含自身序号和数字,在借助vector容器从而实现,人数和出局数字都经过宏定义来实现,便于代码后续维护和修改

#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>

#define Num_person 10
#define Num_out 3
using namespace std;

class Person
{
public:
	Person(int h, int n)
	{
		this->m_hao = h;
		this->m_num = n;
	}
	int m_hao;
	int m_num;

};

class Myprint
{
public:
	void operator()(Person& p)
	{
		cout << "编号为" << p.m_hao << "数字为" << p.m_num << endl;
	}
};

vector<Person> init_vector()
{
	vector<Person> v;
	for (int i = 1; i < Num_person; i++)
	{
		Person p(i, 0);
		v.push_back(p);
	}
	return v;
}

void printPerson(vector<Person>& v)
{
	for_each(v.begin(), v.end(), Myprint());
}

void Random(vector<Person>& v)
{
	random_shuffle(v.begin(), v.end());
	cout << "随机后的排序为:" << endl;
	//printPerson(v);
}

void kick_person(vector<Person>& v) //出局函数
{
	for (vector<Person>::iterator it = v.begin(); it != v.end(); )
	{
		if (it->m_num == Num_out)
		{
			it = v.erase(it); //erase的返回值为下一个元素的地址
		}
		else
			it++;
	}
}

void Num_Assgin(vector<Person>& v) //给人排号
{
	static int j = 1;
	for (vector<Person>::iterator it = v.begin(); it != v.end(); it++) //分配数字
	{
		it->m_num = j++;
		if (j == Num_out + 1)
			j = 1;
	}
}

void Joseph(vector<Person>& v)
{
	Num_Assgin(v);
	printPerson(v);
	cout << endl;
	while (v.size() != 1)
	{
		kick_person(v);
		printPerson(v);
		cout << endl;
		Num_Assgin(v);
	}
	cout << endl;
	printPerson(v);
}

int main()
{
	srand((unsigned int)time(NULL));
	vector<Person> v = init_vector();
	Random(v);
	Joseph(v);
	/*kick_person(v);
	cout << endl;
	printPerson(v);*/
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值