Open In App

JavaScript Program for Space Optimization Using bit Manipulations

Last Updated : 20 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • 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
]

Approach 2: Using bitwise operations

  • We are using bitwise operations to mark multiples of 2 or 5 in an array efficiently.
  • It checks bits for divisibility, sets appropriate bits, and prints multiples from 2 to 10 using bitwise manipulation.

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

Javascript




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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads