Реализация битовой матрицы в Java

Опубликовано: 21 Января, 2022

BitMatrix - это двумерный массив, в котором каждый элемент равен 0 или 1. Мы реализуем BitMatrix, облегчающий базовые битовые операции, такие как OR, AND, XOR.

Approach:

  1. Import BitSet class from java.util package.
  2. Initialize a bit Array of size rows x cols using BitSet. By default, all bits in the set initially have the value false.
  3. Now by using the methods provided by BitSet class we can manipulate the array.
  4. Methods in BitSet class are set, clear, xor, or, and.
  5. Display the BitMatrix using the display method.

Java

// Java program to demonstrate the
// implementation of BitMatrix
 
import java.util.BitSet;
 
public class BitMatrix {
    public static void main(String[] args)
    {
 
        System.out.println("Bit Matrix Implementation");
 
        try {
            MatrixBuilder bmat = new MatrixBuilder(2, 2);
 
            // All the bitsets in the bitArray will be
            // displayed using display(). The values in
            // bitset refer to the columns which are set
            // to 1.
            bmat.set(0, 0);
            bmat.display();
 
            bmat.set(0, 1);
            bmat.display();
 
            bmat.set(1, 0);
            bmat.display();
 
            bmat.set(1, 1);
            bmat.display();
 
            bmat.clear(0, 1);
            bmat.display();
 
            bmat.and(0, 1);
            bmat.display();
 
            bmat.xor(0, 1);
            bmat.display();
 
            bmat.or(0, 1);
            bmat.display();
        }
        catch (Exception e) {
            System.out.println("Error due to " + e);
        }
    }
}
 
class MatrixBuilder {
    public BitSet[] bitArray;
 
    public MatrixBuilder(int rows, int cols)
    {
        // initializing a bit matrix of size rows x cols.
        bitArray = new BitSet[rows];
 
        int i = 0;
 
        while (i < rows) {
            bitArray[i] = new BitSet(cols);
            i++;
        }
    }
 
    // Method to clear entire array.
    public void clear()
    {
        // Getting the value of number of rows.
        int rows = bitArray.length;
 
        // Getting the value number of columns.
        int cols = bitArray[0].size();
 
        // To clear the bitArray Initialize it once again.
        bitArray = new BitSet[rows];
 
        int i = 0;
        while (i < rows) {
            bitArray[i] = new BitSet(cols);
            i++;
        }
    }
 
    // Method to XOR two rows
    public void xor(int row1, int row2)
    {
        bitArray[row1].xor(bitArray[row2]);
    }
 
    // Here clear() method is overloaded.
    // Method to clear specific bit.
    public void clear(int r, int c)
    {
        bitArray[r].clear(c);
    }
 
    // Method to get a specific bit
    public boolean get(int r, int c)
    {
        return bitArray[r].get(c);
    }
 
    // Method to set a specific bit
    public void set(int r, int c) { bitArray[r].set(c); }
 
    // Method to And two rows
    public void and(int row1, int row2)
    {
        bitArray[row1].and(bitArray[row2]);
    }
 
    // Method to OR two rows
    public void or(int row1, int row2)
    {
        bitArray[row1].or(bitArray[row2]);
    }
 
    // Method to display the bit matrix
    public void display()
    {
        System.out.println(" Bit Matrix : ");
 
        // Here each bitset can be refered as each row
        // we will print all the rows using for loop.
        for (BitSet bs : bitArray)
            System.out.println(bs);
 
        System.out.println();
    }
}
Output
Bit Matrix Implementation

Bit Matrix : 
{0}
{}


Bit Matrix : 
{0, 1}
{}


Bit Matrix : 
{0, 1}
{0}


Bit Matrix : 
{0, 1}
{0, 1}


Bit Matrix : 
{0}
{0, 1}


Bit Matrix : 
{0}
{0, 1}


Bit Matrix : 
{1}
{0, 1}


Bit Matrix : 
{0, 1}
{0, 1}


Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по приемлемой для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .

Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.