How to usea bitmask in Javascript
- We are using a bitmask approach to find unique elements in an input array.
- It iterates through the array, setting and checking individual bits to determine uniqueness.
- The uniqueElements array collects unique elements.
Example: In the example we see Space optimization using bit manipulations in JavaScript array using bitmask
Javascript
let inputArray = [3, 6, 7, 9, 6, 12, 7, 15, 18, 21]; let bitSet = 0; let uniqueElements = []; for (let num of inputArray) { let mask = 1 << num; if ((bitSet & mask) === 0) { uniqueElements.push(num); bitSet |= mask; } } console.log( "Unique Elements using Bit Manipulation:" ); // Output: [3, 6, 7, 9, 12, 15, 18, 21] console.log(uniqueElements); |
Output
Unique Elements using Bit Manipulation: [ 3, 6, 7, 9, 12, 15, 18, 21 ]
JavaScript Program for Space Optimization Using bit Manipulations
Space optimization using bit manipulations refers to a technique where data is stored in a compact form using individual bits to represent values, reducing memory usage compared to traditional data structures. This method is efficient for managing and storing binary or boolean information, saving space in memory.
Examples:
Input : 2 10
Output : 2 4 5 6 8 10
Input: 60 95
Output: 60 62 64 65 66 68 70 72 74 75 76 78
80 82 84 85 86 88 90 92 94 95
Table of Content
- Using a bitmask
- Using bitwise operations