随机排列 n 个元素的数组 a C++
To shuffle an array a of n elements C++
我对随机数组有疑问
问题是,根据随机种子,结果又是相同的,而不是 2-exchange,两个数组是相同的!
我想要 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
在这两种情况下都 return 将指针指向传入的同一数组 (x1
= x2
)。 "randomized" 听起来像是一个函数的名称,它应该 return 随机 复制 数据,而不是 修改 原始数据数据.
确定您想要的版本,并根据该版本修复功能或测试程序。
我对随机数组有疑问 问题是,根据随机种子,结果又是相同的,而不是 2-exchange,两个数组是相同的! 我想要 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
在这两种情况下都 return 将指针指向传入的同一数组 (x1
= x2
)。 "randomized" 听起来像是一个函数的名称,它应该 return 随机 复制 数据,而不是 修改 原始数据数据.
确定您想要的版本,并根据该版本修复功能或测试程序。