Hi Rustaceans, good day! I am a newbie here. Got a question about populating a vector of hashsets where the values to populate in a particular hashset in the vector depends on the values of the hashset in a previous element. If I fail to sound articulate enough, consider the following code:
use std::collections::HashSet;
fn main() {
// create a vector of HashSets
let mut v: Vec<HashSet<isize>> = Vec::new();
for _ in 0..10 {
v.push(HashSet::new());
}
// populate the HashSet in element 0. (0..5 is arbitrary)
for i in 0..5 {
v[0].insert(i);
}
// traverse the list and populate the hash sets in element 1 to 9
// the values to insert are 2 times each of the values in the previous element
// 2 times is arbitrary here, just to show dependencies between elements
for i in 1..10 {
let states = &v[i-1];
for k in states.iter() {
v[i].insert( k*2 ); // cannot borrow `v` as mutable because it is also borrowed as immutable
}
}
}
Think of the vector v as a sequence of nodes and in each of the nodes, there is a set of possible (integer) states that are stored in the HashSet. The initial set of states (i.e. for element 0) is known. Now I need to begin from element 0 and populate the states of all the subsequent elements, according to some algorithm which requires looking at what the states are in the previous element.
The above doesn’t work because an immutable reference is borrowed by the variable “states” once and can’t be borrowed again mutably in v[i].insert(…). Changing “states” to a mutable reference won’t work either obviously because there can only be one mutable reference.
The only way I figured so far, is to clone the HashSet instead of holding on to (or borrowing) a reference to it. like so:
...
let states = v[i-1].clone();
...
I know for sure that when I am trying to update the hashset in node i, I will never need to change anything in the nodes before i.
The question is, is there any other ways to do it which avoids cloning/copying? Or in general, what’s the idiomatic way to populate a “nested” data structure that requires looking at some parts of the data structure when populating other parts? I suppose it doesn’t have to be a vector of hashsets, it would be the same problem with a vector of vectors or a hashmap of vectors, etc etc.
The original problem is to implement a particular algorithm called “forward shooting grid” to price path-dependent financial derivatives. The “forward” here means exactly that the algorithm needs to populate a particular node based on the states of the previous nodes. The above code example is just an attempt to extract the “feature” of the problem.
Thanks for reading and thank you in advance for any pointers/advice which would be very much appreciated!
Cheers,
Albert