C++选择一些随机项目而不重复

标签 c++

Write a program that randomly selects from a bag of eight objects.
Each object can be red, blue, orange, or green, and it can be a ball or a cube.
Assume that the bag contains one object for each combination (one red ball, one
red cube, one orange ball, one orange cube, and so on). Write code similar to
Example 5.3, using two string arrays—one to identify colors and the other to
identify shapes.

我正在尝试编写一个程序来执行上述练习 - 我遇到的问题是每次都可以多次选择同一个对象。

这是目前的代码

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;

int rand_0toN1(int n);
void choose_object();

char *colour[4] =
    {"Red", "Blue", "Orange", "Green"};
char *object[2] =
    {"Ball", "Cube"};

int main()
{
    int n, i;
    srand(time(NULL)); // Set seed for randomizing.
    while (1) {
        cout << "Enter no. of objects to draw ";
        cout << "(0 to exit): ";
        cin >> n;
        if (n == 0)
            break;
        for (i = 1; i <= n; i++)
            choose_object();
    }
    return 0;
}
void choose_object() {
    int c; // Random index (0 thru 4) into
    // colours array
    int o; // Random index (0 thru 2) into
    // object array
    c = rand_0toN1(4);
    o = rand_0toN1(2);
    cout << colour[c] << "," << object[o] << endl;
}

int rand_0toN1(int n) {
    return rand() % n;
}

最佳答案

让我们尝试通过做一个现实世界的类比来解决这个问题:

假设您有一大 jar 以上所列颜色的弹珠。它是如此之大(无限大!),以至于您总是有相同的机会绘制给定颜色的大理石,每次总是 1/4。

在现实生活中你会怎么做?你会一直随机挑选,在你画的时候把弹珠扔掉吗?或者您是否可以保留一份您已经画过的东西的小 list ?

或者也许您在 jar 里只有一个……您不会把它放回去吧?因为这就是您在这里所做的事情。

这些思维路径中的每一个都会引导您找到一个好的解决方案。我不想提供代码或任何东西,因为这种作业是教你如何像计算机一样思考的作业。

关于C++选择一些随机项目而不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8527855/

相关文章:

c++ - 打包一个 C++ 项目以发布一些依赖项,如 pthread boost curl 等

c++ - 在 Windows 上使用 Qt Creator 设置缓存

c++ - boost::intrusive 中的线程安全保证

android - 不支持的 OpenGL 函数和常量

c++ - 如何将 vector 传递给基于推力的 odeint 观察器的构造函数,以便可以在仿函数中读取它

c++ - 将字符从 char 数组复制到 char 数组

c++ - 如何切换网格布局中的小部件可见性?

c++ - 代码中的智能指针实现错误

c++ - 如何重写控制台项目中的一行文本?由 小码哥发布于

c++ - 如何确定 C++ 对象是否为 time_t