2个数字之间的随机数选择器

时间:2014-05-18 18:38:01

标签: c++ algorithm tic-tac-toe

我正在使用C ++进行Tic-Tac-Toe游戏,我想知道是否可以随机化一个数字,但它只能选择2或5.

我在用户和计算机之间进行随机启动,以便公平地开始使用这些代码块:

 srand(time(NULL));
 cout << "The First Person to go is randomly chosen!" << endl;
 FirsttoGo = (rand()%2) + 1;
 cout << "The first move goes to Player: " << FirsttoGo << endl;
 turn = FirsttoGo;

我想添加的功能是,无论谁启动游戏都可以选择X或O但是如果计算机首先启动,计算机应该能够在X或O之间进行选择。我还创建了常量值X和O

static const int O = 5;
static const int X = 2;

有没有这样做?

4 个答案:

答案 0 :(得分:4)

(rand() > RAND_MAX/2) ? 2 : 5;

答案 1 :(得分:3)

在C ++ 11中,在一个范围内生成随机数有非常好的和更安全的补充(参见下面的代码):

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 2);
    for (int n=0; n<10; ++n) std::cout << dis(gen) << ' ';
    std::cout << '\n';
}

此外,在此nice talk Stephan T. Lavavej中说明了使用rand()被视为有害的原因。

根据上面的示例,您可以针对您的问题进行调整,如下所示:

int getRandomIDX(int const a = 5, int const b = 2) {
  std::random_device rd;
  std::mt19937 gen(rd());
  std::uniform_int_distribution<> dis(1, 2);
  return (dis(gen) == 1)? a : b;
}

答案 2 :(得分:0)

由于您只需要在两个值之间进行选择,因此您可以使用时间函数

time_t timer; 
time(&timer); // it returns an integral value

如果时间timer甚至选择第一个,如果没有选择第二个.. 那是真正的随机,而不是伪随机

...有人讨厌简单的美丽我猜。转到random devicesdistributions来选择2个值,然后

答案 3 :(得分:0)

这是最快和最简单的方式来随机选择一个号码。在2个数字之间-

Statement stmt = null;
ResultSet rs = null;
Connection conn = getConnection();
try {
  stmt = conn.createStatement();
  rs = stmt.executeQuery(sqlQuery);
  processResults(rs);
} catch (SQLException e) {
  // Forward to handler
} finally {
  try {
    if (rs != null) {rs.close();}
  } catch (SQLException e) {
    // Forward to handler
  } finally {
    try {
      if (stmt != null) {stmt.close();}
    } catch (SQLException e) {
      // Forward to handler
    } finally {
      try {
        if (conn != null) {conn.close();}
      } catch (SQLException e) {
        // Forward to handler
      }
    }
  }
}

就是这样。干杯!

相关问题