对包含n个元素的数组a进行洗牌
To shuffle an array a of n elements C++
我有洗牌数组的问题问题是,根据种子的随机再次是相同的结果,而不是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
)。"随机"听起来像是一个函数的名字,它应该返回数据的随机副本,而不是修改原始数据。
决定你想要哪个版本,并在此基础上,修复函数或测试程序。
相关文章:
- 将包含C样式数组的对象初始化为成员变量(C++)
- C++ 打印包含数据结构的数组
- 通过分隔符分隔包含 UTF-16 BE 文本的uint8_t数组
- 包含作为成员C++函数的结构数组
- 循环访问还包含未使用元素的字符串数组
- C++两个对象,其中包含指向同一数组不同部分的指针
- 查找包含 N 个元素的数组的最小值和最大值
- 无法将字符数组转换为包含 utf-8 字符的字符串
- 常量数组如何在每个元素中只能包含字符,而 char* 数组能够指向每个元素中的字符串?
- 我怎么知道数组包含多少个元素C++?
- 返回一个数组,该数组包含数组中的数量,该数组数量较小或等于给定数组中的元素
- 字符串的变体数组包含替代空间
- C++ -- 指向结构数组的指针,该数组包含指向不起作用的类数组的指针
- 返回连续数字的逻辑假设数组包含元素 1,9,2,3,4,9,6,7,8,那么它应该返回 2,3,4,6,7,8
- 声明一个类型为String的数组,该数组包含带填充的数字
- 如何使数组包含从基类继承的类
- 当用c++编写数组时,我尝试将数组包含到另一个类中,但不起作用
- 为什么这个字符数组包含未填充的内存
- 函数数组包含来自不同对象的函数
- 成员数组包含类的实例。无法决定在哪里放置修改此类变量的方法