【问题标题】:To shuffle an array a of n elements C++洗牌一个包含 n 个元素的数组 C++
【发布时间】:2015-08-16 14:58:38
【问题描述】:

我对随机数组有疑问 问题是,根据随机的种子,结果是相同的,而不是 2-exchange 并且两个数组是相同的! 我想要 2 个结果数组交换随机

兑换码是2次兑换

#include <stdio.h>
#include <cstdlib>
#include <ctime>

void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

void printArray(int arr[], int n)
{
    for(int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

// A function to generate a random exchange
int* randomized(int arr[], int n)
{
    // Use a different seed value so that we don't get same
    // result each time we run this program

    srand(time(NULL));
    // Start from the last element and swap one by one. We don't
    // need to run for the first element that's why i > 0
    for(int i = n - 1; i > 0; i--)
    {
        // Pick a random index from 1 to i-1
        int j = rand() % (i - 1 + 1) + 1;
        //int j = rand() % (i+1);

        // Swap arr[i] with the element at random index
        swap(&arr[i], &arr[j]);
    }

    return arr;
}

// Driver program to test above function.
int main()
{
    int *x1, *x2;
    int arr[] = {6, 1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    x1 = randomized(arr, n);
    x2 = randomized(x1, n);
    printArray(x1, n);
    printArray(x2, n);
    getchar();
}

【问题讨论】:

    标签: c++ arrays algorithm pointers shuffle


    【解决方案1】:

    显然,randomized 在这两种情况下都返回指向传入的同一数组的指针 (x1 = x2)。 “随机化”听起来像是一个函数的名称,它应该返回数据的随机副本,而不是修改原始数据。

    确定您想要的版本,并在此基础上修复功能或测试程序。

    【讨论】:

    • 感谢回答,已更改 x1 = random(arr, n); x2 = 随机化(x1,n);但是 X1 和 X2 的结果是一样的!
    • @Mohmmad 你没有改变任何东西。 x1 = x2 = arr。如果您无法更改main,则制作数组的副本,否则,使randomized 返回void(您不需要传入的指针)和main看起来像这样:randomized(arr, n); printArray(arr, n); randomized(arr, n); printArray(arr, n);.
    猜你喜欢
    • 2019-09-19
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多