本文共 3186 字,大约阅读时间需要 10 分钟。
c ++明明的随机数
Problem statement:
问题陈述:
Write an application code that will suggest movies from a list randomly and there won't be any repeat while suggesting the movies. That means the same movie won't be suggested twice though it will be done randomly. Input will be a movie list.
编写应用程序代码,以随机建议列表中的电影,并且在建议电影时不会重复。 这意味着尽管会随机播放同一部电影,但不会两次被推荐。 输入将是电影列表。
Prerequisite:
先决条件:
Example:
例:
Input:["D-DAY", "RAINCOAT", "OCTOBER","LUNCHBOX", "BARFI", "RAAZI","PIKU"]Movie suggestion list can be"BARFI""PIKU""RAAZI""OCTOBER""D_DAY""LUNCHBOX""RAINCOAT"
Solution
解
We can use Fisher-Yates random shuffling algorithm to solve this problem. Firstly, we need to create a map to store indexes of the movies as we will shuffle based on their indexes.
我们可以使用Fisher-Yates随机改组算法来解决此问题。 首先,我们需要创建一个地图来存储电影的索引,因为我们将根据电影的索引进行随机播放。
So the map will be:
因此,地图将为:
KEY VALUE1 "D-DAY"2 "RAINCOAT"3 "OCTOBER"4 "LUNCHBOX"5 "BARFI"6 "RAAZI"7 "PIKU"
So our movie list will be converted as: [1,2,3,4,5,6,7]
因此,我们的电影列表将被转换为:[1,2,3,4,5,6,7]
Then we will shuffle using the Fisher-Yates algorithm
然后,我们将使用Fisher-Yates算法进行洗牌
At each step iteration, we will suggest movie[i]. Below is the detailed algorithm for suggesting movie randomly
在每一步迭代中,我们都会建议movie [i] 。 以下是随机建议电影的详细算法
The detailed algorithm will be,
详细的算法将是
For i=n-1 to 1 Pick and element in the range [0,i-1] randomly Swap the randomly picked element with a[i] // since it's not going to be reshuffled again // as we are decrementing i , // thus it's guaranteed that it won't be suggested twice Recommend movie[a[i]]Decrement iEnd for loop
So, how this guarantees unique suggestion each time?
那么,如何保证每次的独特建议呢?
Because, we are fixing the ith element after the swap and decrementing i, so that the movie that got suggested never takes part again in swaps.
因为,我们在交换之后固定了第 i 个元素,并减小了i ,以便所建议的电影再也不会参与交换。
C++ Implementation:
C ++实现:
#includeusing namespace std;void recommend_movie_randomly(vector movies){ srand(time(0)); map mymap; int n = movies.size(); for (int i = 0; i < n; i++) { mymap[i] = movies[i]; } vector arr(n); //stores the indexes for (int i = 0; i < n; i++) arr[i] = i; //shiffling randomly and suggesting movie //at each iteartion for (int i = n - 1; i >= 1; i--) { //j will be a random no with in range 0 to i-1 int j = rand() % i; //swap ith index with jth int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; //suggest the ith movie now cout << "Suggesting next movie...\n"; cout << mymap[arr[i]] << endl; }}int main(){ //input list vector movie_list{ "D-DAY", "RAINCOAT", "OCTOBER", "LUNCHBOX", "BARFI", "RAAZI", "PIKU" }; cout << "Recommending movies randomly from the list\n"; recommend_movie_randomly(movie_list); return 0;}
Output:
输出:
Recommending movies randomly from the listSuggesting next movie...RAAZISuggesting next movie...OCTOBERSuggesting next movie...PIKUSuggesting next movie...D-DAYSuggesting next movie...RAINCOATSuggesting next movie...LUNCHBOX
Also tagged in:
还标记在:
翻译自:
c ++明明的随机数
转载地址:http://iyxzd.baihongyu.com/