如何应对结果的无限可能性?

How to respond to a limitless possibility of outcomes?

本文关键字:无限可能 可能性 无限 何应 结果      更新时间:2023-10-16

所以假设有一个虚构的 2 x 2 网格由 4 个数字组成......

1 2
3 4

您可以通过分别插补HV来水平或垂直向下翻转网格。您还可以根据需要多次翻转网格,之前的选择会影响您未来的结果。

例如,您可以从中间水平翻转网格,然后垂直翻转。

在解决这个问题时,我写下了足够的代码,以便程序工作,除了发生"翻转"的部分。由于您可以根据需要输入任意数量的HV,因此我在编写支持此操作的代码时遇到了一些麻烦。

由于程序输入可以包含用户喜欢的任意数量的水平或垂直翻转,这阻止了我手动使用 if 语句;换句话说,我不能说"如果第一个字母是H,水平翻转,如果第二个字母是V,垂直翻转等"。

这只是我到目前为止所发现的一小部分......

void flipGrid(string str, int letterPlace)
{
while (letterPlace < str.length())
{
if (str.at(letterPlace) == 'H')
{
// flip grid horizontally
}
else if (str.at(letterPlace) == 'V')
{
// flip grid vertically
}
letterPlace += 1;
}
}
int main()
{
int increment = 0;
string userInput;
cin >> userInput;
flipGrid(userInput, increment);
return 0;
}

正如您可能知道的那样,我需要评论中指定的部分的帮助。如果代码按计划运行,它应该看起来像这样......

输入(示例 1(

H

输出

3 4
1 2

输入(示例 2(

HVVH

输出(两个 H 和两个 V 抵消,只剩下原始版本(

1 2
3 4

我觉得应该有一种更简单的方法来解决这个问题,或者我目前正在研究的方法是否是解决这个问题的正确方法?请让我知道我是否走在正确的轨道上。谢谢!

我会做几件事。首先,我会简单地计算 H 和 V,完成后,每个计数的模 2。这将使您翻转计数H和翻转计数V各有0或1。没有必要做多次翻转,对吧?然后,您最多执行一次每个操作。

void flipCounts(string str, int &flipCountH, int &flipCountY)
{
for (char c: str) {
if (c == 'H')
{
++flipCountH;
}
else if (c == 'V')
{
++clipCountY
}
}
}

然后使用该方法:

flipCountH %= 2;
flipCountY %= 2;
if (flipCountH > 0) {
performHorizontalFlip();
}
if (flipCountV > 0) {
performVerticalFlip();
}

现在,翻转方式取决于您存储数据的方式。对于这个非常具体的问题,我会将其存储在 int[2][2] 中。

void performVerticalFlip() {
int[2] topLine;
topLine[0] = grid[0][0];
topLine[1] = grid[0][1];
grid[0][0] = grid[1][0];
grid[0][1] = grid[1][1];
grid[1][0] = topLine[0];
grid[1][1] = topLine[1];
}

现在,您可能可以利用C++移动语义,但这是一个高级主题。您还可以创建一个交换两个整数的交换方法。那不是那么先进。

void swap(int &a, int &b) {
int tmp = a;
a = b;
b = tmp;
}

那么上面的代码就更简单了: 交换(网格[0][0], 网格[1][0](; 交换(网格[0][1], 网格[1][1](;

水平翻转类似。

从评论:

我不知道如何在每个语句中翻转它

因此,垂直翻转 2x2 网格很简单:

int tmp = grid[0][0];
grid[0][0] = grid[1][0];
grid[1][0] = tmp;
tmp = grid[0][1];
grid[0][1] = grid[1][1];
grid[1][1] = tmp;

如果您的网格大于 2x2,这也将起作用:

// for half the height of the grid
for(unsigned int i = 0;i<Height/2;i++) {
// for the width of the grid
for(unsigned int j =0; j<Width) {
// store a copy of the old value
int tmp = grid[i][j];
// put the new value in
grid[i][j] = grid[Height-1-i][j]; // note, we are flipping this vertically,
// so we want something an equal distance away
// from the other end as us
// replace the value we were grabbing from with the saved value
grid[Height-1-i][j] = tmp;
}
}

如果这是家庭作业,我将留下一个水平翻转供您弄清楚(提示,这是同一件事,但宽度和高度颠倒了(。