[lab2] Bit vector implementation

This commit is contained in:
Andrew Golovashevich 2026-01-29 20:23:29 +03:00
parent 9144681bad
commit dc98c25c41
5 changed files with 119 additions and 1 deletions

View File

@ -1,5 +1,8 @@
[workspace]
members = ["lab1"]
members = [
"lab1",
"lab2"
]
[workspace.lints]

14
lab2/Cargo.toml Normal file
View File

@ -0,0 +1,14 @@
[package]
name = "bgtu-ai-2"
edition = "2024"
[lints]
workspace = true
[dependencies]
rand = "0.9.2"
eframe = { version = "0.33.3", default-features = false, features = ["default_fonts", "glow"] }
[profile.dev.package.eframe]
opt-level = 2
debug = true

View File

@ -0,0 +1,96 @@
use std::cmp::min;
use std::ops::{BitAnd, BitAndAssign, Index, IndexMut, Not, Shl};
pub(super) struct BitVector {
len: usize,
data: Box<[usize]>,
}
impl BitVector {
pub fn alloc(len: usize) -> Self {
return Self {
len,
data: vec![0usize; (len + (usize::BITS as usize) - 1) / (usize::BITS as usize)]
.into_boxed_slice(),
};
}
pub fn count1(&self) -> usize {
let mut counter = 0usize;
for i in 0..(self.data.len() - 1) {
counter += self.data[i].count_ones() as usize;
}
counter += (self.data[self.data.len() - 1]
& (0usize.not().shl(self.len % (usize::BITS as usize)).not()))
.count_ones() as usize;
return counter;
}
}
impl Clone for BitVector {
fn clone(&self) -> Self {
return Self {
len: self.len,
data: self.data.clone(),
};
}
}
impl BitAnd<&Self> for BitVector {
type Output = Self;
fn bitand(self, rhs: &Self) -> Self::Output {
let mut intersected = self.clone();
intersected &= rhs;
return intersected;
}
}
impl BitAndAssign<&Self> for BitVector {
fn bitand_assign(&mut self, rhs: &Self) {
assert_eq!(self.len, rhs.len, "Vectors has different length's");
for i in 0..self.data.len() {
self.data[i] &= rhs.data[i]
}
}
}
struct _BitLocation {
offset: usize,
mask: usize,
}
impl BitVector {
fn _unpackIndex(&self, i: usize) -> _BitLocation {
assert!(i < self.len);
return _BitLocation {
offset: i / (usize::BITS as usize),
mask: 1 << i % (usize::BITS as usize),
};
}
pub fn get(&self, i: usize) -> bool {
let bl = self._unpackIndex(i);
return self.data[bl.offset] & bl.mask != 0;
}
pub fn set(&mut self, i: usize, value: bool) {
let bl = self._unpackIndex(i);
if value {
self.data[bl.offset] |= bl.mask;
} else {
self.data[bl.offset] &= !bl.mask;
}
}
}
impl BitVector {
pub fn resized(&self, newLen: usize) -> BitVector {
let mut new = Self::alloc(newLen);
for i in 0..(min(self.data.len(), new.data.len())) {
new.data[i] = self.data[i]
}
return new;
}
}

1
lab2/src/algo/mod.rs Normal file
View File

@ -0,0 +1 @@
mod bit_vector;

4
lab2/src/main.rs Normal file
View File

@ -0,0 +1,4 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] // hide console window on Windows in release
mod algo;
fn main() {}