Approximation Algorithm — Set Cover
Tutorial Video
Text description (accessibility)
This video demonstrates the "Approximation Algorithm — Set Cover" functional Rust example. Difficulty level: Advanced. Key concepts covered: Functional Programming. Set cover is NP-hard: given a universe U of elements and a collection S of subsets, find the minimum number of subsets whose union equals U. Key difference from OCaml: | Aspect | Rust | OCaml |
Tutorial
The Problem
Set cover is NP-hard: given a universe U of elements and a collection S of subsets, find the minimum number of subsets whose union equals U. The greedy approximation picks the subset covering the most uncovered elements at each step, achieving an O(log n) approximation — proven optimal assuming P ≠ NP. This approximation is used in: network monitoring (minimum sensor placement to cover all traffic), advertising (minimum campaigns to reach all demographics), feature selection in machine learning, and compiler register allocation. Understanding approximation algorithms — which sacrifice optimality for polynomial time — is essential for NP-hard optimization.
🎯 Learning Outcomes
Code Example
#![allow(clippy::all)]
//! PlaceholderKey Differences
| Aspect | Rust | OCaml |
|---|---|---|
| Universe set | HashSet<u32> | Set.Make(Int).t or Hashtbl |
| Intersection count | .intersection().count() | Set.inter \|> Set.cardinal |
| Best set selection | max_by_key | List.fold_left with max |
| Uncovered removal | retain(|e| !contains) | Set.diff uncovered chosen |
| Approximation ratio | O(ln n) provable | Same |
| Brute force comparison | Exponential search | Same |
OCaml Approach
OCaml implements greedy set cover with a Hashtbl for the uncovered set or a Set.Make(Int) balanced BST. List.fold_left finds the maximum-coverage set. Set.inter uncovered s |> Set.cardinal counts intersections. OCaml's Set.diff uncovered chosen_set removes covered elements immutably. The while loop or tail recursion drives iteration. List.rev restores selection order if building the list by prepending.
Full Source
#![allow(clippy::all)]
//! PlaceholderDeep Comparison
OCaml vs Rust: Approximation Set Cover
Overview
See the example.rs and example.ml files for detailed implementations.
Key Differences
| Aspect | OCaml | Rust |
|---|---|---|
| Type system | Hindley-Milner | Ownership + traits |
| Memory | GC | Zero-cost abstractions |
| Mutability | Explicit ref | mut keyword |
| Error handling | Option/Result | Result<T, E> |
See README.md for detailed comparison.