参考:http://www.cnblogs.com/afarmer/archive/2011/05/01/2033715.html
题意:给数组洗牌,随机打乱顺序
思路:
(1)遍历数组,每次随机生成一个坐标位置,由srand和rand实现
(2)交换当前遍历位置和随机生成的坐标位置的数字,直到遍历到最后一个元素
version 2017.4.4
注意:
(1)#include<time.h>是C/C++中的日期和时间头文件,用于需要时间的函数
(2)#include<stdlib.h>定义了srand(),srand():程序每次运行的时间不一样,所以是随机的
原来的版本,rand每次产生的数是一样的……并不算随机
C++实现:
vector<int> shuffle(vector<int> &v)
{
vector<int> res=v;
for(int i=0;i<res.size();i++)
{
int t=rand()%res.size();
swap(res[i],res[t]);
}
return res;
}
swap(&s,&t)
{
temp=s;
s=t;
t=temp;
}