Open In App

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

Approach 1: Using a bitmask

Example: In the example we see Space optimization using bit manipulations in JavaScript array using bitmask






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
]

Approach 2: Using bitwise operations

Example: In the example we see Space optimization using bit manipulations in JavaScript array using bitwise operations




function checkbit(array, index) {
    return array[index >> 5] & (1 << (index & 31));
}
 
// Sets value of bit for corresponding index
function setbit(array, index) {
    array[index >> 5] |= (1 << (index & 31));
}
 
// Driver code
let a = 2, b = 10;
let size = Math.abs(b - a);
 
 
size = Math.ceil(size / 32);
 
let array = new Array(size);
 
for (let i = a; i <= b; i++)
    if (i % 2 == 0 || i % 5 == 0)
        setbit(array, i - a);
 
console.log("MULTIPLES of 2 and 5:");
for (let i = a; i <= b; i++)
    if (checkbit(array, i - a))
        console.log(i);

Output
MULTIPLES of 2 and 5:
2
4
5
6
8
10

Article Tags :