...

/

Feature #11: Generate Movie Viewing Orders

Feature #11: Generate Movie Viewing Orders

Implementing the "Generate Movie Viewing Orders" feature for our "Netflix" project.

Description

We want to offer marathons for our viewers. Each marathon will have a fixed set of movies catering to a specific taste. For a given marathon, different viewing orders of the movies will yield different user satisfaction results. We want to experiment (A/B testing) with different viewing orders of the same marathon.

Your task is to generate all the possible permutations of movies in a given marathon.

Let’s look at an example to better understand this:

Solution

To solve this problem, we will use the backtracking approach.

We will assume a backtrack function that takes the index of the first movie to consider as an argument backtrack(first).

  • If the first movie to consider has index n, then that means that the current permutation is done.

  • We will iterate over the marathon from index first to index n - 1.

  • We will place the ith movie first in the permutation, that is, movies[first], movies[i] = movies[i], movies[first].

  • We will proceed to create all the permutations that start from the ith movie: backtrack(first + 1).

  • Now we will backtrack, that is, movies[first], movies[i] = movies[i], movies[first] back.

Let’s look at some illustrations to better understand this:

Note: We are using numbers to represent movies in the following illustration.

Let’s look at the code for this solution:

Press + to interact
defmodule Solution do
def generate_permutations(movies) do
res = []
backtrack(movies, res, 0, Arrays.size(movies))
end
def backtrack(movies, res, first, size) when first == size, do: [movies | res]
def backtrack(movies, res, first, size) do
first..size-1
|> Enum.reduce({res, movies}, fn(i, {res, movies}) ->
temp = movies[i]
new_movies =
movies
|> Arrays.replace(i, movies[first])
|> Arrays.replace(first, temp)
res = backtrack(new_movies, res, first+1, size)
{res, movies}
end)
|> elem(0)
end
end
# Driver Code
IO.puts "-----------------------------"
IO.puts "PROGRAM OUTPUT:\n"
# Example #1
input = Arrays.new(["Frozen","Dune","Coco"])
IO.write("Output1: ")
IO.inspect Solution.generate_permutations(input) |> Helper.printer
# Example #2
input = Arrays.new(["Frozen","Dune","Coco","Melificient"])
IO.write("Output2: ")
IO.inspect Solution.generate_permutations(input) |> Helper.printer
# Example #3
input = Arrays.new(["Dune","Coco"])
IO.write("Output3: ")
IO.inspect Solution.generate_permutations(input) |> Helper.printer

Complexity measures

Time complexity
...