Skip to content
Snippets Groups Projects
Commit 9edf0bea authored by Brady James Garvin's avatar Brady James Garvin
Browse files

Implemented the greedy algorithm for the encoding problem.

parent 8daf85f6
No related branches found
No related tags found
No related merge requests found
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;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment