【发布时间】: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