From 8552b0335791795f1f4f3298943795f4912937b2 Mon Sep 17 00:00:00 2001 From: "Brady J. Garvin" <bgarvin@cse.unl.edu> Date: Tue, 25 Oct 2022 16:47:58 -0500 Subject: [PATCH] Designed and implmented a dynamic programming solution. --- .../src/features/ascent/sortingByDeletion.js | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/ascent/src/features/ascent/sortingByDeletion.js b/ascent/src/features/ascent/sortingByDeletion.js index dc52a4b..2d09ed9 100644 --- a/ascent/src/features/ascent/sortingByDeletion.js +++ b/ascent/src/features/ascent/sortingByDeletion.js @@ -1,3 +1,35 @@ +class Backpointer { + constructor(previousIndex, count) { + this.previousIndex = previousIndex; + this.count = count; + } +} + +function chooseBackpointer(list, backpointers) { + const currentIndex = backpointers.length; + const currentElement = currentIndex < list.length ? list[currentIndex] : Infinity; + let best = new Backpointer(undefined, 0); + for (let i = 0; i < currentIndex; ++i) { + if (list[i] <= currentElement) { + const candidate = new Backpointer(i, backpointers[i].count + 1); + if (candidate.count > best.count) { + best = candidate; + } + } + } + return best; +} + export function deleteToSort(list) { - return []; // TODO: stub + const backpointers = []; + while (backpointers.length <= list.length) { + backpointers.push(chooseBackpointer(list, backpointers)); + } + const reversedResults = []; + for (let current = backpointers[list.length].previousIndex; + current !== undefined; + current = backpointers[current].previousIndex) { + reversedResults.push(list[current]); + } + return reversedResults.reverse(); } -- GitLab