haar_lib/ds/
partially_persistent_array.rs1#[derive(Clone, Debug)]
5pub struct PartiallyPersistentArray<T> {
6 time: usize,
7 data: Vec<Vec<(usize, T)>>,
8}
9
10impl<T: Clone> PartiallyPersistentArray<T> {
11 pub fn new(value: T, n: usize) -> Self {
13 Self {
14 time: 0,
15 data: vec![vec![(0, value)]; n],
16 }
17 }
18
19 pub fn latest(&self) -> usize {
21 self.time
22 }
23
24 pub fn set(&mut self, index: usize, value: T) {
26 self.time += 1;
27 self.data[index].push((self.time, value));
28 }
29
30 pub fn get(&self, index: usize, time: usize) -> &T {
32 match self.data[index].binary_search_by_key(&time, |a| a.0) {
33 Ok(i) => &self.data[index][i].1,
34 Err(i) => &self.data[index][i - 1].1,
35 }
36 }
37
38 pub fn iter_at(&self, time: usize) -> impl Iterator<Item = &T> {
40 self.data
41 .iter()
42 .map(move |a| match a.binary_search_by_key(&time, |a| a.0) {
43 Ok(i) => &a[i].1,
44 Err(i) => &a[i - 1].1,
45 })
46 }
47}
48
49#[cfg(test)]
50mod tests {
51 use crate::iter::collect::CollectVec;
52
53 use super::*;
54 use rand::Rng;
55
56 #[test]
57 fn test() {
58 let mut rng = rand::thread_rng();
59
60 let n = 10;
61 let t = 100;
62 let mut a = PartiallyPersistentArray::new(0, n);
63 let mut b = vec![0; n];
64
65 let mut history = vec![b.clone()];
66
67 for _ in 0..t {
68 let i = rng.gen_range(0..n);
69 let x = rng.gen::<u32>();
70
71 b[i] = x;
72 a.set(i, x);
73
74 history.push(b.clone());
75 }
76
77 for time in 0..=t {
78 assert_eq!(history[time], a.iter_at(time).cloned().collect_vec());
79 }
80 }
81}