我正在尝试进行编码挑战,我们必须缩短和最小化方向指示。在执行while循环之前,我正在使用无序映射。其余代码按预期工作,但是while循环无法实现,因此我无法输出适当的值。
std::vector<std::string> dirReduc(std::vector <std::string>& arr)
{
enum Direction
{
NORTH = 1, SOUTH = -1,
EAST = 1, WEST = -1
};
int x=0, y=0;
std::unordered_map<std::string, Direction> uMapDir = { {"North",NORTH},{"NORTH",NORTH},
{"South",SOUTH},{"SOUTH",SOUTH},
{"East",EAST},{"EAST",EAST},
{"West",WEST},{"WEST",WEST} };
for (std::vector<std::string> ::const_iterator i =arr.begin(); i!=arr.end() ; i ++)
{
if ((*i=="North")||(*i == "NORTH")||(*i=="South")|| (*i == "SOUTH"))
{
y += uMapDir[*i];
}
else
{
x += uMapDir[*i];
}
}
std::vector<std::string> outPutArr;
while ((x!=0)&&(y!=0))
{
if (x<0)
{
x++;
outPutArr.push_back("WEST");
}
else
{
x--;
outPutArr.push_back("EAST");
}
if (y < 0)
{
y++;
outPutArr.push_back("SOUTH");
}
else
{
y--;
outPutArr.push_back("NORTH");
}
}
return outPutArr;
}
你的问题是,你正在试图做的都x
和y
在同一回路。这意味着每个循环都必须push_back
向东或向西, push_back
向南或向北。但这没有任何意义。如果每个人的号码都不相同怎么办?
相反,您应该使用两个循环:
while (x)
{
if (x<0)
{
x++;
outPutArr.push_back("WEST");
}
else
{
x--;
outPutArr.push_back("EAST");
}
}
while(y) {
if (y < 0)
{
y++;
outPutArr.push_back("SOUTH");
}
else
{
y--;
outPutArr.push_back("NORTH");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句