【发布时间】:2018-02-19 01:48:46
【问题描述】:
注意:这是课堂作业,必须以这种方式完成,我知道这效率低下,我并不是要求我完成作业,我只是需要一些指导我做错了什么。
我想创建一个函数,生成所有可能的井字游戏组合,格式为“xoxxooxox”,每三个字母代表一排棋盘。当我调用函数时,我需要它返回一个向量。
到目前为止,我所拥有的是一个 循环,它可以生成 0,1 和 2 的所有可能的 9 位组合,直到 19683,这只是 3^9 的板组合。然后我让它将 0 转换为 #(这意味着一个空格),将 1 转换为“o”,将 2 转换为“x”。
#include<iostream>
#include<vector>
#include<string>
using namespace std;
vector<string> get_all_boards() {
vector<int> numboard;
std::string board;
for(int i = 0; i < 19683; ++i) {
int c = i;
for (int j = 0; j < 9; ++j) {
int playnum = c % 3;
if (playnum == 0) {
playnum = 35;
numboard.push_back(playnum);
} else if (playnum == 1) {
playnum = 111;
numboard.push_back(playnum);
} else if (playnum == 2) {
playnum = 120;
numboard.push_back(playnum);
}
c /= 3;
}
for (auto x : numboard) {
board += static_cast<char>(x);
}
std::copy( board.begin(), board.end(), std::back_inserter(numboard));
}
}
int main() {
get_all_boards();
}
我不确定如何检查它是否在输出我想要的内容,并且我收到“错误分配”的错误。有没有更有效的方法来做到这一点?如何修复错误的分配错误?
【问题讨论】:
-
board 是您尝试将 int 放入的字符串向量
-
你知道很多 19683 组合是不可能的吧?例如“呜呜呜”……
-
补充@John3136 所说的,您需要消除已经赢得/平局的位置(继续比赛没有意义),并考虑将删除大量重复位置的旋转和反射。
-
使用极小极大算法解决最佳可能移动
-
你不会 static_cast int's to char 来获得一个 int 的字符串表示。将 int 转换为 char 使用 ASCII 表进行转换。
标签: c++ c++11 vector tic-tac-toe