Generate Flashcards
Using flashcards is a proven way to learn, and suggested by anybody worth their weight in salt. To implement this feature, we want an algorithm to provide this functionality. You hear a lot of people say that knowledge of algorithms and data structures isn’t necessary, and that can be true at times. Often it is valuable, and in this example, we’re showing how it’s directly related.
The feature is, to show a random problem that matches the selected tags.
Given an array of cards, and some tags, generate a randomly sorted list while showing one card at a time.
The first step is to break this down. One part of this step is to take two arrays, and generate a new array. This could be one algorithm on it’s own. Given a list of posts with tags, and a list of tags, return a list of posts that have these tags.
input: [{problem: ‘problem1’, tags: [‘tag1’, ‘tag2’]}, {problem: ‘problem2’, tags: [‘tag2’]}], [‘tag1’] output: [{problem: ‘problem1’, tags: [‘tag1’, ‘tag2’]}]
This is written in a text editor without syntax highlighting. A good way to simulate some of the aspects of whiteboarding.
function filterProblems(problems, tags) {
const filteredProblems = []
for (let tag of tags) {
for (let problem of problems) {
if (problem.tags.includes(tag)) filteredProblems.push(problem)
}
}
return filteredProblems
}
Next step is to show one problem at a time, while keeping track of the problems we’ve already seen. This is a good place to use the frequency pattern. The implementation will involve a GraphQL API because that’s what’s available to us. Written as a function this would look like this:
function showProblems(filteredProblems) {
let shown = filteredProblems
for (let problem of filteredProblems) {
const randomProblem = filteredProblems[Math.floor(Math.random()*filteredProblems.length)]
shown.splice(filteredProblems.indexOf(randomProblem), 1)
}
return shown
}
The first approach to the first part of this problem has a time complexity of O(n2) with an space complexity of O(1). This is a typical brute force way approach, thought we can make this approach O(n) with a small change.
Solution
// coming soon