【问题标题】:How to pick a random integer out of three integers I chose如何从我选择的三个整数中选择一个随机整数
【发布时间】:2019-08-08 04:08:05
【问题描述】:

我正在制作一个琐事游戏,并且在函数中有问题以得到一个随机问题那个功能。然后我想这样做,所以当我再次这样做时,我可以确保我不会再得到这个整数,以免运行同样的问题。

这就是我现在拥有的

  srand(time(NULL));
  int randomnumber;
  randomnumber = rand() % 3;

但它只是得到一个介于 0 和 2 之间的随机整数,然后不让我选择三个直接整数,然后在运行时将它们从这个数组中取出。

【问题讨论】:

    标签: c random integer


    【解决方案1】:

    有很多方法可供选择。其中之一是创建一个整数数组,在您的情况下,它的大小为 3,其中包含数字 0...2。现在洗牌这个数组。有许多算法可以做到这一点。一个例子是this
    现在,只需遍历这个新创建的 shuffle 数组来调用函数。在这种情况下,您的两个要求都将得到满足。 问题将按随机顺序排列,您不会再拨打同一个号码

    此代码示例将帮助您入门:

    void shuffle ( int arr[], int n ) {
        srand ( time(NULL) );
        //this will shuffle the array
        for (int i = n-1; i > 0; i--){
            // Pick a random index from 0 to i-1
            int j = rand() % (i);
            // Swap arr[i] with the element at random index
            swap(&arr[i], &arr[j]);
        }
    }
    int main(){
        int arr[] = {0, 1, 2};
        shuffle(arr, 3);
        int i;
        for(i = 0; i < 3; i++){
            // call the function with shuffled array
        }
    }
    

    你需要编写swap函数

    【讨论】:

    • 我在问题中错过了“当我再次执行此操作时,我可以确保我不再得到这个整数......”,所以我删除了我的答案,我支持你的:-)
    • 我明白这是想让我做什么,但不明白我应该如何将它放入可以工作的代码中。
    • @bobbyjoe。我已经添加了一些代码来帮助你开始。
    【解决方案2】:

    对于少量项目,将所选项目替换为无效值。
    可以使用开关来处理随机项目。

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <time.h>
    
    int main( void) {
        char items[] = "012";
        int each = 0;
    
        srand ( time ( NULL));
    
        while ( 1) {
            if ( ! strcmp ( "   ", items)) {
                printf ( "all items used\n");
                break;
            }
    
            do {//find an item that is not ' '
                each = rand ( ) % 3;
            } while ( items[each] == ' ');
    
            switch ( items[each]) {
                case '0':
                    printf ( "using item 0\n");
                    //do other things here as needed
                    break;
                case '1':
                    printf ( "using item 1\n");
                    //do other things here as needed
                    break;
                case '2':
                    printf ( "using item 2\n");
                    //do other things here as needed
                    break;
            }
    
            items[each] = ' ';//set used item to ' '
        }
        return 0;
    }
    

    【讨论】:

    • 谢谢你,这对我很有帮助。
    猜你喜欢
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 2013-02-08
    • 1970-01-01
    • 2022-11-30
    • 2020-02-07
    相关资源
    最近更新 更多