您的位置:首页 > 编程语言 > C语言/C++

利用std::set和遍历骰子的24种可能(人面向骰子)

2015-03-03 04:56 239 查看
筛子如下图,有六个







rotate.h

#include <string>
void swap(char& a, char& b, char& c, char& d){
char temp=a;
a=b;
b=c;
c=d;
d=temp;
}

string rotate(string dice,int rotation){
// rotation:top 1,back 2,right 3,front 4,left 5, down 6
switch(rotation){
case 1://roll front
{
swap(dice.at(4-1),dice.at(1-1),dice.at(2-1),dice.at(6-1));
break;
}
case 2://roll back
{
swap(dice.at(6-1),dice.at(2-1),dice.at(1-1),dice.at(4-1));
break;
}
case 3://roll left
{
swap(dice.at(1-1),dice.at(3-1),dice.at(6-1),dice.at(5-1));
break;
}
case 4://roll right
{
swap(dice.at(5-1),dice.at(6-1),dice.at(3-1),dice.at(1-1));
break;
}
case 5://rotate left
{
swap(dice.at(2-1),dice.at(3-1),dice.at(4-1),dice.at(5-1));
break;
}
case 6://rotate right
{
swap(dice.at(5-1),dice.at(4-1),dice.at(3-1),dice.at(2-1));
break;
}
default:break;
}
return dice;
}

printdice.hh

#ifndef PRINTDICE_HH
#define PRINTDICE_HH
#include <string>
#include <set>
void printdices(std::set<string> & dices,string dice){
if(dices.size()==(unsigned)24) return;
//cout<<"size of the set:"<<dices.size()<<endl;
std::set<string>::iterator it;
bool isexist=false;
for(it=dices.begin();it!=dices.end();++it){
std::string temp=*it;
if(temp.compare(dice)==0){
isexist=true;
}
}
if(isexist==false){
cout<<dice<<endl;
dices.insert(dice);
}else{
return;
}
for(int i=1;i<=6;++i){
//cout<<"i:"<<i<<endl;
string temp=rotate(dice,i);
printdices(dices,temp);
}
}
#endif // PRINTDICE_HH



main.cc

#include <iostream>
using namespace std;
#include "complex.hh"
#include "rotate.hh"
#include "printdice.hh"

int main()
{
//program2
 string dice2="145326";
cout<<"start: "<<dice2<<endl;
cout<<"roll front: ";
cout<<rotate(dice2,1)<<endl;
cout<<"turn left: ";
cout<<rotate(dice2,5)<<endl;
//program3
string dice3="145326";
std::set<string> set_dices;
printdices(set_dices,dice3);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ dice 骰子 递归 set