# 給定數字N,生成1,2,3...,N共N個不重複的隨機數

Note小技巧: val = max*coeff, coeff=[0,1), max爲正整數，coeff爲float，， (int)val屬於[0,max-1]，向下取整了。

Show me:

``````#include <iostream>
#include <vector>
#include <cstdlib>

/*
Function:       generateRandomNums
Description:    Give parameter N(N>0), then generate N unduplicated random numbers within the range from 1 to N.
*/
void generateRandomNums(unsigned int max)
{
if (max < 1)
return;
unsigned int MaxNum = max;
std::vector<unsigned int> BaseArray(max);
std::vector<unsigned int> mResult(max);
unsigned int si = BaseArray.size();
for (unsigned int i = 0; i < max; ++i)
{
BaseArray[i] = i + 1;
}

for (int i = 0; i < MaxNum; ++i)
{
/**generate a random number within the range of max*[0,1)*/
int index = (rand() % 100) / 100.0f *max;
/**get a member from BaseArray*/
mResult[i] = BaseArray[index];

BaseArray[index] = BaseArray[max - 1];
/**decrease max to ensure that mResult's elements is ununduplicated. */
max--;
}
for (auto val : mResult)
{
std::cout << val << std::endl;
}

}``````