简体   繁体   English

C ++为多米诺骨牌生成随机数

[英]C++ Generate random numbers for dominoes

My assignment involves writing several classes that will work together to randomly sort 28 dominoes for the user and display them. 我的作业涉及编写几个类,这些类将一起为用户随机排序28个多米诺骨牌并显示它们。 The main trouble I'm having so far is just creating the dominoes without any duplication. 到目前为止,我遇到的主要麻烦是创建多米诺骨牌而没有任何重复。 If you're familiar with dominoes, you know that each half of them are either blank or have 1-6 dots. 如果您熟悉多米诺骨牌,您会知道它们中的每一个都是空白或有1-6个点。 Basically I'll have a dynamic array of 28 unique structs (dominoes) but I'm just stuck on generating these dominoes without having identical ones. 基本上,我将动态地排列28个唯一的结构体(多米诺骨牌),但我只是在没有相同的情况下生成这些多米诺骨牌。 I was thinking of using FOR loops to just go through and assign values within each struct but I figured there had to be some easier way. 我当时在考虑使用FOR循环在每个结构中进行遍历并分配值,但我认为必须有一些更简单的方法。

This is what I have so far below; 这是我到目前为止要说的。 I know it's not much but I can't and don't want to go on with writing methods for sorting and display without getting this right first. 我知道不多,但是我不能也不想继续编写方法来进行排序和显示,而不必首先解决这一问题。

class CDominoes{
    public:
    struct Data
    {
        int top;
        int bottom;

        Data()
        {
            top = 0;
            bottom = 0;
        }
    } domino[28];

    //methods to assign spots to halves
};

The simplest solution is to generate, and then shuffle. 最简单的解决方案是生成,然后随机播放。 To generate, you need to avoid wasting time generating duplicates. 要生成,您需要避免浪费时间生成重复项。 For example, (4,5) is the same as (5,4), so you don't want to generate both. 例如,(4,5)与(5,4)相同,因此您不想同时生成两者。 That means that your inner loop should always begin at the current value of the outer loop. 这意味着您的内部循环应始终从外部循环的当前值开始。 In so doing, you'll never repeat a combination. 这样,您将永远不会重复组合。 Here's an example: 这是一个例子:

int main () {
    for( int t = 0; t <= 6; ++t ) {
        for( int b = t; b <= 6; ++b ) {
            std::cout << "(" << t << "," << b << ")\n";
        }
    }
    return 0;
}

In this example, we're considering '0' to be the same as a blank domino. 在此示例中,我们认为“ 0”与空白多米诺相同。

Next, instead of printing these, put them into a random access container such as std::array or std::vector , and then use std::shuffle to shuffle your container. 接下来,不要打印这些,而是​​将它们放入随机访问容器(例如std::arraystd::vector ,然后使用std::shuffle来随机播放您的容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM