有没有更好的方法来简化这个switch表达式?

huangapple go评论72阅读模式
英文:

Is there a better way to simplify this switch expression?

问题

我一直在自学C++,想知道是否有人知道更高效的方法来玩这个石头、剪刀、布游戏。

cout << "选择1、2或3代表石头、剪刀或布\n> ";

// ...

int match = guess - botGuess;

switch (match) {

case 0:
    cout << 平局;
    break;
case -1:
case 2:
    cout << ;
    break;
case -2:
case 1:
    cout << ;
}

我将游戏的9种可能排列简化为这5种不同的情况,但我想知道是否有更快的玩法。

英文:

I have teaching myself c++, and was curious if anyone knows of a more efficient approach to this rock, paper, scissors game.

cout &lt;&lt; &quot;Pick 1, 2, or 3 for Rock, Paper, or Scissors\n&gt; &quot;;

// ...

int match = guess - botGuess;

switch (match) {

case 0:
	cout &lt;&lt; tie;
	break;
case -1:
case 2:
	cout &lt;&lt; lose;
	break;
case -2:
case 1:
	cout &lt;&lt; win;
}

I simplified the 9 possible arrangements of the game into these 5 different cases, but I want to know if there's an even quicker way to play the game.

答案1

得分: 2

对于这样的小问题,我会使用查找表而不是逻辑。它的时间复杂度是O(1)

#include <iostream>
#include <array>

constexpr std::array<const char*,3> names = {"Rock","Paper","Scissors"};
constexpr std::array<const char*,3> outcomes = {"Draw","win","Lose"};
constexpr std::array<std::array<int,3>,3> results = {{0,2,1},{1,0,2},{2,1,0}};

int main() {
    for ( int j=0; j<3; ++j ) {
        for ( int k=0; k<3; ++k ) {
            int result = results[j][k];
            std::cout << names[j] << " x " << names[k] << ": " << outcomes[result] << std::endl;
        }
    }
}

打印输出:

Rock x Rock: Draw
Rock x Paper: Lose
Rock x Scissors: win
Paper x Rock: win
Paper x Paper: Draw
Paper x Scissors: Lose
Scissors x Rock: Lose
Scissors x Paper: win
Scissors x Scissors: Draw

Godbolt链接:https://godbolt.org/z/Gxa5vKsGv

英文:

For such small problem I'd use a lookup table instead of logic. It's O(1)

#include &lt;iostream&gt;
#include &lt;array&gt;

constexpr std::array&lt;const char*,3&gt; names = {&quot;Rock&quot;,&quot;Paper&quot;,&quot;Scissors&quot;};
constexpr std::array&lt;const char*,3&gt; outcomes = {&quot;Draw&quot;,&quot;win&quot;,&quot;Lose&quot;}; 
constexpr std::array&lt;std::array&lt;int,3&gt;,3&gt; results = {{{0,2,1},{1,0,2},{2,1,0}}};

int main() {
    for ( int j=0; j&lt;3; ++j ) {
        for ( int k=0; k&lt;3; ++k ) {
            int result = results[j][k];
            std::cout &lt;&lt; names[j] &lt;&lt; &quot; x &quot; &lt;&lt; names[k] &lt;&lt; &quot;: &quot; &lt;&lt; outcomes[result] &lt;&lt; std::endl;
        }
    }
}

Prints

Rock x Rock: Draw
Rock x Paper: Lose
Rock x Scissors: win
Paper x Rock: win
Paper x Paper: Draw
Paper x Scissors: Lose
Scissors x Rock: Lose
Scissors x Paper: win
Scissors x Scissors: Draw

Godbolt: https://godbolt.org/z/Gxa5vKsGv

huangapple
  • 本文由 发表于 2023年8月5日 10:03:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839876.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定