From d671327ebe63832434285ef96cabf255e11bf2cd Mon Sep 17 00:00:00 2001 From: Nikunj Bisht <52692588+Nikunj-bisht@users.noreply.github.com> Date: Thu, 26 Oct 2023 19:08:19 +0530 Subject: [PATCH] feat: added find subsets algorithm using bitmanipulation (#1514) * feat: added find subsets algorithm using bitmanipulation * file name fix * test file name fix * fix: codespell fix * error handled * added test cases for error --- Bit-Manipulation/GenerateSubSets.js | 34 ++++++++++++++++++ Bit-Manipulation/test/GenerateSubSets.test.js | 36 +++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 Bit-Manipulation/GenerateSubSets.js create mode 100644 Bit-Manipulation/test/GenerateSubSets.test.js diff --git a/Bit-Manipulation/GenerateSubSets.js b/Bit-Manipulation/GenerateSubSets.js new file mode 100644 index 000000000..9ee131d75 --- /dev/null +++ b/Bit-Manipulation/GenerateSubSets.js @@ -0,0 +1,34 @@ +/** + * @function generateSubSets + * @param {Array} inputArray + * @returns {Array} + * @example [1,2] -> [[],[1],[2],[1,2]] + */ + +// The time complexity of this algorithm is BigO(2^n) where n is the length of array +function generateSubSets(inputArray) { + if (!Array.isArray(inputArray)) { + throw new Error('Provided input is not an array') + } + if (inputArray.length > 32) { + throw new RangeError('Error size should be less than equal to 32') + } + let arrayLength = inputArray.length + let subSets = [] + // loop till (2^n) - 1 + for (let i = 0; i < 1 << arrayLength; i++) { + let subSet = [] + for (let j = 0; j < arrayLength; j++) { + // 1 << j it shifts binary digit 1 by j positions and then we perform + // and by AND operation we are checking whetheer jth bit + // in i is set to 1 if result is non zero just add into set + if (i & (1 << j)) { + subSet.push(inputArray[j]) + } + } + subSets.push(subSet) + } + return subSets +} + +export { generateSubSets } diff --git a/Bit-Manipulation/test/GenerateSubSets.test.js b/Bit-Manipulation/test/GenerateSubSets.test.js new file mode 100644 index 000000000..2e3b90ba7 --- /dev/null +++ b/Bit-Manipulation/test/GenerateSubSets.test.js @@ -0,0 +1,36 @@ +import { generateSubSets } from '../GenerateSubSets' + +describe('subSets', () => { + it('find the subsets', () => { + expect(generateSubSets([1, 2, 3])).toEqual([ + [], + [1], + [2], + [1, 2], + [3], + [1, 3], + [2, 3], + [1, 2, 3] + ]) + expect(generateSubSets([1, 2])).toEqual([[], [1], [2], [1, 2]]) + expect(generateSubSets([1, 2, 3])).toEqual([ + [], + [1], + [2], + [1, 2], + [3], + [1, 3], + [2, 3], + [1, 2, 3] + ]) + expect(() => generateSubSets('invalid')).toThrow( + 'Provided input is not an array' + ) + expect(() => + generateSubSets([ + 1, 2, 2, 1, 2, 3, 4, 3, 2, 3, 4, 3, 2, 2, 2, 3, 12, 11, 4, 2, 2, 2, 2, + 1, 2, 3, 5, 6, 7, 7, 8, 6, 5, 6, 7, 8, 9, 8, 0, 6 + ]) + ).toThrow('Error size should be less than equal to 32') + }) +})