From 1ef238d9e4b6d28a469597384e0b7141e746e322 Mon Sep 17 00:00:00 2001 From: ROHAN13498 <95855114+ROHAN13498@users.noreply.github.com> Date: Mon, 9 Oct 2023 12:30:58 +0530 Subject: [PATCH 1/4] Combined Min Heap and Max Heap classes --- Data-Structures/Heap/BinaryHeap.js | 81 ++++++++++++ Data-Structures/Heap/MaxHeap.js | 85 ------------- Data-Structures/Heap/MinHeap.js | 127 ------------------- Data-Structures/Heap/test/BinaryHeap.test.js | 99 +++++++++++++++ Data-Structures/Heap/test/MinHeap.test.js | 37 ------ 5 files changed, 180 insertions(+), 249 deletions(-) create mode 100644 Data-Structures/Heap/BinaryHeap.js delete mode 100644 Data-Structures/Heap/MaxHeap.js delete mode 100644 Data-Structures/Heap/MinHeap.js create mode 100644 Data-Structures/Heap/test/BinaryHeap.test.js delete mode 100644 Data-Structures/Heap/test/MinHeap.test.js diff --git a/Data-Structures/Heap/BinaryHeap.js b/Data-Structures/Heap/BinaryHeap.js new file mode 100644 index 0000000000..c39234ca65 --- /dev/null +++ b/Data-Structures/Heap/BinaryHeap.js @@ -0,0 +1,81 @@ +class BinaryHeap { + constructor(comparatorFunction) { + this.heap = []; + this.comparator = comparatorFunction; + } + + insert(value) { + this.heap.push(value); + this.bubbleUp(this.heap.length - 1); + } + + size() { + return this.heap.length; + } + + empty() { + return this.size() === 0; + } + + bubbleUp(currIdx) { + let parentIdx = Math.floor((currIdx - 1) / 2); + + while (currIdx > 0 && this.comparator(this.heap[currIdx], this.heap[parentIdx])) { + this.swap(currIdx, parentIdx); + currIdx = parentIdx; + parentIdx = Math.floor((currIdx - 1) / 2); + } + } + + sinkDown(currIdx) { + let childOneIdx = currIdx * 2 + 1; + + while (childOneIdx < this.size()) { + const childTwoIdx = childOneIdx + 1 < this.size() ? childOneIdx + 1 : -1; + const swapIdx = + childTwoIdx !== -1 && this.comparator(this.heap[childTwoIdx], this.heap[childOneIdx]) + ? childTwoIdx + : childOneIdx; + + if (this.comparator(this.heap[swapIdx], this.heap[currIdx])) { + this.swap(currIdx, swapIdx); + currIdx = swapIdx; + childOneIdx = currIdx * 2 + 1; + } else { + return; + } + } + } + + peek() { + return this.heap[0]; + } + + extractTop() { + const top = this.peek(); + const last = this.heap.pop(); + + if (!this.empty()) { + this.heap[0] = last; + this.sinkDown(0); + } + + return top; + } + + swap(index1, index2) { + [this.heap[index1], this.heap[index2]] = [this.heap[index2], this.heap[index1]]; + } + } + + // Min Heap comparator function + const minHeapComparator = (a, b) => a < b; + + // Max Heap comparator function + const maxHeapComparator = (a, b) => a > b; + + // Example usage: + // const minHeap = new BinaryHeap(minHeapComparator); + // const maxHeap = new BinaryHeap(maxHeapComparator); + export { BinaryHeap, minHeapComparator, maxHeapComparator }; + \ No newline at end of file diff --git a/Data-Structures/Heap/MaxHeap.js b/Data-Structures/Heap/MaxHeap.js deleted file mode 100644 index 5788d786e3..0000000000 --- a/Data-Structures/Heap/MaxHeap.js +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Author: Samarth Jain - * Max Heap implementation in Javascript - */ - -class BinaryHeap { - constructor() { - this.heap = [] - } - - insert(value) { - this.heap.push(value) - this.heapify() - } - - size() { - return this.heap.length - } - - empty() { - return this.size() === 0 - } - - // using iterative approach to reorder the heap after insertion - heapify() { - let index = this.size() - 1 - - while (index > 0) { - const element = this.heap[index] - const parentIndex = Math.floor((index - 1) / 2) - const parent = this.heap[parentIndex] - - if (parent[0] >= element[0]) break - this.heap[index] = parent - this.heap[parentIndex] = element - index = parentIndex - } - } - - // Extracting the maximum element from the Heap - extractMax() { - const max = this.heap[0] - const tmp = this.heap.pop() - if (!this.empty()) { - this.heap[0] = tmp - this.sinkDown(0) - } - return max - } - - // To restore the balance of the heap after extraction. - sinkDown(index) { - const left = 2 * index + 1 - const right = 2 * index + 2 - let largest = index - const length = this.size() - - if (left < length && this.heap[left][0] > this.heap[largest][0]) { - largest = left - } - if (right < length && this.heap[right][0] > this.heap[largest][0]) { - largest = right - } - // swap - if (largest !== index) { - const tmp = this.heap[largest] - this.heap[largest] = this.heap[index] - this.heap[index] = tmp - this.sinkDown(largest) - } - } -} - -// Example - -// const maxHeap = new BinaryHeap() -// maxHeap.insert([4]) -// maxHeap.insert([3]) -// maxHeap.insert([6]) -// maxHeap.insert([1]) -// maxHeap.insert([8]) -// maxHeap.insert([2]) -// const mx = maxHeap.extractMax() - -export { BinaryHeap } diff --git a/Data-Structures/Heap/MinHeap.js b/Data-Structures/Heap/MinHeap.js deleted file mode 100644 index a115447c97..0000000000 --- a/Data-Structures/Heap/MinHeap.js +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Min Heap is one of the two Binary Heap types (the other is Max Heap) - * which maintains the smallest value of its input array on top and remaining values in loosely (but not perfectly sorted) order. - * - * Min Heaps can be expressed as a 'complete' binary tree structure - * (in which all levels of the binary tree are filled, with the exception of the last level which must be filled left-to-right). - * - * However the Min Heap class below expresses this tree structure as an array - * which represent the binary tree node values in an array ordered from root-to-leaf, left-to-right. - * - * In the array representation, the parent node-child node relationship is such that the - * * parent index relative to its two children are: (parentIdx * 2) and (parent * 2 + 1) - * * and either child's index position relative to its parent is: Math.floor((childIdx-1)/2) - * - * The parent and respective child values define much of heap behavior as we continue to sort or not sort depending on their values. - * * The parent value must be less than or equal to either child's value. - * - * This is a condensed overview but for more information and visuals here is a nice read: https://www.geeksforgeeks.org/binary-heap/ - */ - -class MinHeap { - constructor(array) { - this.heap = this.initializeHeap(array) - } - - /** - * startingParent represents the parent of the last index (=== array.length-1) - * and iterates towards 0 with all index values below sorted to meet heap conditions - */ - initializeHeap(array) { - const startingParent = Math.floor((array.length - 2) / 2) - - for (let currIdx = startingParent; currIdx >= 0; currIdx--) { - this.sinkDown(currIdx, array.length - 1, array) - } - return array - } - - /** - * overall functionality: heap-sort value at a starting index (currIdx) towards end of heap - * - * currIdx is considered to be a starting 'parent' index of two children indices (childOneIdx, childTwoIdx). - * endIdx represents the last valid index in the heap. - * - * first check that childOneIdx and childTwoIdx are both smaller than endIdx - * and check for the smaller heap value between them. - * - * the child index with the smaller heap value is set to a variable called swapIdx. - * - * swapIdx's value will be compared to currIdx (the 'parent' index) - * and if swapIdx's value is smaller than currIdx's value, swap the values in the heap, - * update currIdx and recalculate the new childOneIdx to check heap conditions again. - * - * if there is no swap, it means the children indices and the parent index satisfy heap conditions and can exit the function. - */ - sinkDown(currIdx, endIdx, heap) { - let childOneIdx = currIdx * 2 + 1 - - while (childOneIdx <= endIdx) { - const childTwoIdx = childOneIdx + 1 <= endIdx ? childOneIdx + 1 : -1 - const swapIdx = - childTwoIdx !== -1 && heap[childTwoIdx] < heap[childOneIdx] - ? childTwoIdx - : childOneIdx - - if (heap[swapIdx] < heap[currIdx]) { - this.swap(currIdx, swapIdx, heap) - currIdx = swapIdx - childOneIdx = currIdx * 2 + 1 - } else { - return - } - } - } - - /** - * overall functionality: heap-sort value at a starting index (currIdx) towards front of heap. - * - * while the currIdx's value is smaller than its parent's (parentIdx) value, swap the values in the heap - * update currIdx and recalculate the new parentIdx to check heap condition again. - * - * iteration does not end while a valid currIdx has a value smaller than its parentIdx's value - */ - bubbleUp(currIdx) { - let parentIdx = Math.floor((currIdx - 1) / 2) - - while (currIdx > 0 && this.heap[currIdx] < this.heap[parentIdx]) { - this.swap(currIdx, parentIdx, this.heap) - currIdx = parentIdx - parentIdx = Math.floor((currIdx - 1) / 2) - } - } - - peek() { - return this.heap[0] - } - - /** - * the min heap value should be the first value in the heap (=== this.heap[0]) - * - * firstIdx value and lastIdx value are swapped - * the resulting min heap value now resides at heap[heap.length-1] which is popped and later returned. - * - * the remaining values in the heap are re-sorted - */ - extractMin() { - this.swap(0, this.heap.length - 1, this.heap) - const min = this.heap.pop() - this.sinkDown(0, this.heap.length - 1, this.heap) - return min - } - - // a new value is pushed to the end of the heap and sorted up - insert(value) { - this.heap.push(value) - this.bubbleUp(this.heap.length - 1) - } - - // index-swapping helper method - swap(idx1, idx2, heap) { - const temp = heap[idx1] - heap[idx1] = heap[idx2] - heap[idx2] = temp - } -} - -export { MinHeap } diff --git a/Data-Structures/Heap/test/BinaryHeap.test.js b/Data-Structures/Heap/test/BinaryHeap.test.js new file mode 100644 index 0000000000..0a79ebc672 --- /dev/null +++ b/Data-Structures/Heap/test/BinaryHeap.test.js @@ -0,0 +1,99 @@ +import { BinaryHeap, minHeapComparator, maxHeapComparator } from '../BinaryHeap'; +describe('BinaryHeap', () => { + describe('MinHeap', () => { + let minHeap; + + beforeEach(() => { + minHeap = new BinaryHeap(minHeapComparator); + minHeap.insert(4); + minHeap.insert(3); + minHeap.insert(6); + minHeap.insert(1); + minHeap.insert(8); + minHeap.insert(2); + }); + + it('should initialize a heap from an input array', () => { + expect(minHeap.heap).toEqual([1, 3, 2, 4, 8, 6]); + }); + + it('should show the top value in the heap', () => { + const minValue = minHeap.peek(); + expect(minValue).toEqual(1); + }); + + it('should remove and return the top value in the heap', () => { + const minValue = minHeap.extractTop(); + expect(minValue).toEqual(1); + expect(minHeap.heap).toEqual([2, 3, 6, 4, 8]); + }); + + it('should handle insertion of duplicate values', () => { + minHeap.insert(2); + expect(minHeap.heap).toEqual([ 1, 3, 2, 4,8, 6, 2]); + }); + + + it('should handle an empty heap', () => { + const emptyHeap = new BinaryHeap(minHeapComparator); + expect(emptyHeap.peek()).toBeUndefined(); + expect(emptyHeap.extractTop()).toBeUndefined(); + }); + + it('should handle extracting all elements from the heap', () => { + const extractedValues = []; + while (!minHeap.empty()) { + extractedValues.push(minHeap.extractTop()); + } + expect(extractedValues).toEqual([1, 2, 3, 4, 6, 8]); + }); + }); + + describe('MaxHeap', () => { + let maxHeap; + + beforeEach(() => { + maxHeap = new BinaryHeap(maxHeapComparator); + maxHeap.insert(4); + maxHeap.insert(3); + maxHeap.insert(6); + maxHeap.insert(1); + maxHeap.insert(8); + maxHeap.insert(2); + }); + + it('should initialize a heap from an input array', () => { + expect(maxHeap.heap).toEqual([8, 6, 4, 1, 3, 2]); + }); + + it('should show the top value in the heap', () => { + const maxValue = maxHeap.peek(); + expect(maxValue).toEqual(8); + }); + + it('should remove and return the top value in the heap', () => { + const maxValue = maxHeap.extractTop(); + expect(maxValue).toEqual(8); + expect(maxHeap.heap).toEqual([6, 3, 4, 1, 2]); + }); + + it('should handle insertion of duplicate values', () => { + maxHeap.insert(6); + expect(maxHeap.heap).toEqual([8, 6, 6, 1, 3, 2, 4]); + }); + + it('should handle an empty heap', () => { + const emptyHeap = new BinaryHeap(maxHeapComparator); + expect(emptyHeap.peek()).toBeUndefined(); + expect(emptyHeap.extractTop()).toBeUndefined(); + }); + + it('should handle extracting all elements from the heap', () => { + const extractedValues = []; + while (!maxHeap.empty()) { + extractedValues.push(maxHeap.extractTop()); + } + expect(extractedValues).toEqual([8, 6, 4, 3, 2, 1]); + }); + }); + }); \ No newline at end of file diff --git a/Data-Structures/Heap/test/MinHeap.test.js b/Data-Structures/Heap/test/MinHeap.test.js deleted file mode 100644 index d7947ad12f..0000000000 --- a/Data-Structures/Heap/test/MinHeap.test.js +++ /dev/null @@ -1,37 +0,0 @@ -import { MinHeap } from '../MinHeap' - -describe('MinHeap', () => { - const array = [2, 4, 10, 23, 43, 42, 39, 7, 9, 16, 85, 1, 51] - let heap - - beforeEach(() => { - heap = new MinHeap(array) - }) - - it('should initialize a heap from an input array', () => { - expect(heap).toEqual({ - heap: [1, 4, 2, 7, 16, 10, 39, 23, 9, 43, 85, 42, 51] - }) // eslint-disable-line - }) - - it('should show the top value in the heap', () => { - const minValue = heap.peek() - - expect(minValue).toEqual(1) - }) - - it('should remove and return the top value in the heap', () => { - const minValue = heap.extractMin() - - expect(minValue).toEqual(1) - expect(heap).toEqual({ heap: [2, 4, 10, 7, 16, 42, 39, 23, 9, 43, 85, 51] }) // eslint-disable-line - }) - - it('should insert a new value and sort until it meets heap conditions', () => { - heap.insert(15) - - expect(heap).toEqual({ - heap: [2, 4, 10, 7, 16, 15, 39, 23, 9, 43, 85, 51, 42] - }) // eslint-disable-line - }) -}) From 45170ebad28cc78f81bcdd22439cd1a90d49a752 Mon Sep 17 00:00:00 2001 From: ROHAN13498 <95855114+ROHAN13498@users.noreply.github.com> Date: Mon, 9 Oct 2023 21:47:01 +0530 Subject: [PATCH 2/4] Added JSdoc comments and also improved tests for binary heap --- Data-Structures/Heap/BinaryHeap.js | 207 ++++++++++++------- Data-Structures/Heap/test/BinaryHeap.test.js | 169 +++++++-------- Maths/test/EuclideanDistance.test.js | 10 +- 3 files changed, 211 insertions(+), 175 deletions(-) diff --git a/Data-Structures/Heap/BinaryHeap.js b/Data-Structures/Heap/BinaryHeap.js index c39234ca65..f365022f0c 100644 --- a/Data-Structures/Heap/BinaryHeap.js +++ b/Data-Structures/Heap/BinaryHeap.js @@ -1,81 +1,138 @@ +/** + * BinaryHeap class represents a binary heap data structure that can be configured as a Min Heap or Max Heap. + * + * Binary heaps are binary trees that are filled level by level and from left to right inside each level. + * They have the property that any parent node has a smaller (for Min Heap) or greater (for Max Heap) priority + * than its children, ensuring that the root of the tree always holds the extremal value. + * + * This implementation of the Binary Heap allows nodes to be associated with values of any data type and priorities. + * The heap is represented as an array with nodes ordered from root to leaf, left to right. + * Therefore, the parent-child relationships are as follows: + * - The positions of the children nodes relative to their parent are: (parentPos * 2 + 1) and (parentPos * 2 + 2). + * - The position of the parent node relative to either of its children is: Math.floor((childPos - 1) / 2). + */ class BinaryHeap { - constructor(comparatorFunction) { - this.heap = []; - this.comparator = comparatorFunction; - } - - insert(value) { - this.heap.push(value); - this.bubbleUp(this.heap.length - 1); - } - - size() { - return this.heap.length; - } - - empty() { - return this.size() === 0; - } - - bubbleUp(currIdx) { - let parentIdx = Math.floor((currIdx - 1) / 2); - - while (currIdx > 0 && this.comparator(this.heap[currIdx], this.heap[parentIdx])) { - this.swap(currIdx, parentIdx); - currIdx = parentIdx; - parentIdx = Math.floor((currIdx - 1) / 2); - } - } - - sinkDown(currIdx) { - let childOneIdx = currIdx * 2 + 1; - - while (childOneIdx < this.size()) { - const childTwoIdx = childOneIdx + 1 < this.size() ? childOneIdx + 1 : -1; - const swapIdx = - childTwoIdx !== -1 && this.comparator(this.heap[childTwoIdx], this.heap[childOneIdx]) - ? childTwoIdx - : childOneIdx; - - if (this.comparator(this.heap[swapIdx], this.heap[currIdx])) { - this.swap(currIdx, swapIdx); - currIdx = swapIdx; - childOneIdx = currIdx * 2 + 1; - } else { - return; - } - } - } - - peek() { - return this.heap[0]; + /** + * Creates a new BinaryHeap instance. + * @param {Function} comparatorFunction - The comparator function used to determine the order of elements (e.g., minHeapComparator or maxHeapComparator). + */ + constructor(comparatorFunction) { + this.heap = []; + this.comparator = comparatorFunction; + } + + /** + * Inserts a new value into the heap. + * @param {*} value - The value to be inserted into the heap. + */ + insert(value) { + this.heap.push(value); + this.bubbleUp(this.heap.length - 1); + } + + /** + * Returns the number of elements in the heap. + * @returns {number} - The number of elements in the heap. + */ + size() { + return this.heap.length; + } + + /** + * Checks if the heap is empty. + * @returns {boolean} - True if the heap is empty, false otherwise. + */ + empty() { + return this.size() === 0; + } + + /** + * Bubbles up a value from the specified index to maintain the heap property. + * @param {number} currIdx - The index of the value to be bubbled up. + * @private + */ + bubbleUp(currIdx) { + let parentIdx = Math.floor((currIdx - 1) / 2); + + while ( + currIdx > 0 && + this.comparator(this.heap[currIdx], this.heap[parentIdx]) + ) { + this.swap(currIdx, parentIdx); + currIdx = parentIdx; + parentIdx = Math.floor((currIdx - 1) / 2); } - - extractTop() { - const top = this.peek(); - const last = this.heap.pop(); - - if (!this.empty()) { - this.heap[0] = last; - this.sinkDown(0); + } + + /** + * Sinks down a value from the specified index to maintain the heap property. + * @param {number} currIdx - The index of the value to be sunk down. + * @private + */ + sinkDown(currIdx) { + let childOneIdx = currIdx * 2 + 1; + + while (childOneIdx < this.size()) { + const childTwoIdx = + childOneIdx + 1 < this.size() ? childOneIdx + 1 : -1; + const swapIdx = + childTwoIdx !== -1 && + this.comparator(this.heap[childTwoIdx], this.heap[childOneIdx]) + ? childTwoIdx + : childOneIdx; + + if (this.comparator(this.heap[swapIdx], this.heap[currIdx])) { + this.swap(currIdx, swapIdx); + currIdx = swapIdx; + childOneIdx = currIdx * 2 + 1; + } else { + return; } - - return top; } - - swap(index1, index2) { - [this.heap[index1], this.heap[index2]] = [this.heap[index2], this.heap[index1]]; + } + + /** + * Retrieves the top element of the heap without removing it. + * @returns {*} - The top element of the heap. + */ + peek() { + return this.heap[0]; + } + + /** + * Removes and returns the top element of the heap. + * @returns {*} - The top element of the heap. + */ + extractTop() { + const top = this.peek(); + const last = this.heap.pop(); + + if (!this.empty()) { + this.heap[0] = last; + this.sinkDown(0); } + + return top; + } + + /** + * Swaps elements at two specified indices in the heap. + * @param {number} index1 - The index of the first element to be swapped. + * @param {number} index2 - The index of the second element to be swapped. + * @private + */ + swap(index1, index2) { + [this.heap[index1], this.heap[index2]] = [ + this.heap[index2], + this.heap[index1], + ]; } - - // Min Heap comparator function - const minHeapComparator = (a, b) => a < b; - - // Max Heap comparator function - const maxHeapComparator = (a, b) => a > b; - - // Example usage: - // const minHeap = new BinaryHeap(minHeapComparator); - // const maxHeap = new BinaryHeap(maxHeapComparator); - export { BinaryHeap, minHeapComparator, maxHeapComparator }; - \ No newline at end of file +} + +// Min Heap comparator function +const minHeapComparator = (a, b) => a < b; + +// Max Heap comparator function +const maxHeapComparator = (a, b) => a > b; + +export { BinaryHeap, minHeapComparator} diff --git a/Data-Structures/Heap/test/BinaryHeap.test.js b/Data-Structures/Heap/test/BinaryHeap.test.js index 0a79ebc672..1207ed3fb7 100644 --- a/Data-Structures/Heap/test/BinaryHeap.test.js +++ b/Data-Structures/Heap/test/BinaryHeap.test.js @@ -1,99 +1,72 @@ -import { BinaryHeap, minHeapComparator, maxHeapComparator } from '../BinaryHeap'; +import { BinaryHeap, minHeapComparator} from '../BinaryHeap' + describe('BinaryHeap', () => { - describe('MinHeap', () => { - let minHeap; - - beforeEach(() => { - minHeap = new BinaryHeap(minHeapComparator); - minHeap.insert(4); - minHeap.insert(3); - minHeap.insert(6); - minHeap.insert(1); - minHeap.insert(8); - minHeap.insert(2); - }); - - it('should initialize a heap from an input array', () => { - expect(minHeap.heap).toEqual([1, 3, 2, 4, 8, 6]); - }); - - it('should show the top value in the heap', () => { - const minValue = minHeap.peek(); - expect(minValue).toEqual(1); - }); - - it('should remove and return the top value in the heap', () => { - const minValue = minHeap.extractTop(); - expect(minValue).toEqual(1); - expect(minHeap.heap).toEqual([2, 3, 6, 4, 8]); - }); - - it('should handle insertion of duplicate values', () => { - minHeap.insert(2); - expect(minHeap.heap).toEqual([ 1, 3, 2, 4,8, 6, 2]); - }); - - - it('should handle an empty heap', () => { - const emptyHeap = new BinaryHeap(minHeapComparator); - expect(emptyHeap.peek()).toBeUndefined(); - expect(emptyHeap.extractTop()).toBeUndefined(); - }); - - it('should handle extracting all elements from the heap', () => { - const extractedValues = []; - while (!minHeap.empty()) { - extractedValues.push(minHeap.extractTop()); - } - expect(extractedValues).toEqual([1, 2, 3, 4, 6, 8]); - }); - }); - - describe('MaxHeap', () => { - let maxHeap; - - beforeEach(() => { - maxHeap = new BinaryHeap(maxHeapComparator); - maxHeap.insert(4); - maxHeap.insert(3); - maxHeap.insert(6); - maxHeap.insert(1); - maxHeap.insert(8); - maxHeap.insert(2); - }); - - it('should initialize a heap from an input array', () => { - expect(maxHeap.heap).toEqual([8, 6, 4, 1, 3, 2]); - }); - - it('should show the top value in the heap', () => { - const maxValue = maxHeap.peek(); - expect(maxValue).toEqual(8); - }); - - it('should remove and return the top value in the heap', () => { - const maxValue = maxHeap.extractTop(); - expect(maxValue).toEqual(8); - expect(maxHeap.heap).toEqual([6, 3, 4, 1, 2]); - }); - - it('should handle insertion of duplicate values', () => { - maxHeap.insert(6); - expect(maxHeap.heap).toEqual([8, 6, 6, 1, 3, 2, 4]); - }); - - it('should handle an empty heap', () => { - const emptyHeap = new BinaryHeap(maxHeapComparator); - expect(emptyHeap.peek()).toBeUndefined(); - expect(emptyHeap.extractTop()).toBeUndefined(); - }); - - it('should handle extracting all elements from the heap', () => { - const extractedValues = []; - while (!maxHeap.empty()) { - extractedValues.push(maxHeap.extractTop()); - } - expect(extractedValues).toEqual([8, 6, 4, 3, 2, 1]); - }); - }); - }); \ No newline at end of file + describe('MinHeap', () => { + let minHeap + + beforeEach(() => { + // Initialize a MinHeap + minHeap = new BinaryHeap(minHeapComparator) + minHeap.insert(4) + minHeap.insert(3) + minHeap.insert(6) + minHeap.insert(1) + minHeap.insert(8) + minHeap.insert(2) + }) + + it('should initialize a heap from an input array', () => { + // Check if the heap is initialized correctly + expect(minHeap.heap).toEqual([1, 3, 2, 4, 8, 6]) + }) + + it('should show the top value in the heap', () => { + // Check if the top value is as expected + const minValue = minHeap.peek() + expect(minValue).toEqual(1) + }) + + it('should remove and return the top value in the heap', () => { + // Check if the top value is removed correctly + const minValue = minHeap.extractTop() + expect(minValue).toEqual(1) + expect(minHeap.heap).toEqual([2, 3, 6, 4, 8]) + }) + + it('should handle insertion of duplicate values', () => { + // Check if the heap handles duplicate values correctly + minHeap.insert(2) + expect(minHeap.heap).toEqual([1, 3, 2, 4, 8, 6, 2]) + }) + + it('should handle an empty heap', () => { + // Check if an empty heap behaves as expected + const emptyHeap = new BinaryHeap(minHeapComparator) + expect(emptyHeap.peek()).toBeUndefined() + expect(emptyHeap.extractTop()).toBeUndefined() + }) + + it('should handle extracting all elements from the heap', () => { + // Check if all elements can be extracted in the correct order + const extractedValues = [] + while (!minHeap.empty()) { + extractedValues.push(minHeap.extractTop()) + } + expect(extractedValues).toEqual([1, 2, 3, 4, 6, 8]) + }) + + it('should insert elements in ascending order', () => { + // Check if elements are inserted in ascending order + const ascendingHeap = new BinaryHeap(minHeapComparator); + ascendingHeap.insert(4); + ascendingHeap.insert(3); + ascendingHeap.insert(2); + ascendingHeap.insert(1); + expect(ascendingHeap.extractTop()).toEqual(1); + expect(ascendingHeap.extractTop()).toEqual(2); + expect(ascendingHeap.extractTop()).toEqual(3); + expect(ascendingHeap.extractTop()).toEqual(4); + }) + }) + +}) diff --git a/Maths/test/EuclideanDistance.test.js b/Maths/test/EuclideanDistance.test.js index d73bb03875..717ea2e6a0 100644 --- a/Maths/test/EuclideanDistance.test.js +++ b/Maths/test/EuclideanDistance.test.js @@ -2,11 +2,17 @@ import { EuclideanDistance } from '../EuclideanDistance.js' describe('EuclideanDistance', () => { it('should calculate the distance correctly for 2D vectors', () => { - expect(EuclideanDistance([0, 0], [2, 2])).toBeCloseTo(2.8284271247461903, 10) + expect(EuclideanDistance([0, 0], [2, 2])).toBeCloseTo( + 2.8284271247461903, + 10 + ) }) it('should calculate the distance correctly for 3D vectors', () => { - expect(EuclideanDistance([0, 0, 0], [2, 2, 2])).toBeCloseTo(3.4641016151377544, 10) + expect(EuclideanDistance([0, 0, 0], [2, 2, 2])).toBeCloseTo( + 3.4641016151377544, + 10 + ) }) it('should calculate the distance correctly for 4D vectors', () => { From dc2d8015c8dfd60c9ba7a7a895523030663ca3cb Mon Sep 17 00:00:00 2001 From: ROHAN13498 <95855114+ROHAN13498@users.noreply.github.com> Date: Mon, 9 Oct 2023 22:52:49 +0530 Subject: [PATCH 3/4] Added private methods for BinaryHeap class --- Data-Structures/Heap/BinaryHeap.js | 95 +++++++++++--------- Data-Structures/Heap/test/BinaryHeap.test.js | 24 ++--- 2 files changed, 67 insertions(+), 52 deletions(-) diff --git a/Data-Structures/Heap/BinaryHeap.js b/Data-Structures/Heap/BinaryHeap.js index f365022f0c..b8aeb0c9c2 100644 --- a/Data-Structures/Heap/BinaryHeap.js +++ b/Data-Structures/Heap/BinaryHeap.js @@ -5,20 +5,26 @@ * They have the property that any parent node has a smaller (for Min Heap) or greater (for Max Heap) priority * than its children, ensuring that the root of the tree always holds the extremal value. * - * This implementation of the Binary Heap allows nodes to be associated with values of any data type and priorities. - * The heap is represented as an array with nodes ordered from root to leaf, left to right. - * Therefore, the parent-child relationships are as follows: - * - The positions of the children nodes relative to their parent are: (parentPos * 2 + 1) and (parentPos * 2 + 2). - * - The position of the parent node relative to either of its children is: Math.floor((childPos - 1) / 2). + * @class */ class BinaryHeap { /** * Creates a new BinaryHeap instance. + * @constructor * @param {Function} comparatorFunction - The comparator function used to determine the order of elements (e.g., minHeapComparator or maxHeapComparator). */ constructor(comparatorFunction) { - this.heap = []; - this.comparator = comparatorFunction; + /** + * The heap array that stores elements. + * @member {Array} + */ + this.heap = [] + + /** + * The comparator function used for ordering elements in the heap. + * @member {Function} + */ + this.comparator = comparatorFunction } /** @@ -26,8 +32,8 @@ class BinaryHeap { * @param {*} value - The value to be inserted into the heap. */ insert(value) { - this.heap.push(value); - this.bubbleUp(this.heap.length - 1); + this.heap.push(value) + this.#bubbleUp(this.heap.length - 1) } /** @@ -35,7 +41,7 @@ class BinaryHeap { * @returns {number} - The number of elements in the heap. */ size() { - return this.heap.length; + return this.heap.length } /** @@ -43,7 +49,7 @@ class BinaryHeap { * @returns {boolean} - True if the heap is empty, false otherwise. */ empty() { - return this.size() === 0; + return this.size() === 0 } /** @@ -51,16 +57,16 @@ class BinaryHeap { * @param {number} currIdx - The index of the value to be bubbled up. * @private */ - bubbleUp(currIdx) { - let parentIdx = Math.floor((currIdx - 1) / 2); + #bubbleUp(currIdx) { + let parentIdx = Math.floor((currIdx - 1) / 2) while ( currIdx > 0 && this.comparator(this.heap[currIdx], this.heap[parentIdx]) ) { - this.swap(currIdx, parentIdx); - currIdx = parentIdx; - parentIdx = Math.floor((currIdx - 1) / 2); + this.#swap(currIdx, parentIdx) + currIdx = parentIdx + parentIdx = Math.floor((currIdx - 1) / 2) } } @@ -69,24 +75,23 @@ class BinaryHeap { * @param {number} currIdx - The index of the value to be sunk down. * @private */ - sinkDown(currIdx) { - let childOneIdx = currIdx * 2 + 1; + #sinkDown(currIdx) { + let childOneIdx = currIdx * 2 + 1 while (childOneIdx < this.size()) { - const childTwoIdx = - childOneIdx + 1 < this.size() ? childOneIdx + 1 : -1; + const childTwoIdx = childOneIdx + 1 < this.size() ? childOneIdx + 1 : -1 const swapIdx = childTwoIdx !== -1 && this.comparator(this.heap[childTwoIdx], this.heap[childOneIdx]) ? childTwoIdx - : childOneIdx; + : childOneIdx if (this.comparator(this.heap[swapIdx], this.heap[currIdx])) { - this.swap(currIdx, swapIdx); - currIdx = swapIdx; - childOneIdx = currIdx * 2 + 1; + this.#swap(currIdx, swapIdx) + currIdx = swapIdx + childOneIdx = currIdx * 2 + 1 } else { - return; + return } } } @@ -96,7 +101,7 @@ class BinaryHeap { * @returns {*} - The top element of the heap. */ peek() { - return this.heap[0]; + return this.heap[0] } /** @@ -104,15 +109,15 @@ class BinaryHeap { * @returns {*} - The top element of the heap. */ extractTop() { - const top = this.peek(); - const last = this.heap.pop(); + const top = this.peek() + const last = this.heap.pop() if (!this.empty()) { - this.heap[0] = last; - this.sinkDown(0); + this.heap[0] = last + this.#sinkDown(0) } - return top; + return top } /** @@ -121,18 +126,28 @@ class BinaryHeap { * @param {number} index2 - The index of the second element to be swapped. * @private */ - swap(index1, index2) { - [this.heap[index1], this.heap[index2]] = [ + #swap(index1, index2) { + ;[this.heap[index1], this.heap[index2]] = [ this.heap[index2], - this.heap[index1], - ]; + this.heap[index1] + ] } } -// Min Heap comparator function -const minHeapComparator = (a, b) => a < b; +/** + * Comparator function for creating a Min Heap. + * @param {*} a - The first element to compare. + * @param {*} b - The second element to compare. + * @returns {boolean} - True if 'a' should have higher priority than 'b' in the Min Heap, false otherwise. + */ +const minHeapComparator = (a, b) => a < b -// Max Heap comparator function -const maxHeapComparator = (a, b) => a > b; +/** + * Comparator function for creating a Max Heap. + * @param {*} a - The first element to compare. + * @param {*} b - The second element to compare. + * @returns {boolean} - True if 'a' should have higher priority than 'b' in the Max Heap, false otherwise. + */ +const maxHeapComparator = (a, b) => a > b -export { BinaryHeap, minHeapComparator} +export { BinaryHeap, minHeapComparator, maxHeapComparator } diff --git a/Data-Structures/Heap/test/BinaryHeap.test.js b/Data-Structures/Heap/test/BinaryHeap.test.js index 1207ed3fb7..56aef11e02 100644 --- a/Data-Structures/Heap/test/BinaryHeap.test.js +++ b/Data-Structures/Heap/test/BinaryHeap.test.js @@ -1,4 +1,4 @@ -import { BinaryHeap, minHeapComparator} from '../BinaryHeap' +import { BinaryHeap, minHeapComparator } from '../BinaryHeap' describe('BinaryHeap', () => { describe('MinHeap', () => { @@ -36,6 +36,7 @@ describe('BinaryHeap', () => { it('should handle insertion of duplicate values', () => { // Check if the heap handles duplicate values correctly minHeap.insert(2) + console.log(minHeap.heap); expect(minHeap.heap).toEqual([1, 3, 2, 4, 8, 6, 2]) }) @@ -54,19 +55,18 @@ describe('BinaryHeap', () => { } expect(extractedValues).toEqual([1, 2, 3, 4, 6, 8]) }) - + it('should insert elements in ascending order', () => { // Check if elements are inserted in ascending order - const ascendingHeap = new BinaryHeap(minHeapComparator); - ascendingHeap.insert(4); - ascendingHeap.insert(3); - ascendingHeap.insert(2); - ascendingHeap.insert(1); - expect(ascendingHeap.extractTop()).toEqual(1); - expect(ascendingHeap.extractTop()).toEqual(2); - expect(ascendingHeap.extractTop()).toEqual(3); - expect(ascendingHeap.extractTop()).toEqual(4); + const ascendingHeap = new BinaryHeap(minHeapComparator) + ascendingHeap.insert(4) + ascendingHeap.insert(3) + ascendingHeap.insert(2) + ascendingHeap.insert(1) + expect(ascendingHeap.extractTop()).toEqual(1) + expect(ascendingHeap.extractTop()).toEqual(2) + expect(ascendingHeap.extractTop()).toEqual(3) + expect(ascendingHeap.extractTop()).toEqual(4) }) }) - }) From dff36e7f18f71296273150cf59dbcb1733ffbd0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lars=20M=C3=BCller?= <34514239+appgurueu@users.noreply.github.com> Date: Mon, 9 Oct 2023 21:30:04 +0200 Subject: [PATCH 4/4] JSDoc knows that a class is a class I assume the @class tag is for classes implemented via constructor functions, not using ES6 class syntax --- Data-Structures/Heap/BinaryHeap.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/Data-Structures/Heap/BinaryHeap.js b/Data-Structures/Heap/BinaryHeap.js index b8aeb0c9c2..af4fe3ba75 100644 --- a/Data-Structures/Heap/BinaryHeap.js +++ b/Data-Structures/Heap/BinaryHeap.js @@ -4,8 +4,6 @@ * Binary heaps are binary trees that are filled level by level and from left to right inside each level. * They have the property that any parent node has a smaller (for Min Heap) or greater (for Max Heap) priority * than its children, ensuring that the root of the tree always holds the extremal value. - * - * @class */ class BinaryHeap { /**