diff --git a/greedy-algorithms/notes.md b/greedy-algorithms/notes.md index 2e3a406db46d35fb2951df2a96c6296c04c7e8cb..17d5fa4d2f0327bfe5d152958ed9f5ddc6d1c9a2 100644 --- a/greedy-algorithms/notes.md +++ b/greedy-algorithms/notes.md @@ -240,4 +240,6 @@ Problem: Given frequencies for a set of symbols, create a lossless binary encodi Symbol Partitioning (Frequency Order) 'a' 'b' 'c' 'd' ------------------------------------------------------- --- --- --- --- {'a'} → 0.15, {'c'} → 0.25, {'b'} → 0.30, {'d'} → 0.30 - … + {'a', 'c'} → 0.40, {'b'} → 0.30, {'d'} → 0.30 0 1 + {'a', 'c'} → 0.40, {'b', 'd'} → 0.60 0 0 1 1 + {'a', 'c', 'b', 'd'} → 1.00 00 10 01 11 diff --git a/greedy-algorithms/src/features/encoding/solver.js b/greedy-algorithms/src/features/encoding/solver.js index 7c7344bb7c83a81a24a9cc163affa00b9802e719..ffa56ad01436adc383f09b1d0061d3c1f83e5bbe 100644 --- a/greedy-algorithms/src/features/encoding/solver.js +++ b/greedy-algorithms/src/features/encoding/solver.js @@ -1,8 +1,25 @@ +import { PriorityQueue } from './collections.js'; + export function findEncoding(frequencies) { const results = new Map(); + const partitioning = new PriorityQueue(); for (const [meaning, frequency] of frequencies) { results.set(meaning, ''); + partitioning.insert(new Set([meaning]), frequency); + } + while (partitioning.size > 1) { + const [firstMeaningSet, firstFrequency] = partitioning.remove(); + const [secondMeaningSet, secondFrequency] = partitioning.remove(); + for (const meaning of firstMeaningSet) { + results.set(meaning, `0${results.get(meaning)}`); + } + for (const meaning of secondMeaningSet) { + results.set(meaning, `1${results.get(meaning)}`); + } + partitioning.insert( + new Set([...firstMeaningSet, ...secondMeaningSet]), + firstFrequency + secondFrequency, + ); } - // TODO: stub return results; }