diff --git a/greedy-algorithms/notes.md b/greedy-algorithms/notes.md index 34ac568bd127ac3a3e7bb1e39af72fffa2cd02f9..901e99656efa04003da5a9d79b8080c13874ccf1 100644 --- a/greedy-algorithms/notes.md +++ b/greedy-algorithms/notes.md @@ -126,8 +126,8 @@ Problem: [same as above] ## Choosing a Forward Edge * Exhaustive search: - * Generate … - * Check that … + * Generate all edges that travel up to distance `range` along the route + * Check that the chosen edge travels farthest (always favors the current candidate) ## Example @@ -143,12 +143,15 @@ Problem: [same as above] Location Next Location -------- ------------- - a … - … + a c + c d + d e + e h + h i Path ---- - a → … + a → c → d → e → h → i -------------------------------------------------------------------------------- @@ -214,22 +217,22 @@ Problem: Given frequencies for a set of symbols, create a lossless binary encodi ## DAG * Edges (actions): - * … + * Combining two sets of symbols * Vertices (situations): - * … + * Symbol partitionnings * Edge weights: - * … + * Total frequency of the combined sets * Topological order: - * … + * By decreasing number of sets (parts in the paritioning) * Goal: - * … + * Find the shortest path ## Choosing a Forward Edge * Direct solution: - * … - * … - * … + * Choose the lowest-frequency set + * Choose the second-lowest-frequency set + * Choose the edge that combines those sets ## Example diff --git a/greedy-algorithms/src/features/fueling/solver.js b/greedy-algorithms/src/features/fueling/solver.js index 18326349a6727b0110a14ffee9f92a0950e54315..0f04b420a88853613bd752100fcc9021ced89eca 100644 --- a/greedy-algorithms/src/features/fueling/solver.js +++ b/greedy-algorithms/src/features/fueling/solver.js @@ -7,7 +7,16 @@ export function planFuelings(gaps, range) { gaps.every((gap) => gap <= range), `Tried to find a fueling plan crossing a gap longer than the range ${range}.`, ); - const results = []; - // TODO: stub + const destination = gaps.length; + const results = [0]; + while (results[results.length - 1] !== destination) { + let best = undefined; + for (let distance = 0, candidate = results[results.length - 1]; + distance <= range && candidate <= destination; + distance += gaps[candidate], ++candidate) { + best = candidate; + } + results.push(best); + } return results; }