【发布时间】:2018-04-19 12:23:38
【问题描述】:
我看了又看,仍然迷失在如何从数组中复制或获取元素并将它们放入新数组中(目标是分而治之)。
我有一个生成 100 个随机数的数组。我需要将随机数拆分为 4 个较小的数组,显然包含 25 个元素并且没有任何重复项。我读过关于使用指针的文章,但老实说,我不明白为什么还要使用指针。为什么我关心另一个变量地址?
我不知道该怎么做。到目前为止,这是我的代码:
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
// Seed the random number generator
srand(time(NULL));
//create an array to store our random numbers in
int Orignumbers[100] = {};
// Arrays for the divide and conquer method
int NumbersA [25] = {};
int NumbersB [25] = {};
int NumbersC [25] = {};
int NumbersD [25] = {};
//Generate the random numbers
for(int i =0; i < 100; i++)
{
int SomeRandomNumber = rand() % 100 + 1;
// Throw random number into the array
Orignumbers[i] = SomeRandomNumber;
}
// for(int i = 0; i < ) started the for loop for the other arrays, this is where I am stuck!!
// Print out the random numbers
for(int i = 0; i < 100; i++)
{
cout << Orignumbers[i] << " , ";
}
}
【问题讨论】:
-
如果
Orignumbers数组中的前 100 个数字不是不同的怎么办?那么根据鸽巢原理,您不能拥有任何大小为 25 且具有 25 个不同值的数组。您显然会在 4 个数组中至少有一个重复。 -
使用
std::vector(或std::array用于固定大小),而不是原始数组。最好使用<random>设施而不是旧的srand等。如果您想要连续序列中没有重复的随机数,请考虑改组。
标签: c++ arrays divide-and-conquer