Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Bit-Manipulation/GenerateSubSets.js
Original file line number Diff line number Diff line change
@@ -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 }
36 changes: 36 additions & 0 deletions Bit-Manipulation/test/GenerateSubSets.test.js
Original file line number Diff line number Diff line change
@@ -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')
})
})
10 changes: 8 additions & 2 deletions Maths/test/EuclideanDistance.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down