我有洗牌数组的问题问题是,根据种子的随机再次是相同的结果,而不是2-交换和两个数组是相同的!我想要2个结果数组交换随机
代码为2-exchange
#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();
}
显然,randomized
在两种情况下都返回指向传入的相同数组的指针(x1
= x2
)。"随机"听起来像是一个函数的名字,它应该返回数据的随机副本,而不是修改原始数据。
决定你想要哪个版本,并在此基础上,修复函数或测试程序。