英文:
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 << "Pick 1, 2, or 3 for Rock, Paper, or Scissors\n> ";
// ...
int match = guess - botGuess;
switch (match) {
case 0:
cout << tie;
break;
case -1:
case 2:
cout << lose;
break;
case -2:
case 1:
cout << 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 <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;
}
}
}
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论