Write an application code that will suggest movies from a list randomly and there will not be any repeat while suggesting the movies. That means the same movie will not be suggested twice though it will be done randomly. Input will be a movie list.
Example:
Input:
["D-DAY", "RAINCOAT", "OCTOBER","LUNCHBOX", "BARFI", "RAAZI","PIKU"]
Movie suggestion list can be
"BARFI"
"PIKU"
"RAAZI"
"OCTOBER"
"D_DAY"
"LUNCHBOX"
"RAINCOAT"
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.
So the map will be:
So our movie list will be converted as: [1,2,3,4,5,6,7]
Then we will shuffle using the Fisher-Yates algorithm
At each step iteration, we will suggest movie[i]. Below is the detailed algorithm for suggesting movie randomly
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 i End for loopSo, 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.
C++ Implementation:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer