-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetfrom.cpp
32 lines (28 loc) · 839 Bytes
/
getfrom.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/******************************************************************************
* File: getfrom.cpp
*
* Author: yychi
* Created: 2019-10-17 09:59
* Description: Get m different elems from a sequence of length n, randomly.
*****************************************************************************/
#include <iostream>
#include <vector>
using namespace std;
vector<int> getfrom(vector<int>& v, int m)
{
for (int i = v.size()-1, cnt = m; i > 0 && cnt > 0; --i, --cnt)
{
int randidx = rand() % (i+1);
std::swap(v[randidx], v[i]);
}
if (m < (int)v.size()) return {v.rbegin(), v.rbegin() + m};
else return v;
}
int main()
{
srand(time(NULL));
vector<int> v = {1,2,68,4,56,45,34,7,9,3,42,37,3453,49};
int m = 5;
for (auto e : getfrom(v, m)) cout << e << " ";
return 0;
}