Write an application code that will suggest movies from a list randomly and there won\'t be any repeat while suggesting the movies
belongs to collection: Interview C++ coding problems/challenges | arrays
All Answers
total answers (1)
belongs to collection: Interview C++ coding problems/challenges | arrays
total answers (1)
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,
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.
C++ Implementation:
Output: