Randomized algorithms
- Algorithms course
- Expert
- Lesson 10/41
- 4 min
Algorithms using random choices.
Randomized algorithms
A randomized algorithm uses random choices to reach a solution. In some cases it is faster than deterministic algorithms.
Randomized algorithms come in two flavors: Las Vegas that always gives correct results, and Monte Carlo that gives correct results with high probability.
Sampling for maximum
We can find the maximum of an array by checking randomly selected indices. This shows the basis of randomized algorithms.
If all indices are selected, the result is exact. If a subset is selected, the result is probabilistic. This is Monte Carlo style.
Practice sample_max function
Write sample_max(arr, indices). Return the maximum among arr values at indices. Print 9 with print(sample_max([3, 5, 7, 1, 9], [0, 2, 4])).
Starter code
def sample_max(arr, indices):
# Find max among sampled indicesSample solution
def sample_max(arr, indices):
# Find max among sampled indices
best = arr[indices[0]]
for i in indices:
if arr[i] > best:
best = arr[i]
return best
print(sample_max([3, 5, 7, 1, 9], [0, 2, 4]))Expected output
9
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Sampling
for i in ____:
for i in indices:
Explanation: indices is right.
2 What does a Monte Carlo algorithm provide?
- No result
- Constant time
- Correct result with high probability Correct answer
- Always correct result
Explanation: Monte Carlo gives a correct result with high probability.
3 Randomized algorithms: match the terms
| Term | Meaning |
|---|---|
random |
Random |
Monte Carlo |
Probabilistic |
Las Vegas |
Exact |
sample |
Subset |