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.
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,
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.