From d2aa9289c5c3a2fa2b6442bea771f6578624e3eb Mon Sep 17 00:00:00 2001
From: "Brady J. Garvin" <bgarvin@cse.unl.edu>
Date: Fri, 20 Oct 2023 14:35:10 -0500
Subject: [PATCH] Took notes from Wednesday.

---
 greedy-algorithms/notes.md                    |  4 +++-
 .../src/features/encoding/solver.js           | 19 ++++++++++++++++++-
 2 files changed, 21 insertions(+), 2 deletions(-)

diff --git a/greedy-algorithms/notes.md b/greedy-algorithms/notes.md
index 2e3a406..17d5fa4 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 7c7344b..ffa56ad 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;
 }
-- 
GitLab