Complete the code to iterate over all subsets using bitmask.
for mask in 0..[1] { println!("Mask: {}", mask); }
We use 1 << n to get 2 to the power n, which is the total number of subsets.
Complete the code to check if the j-th element is in the current subset mask.
if mask & (1 << [1]) != 0 { println!("Element {} is in subset", j); }
We check the bit at position j by shifting 1 left by j.
Fix the error in the code to collect elements of the subset correctly.
let mut subset = Vec::new(); for j in 0..n { if mask & (1 << j) != 0 { subset.push([1][j]); } }
We push the element at index j from the original elements array.
Fill both blanks to generate all subsets and print them.
for mask in 0..[1] { let mut subset = Vec::new(); for j in 0..[2] { if mask & (1 << j) != 0 { subset.push(elements[j]); } } println!("{:?}", subset); }
The outer loop runs from 0 to 2^n (1 << n). The inner loop runs from 0 to n.
Fill all three blanks to create a function that returns all subsets of a vector.
fn subsets(elements: Vec<i32>) -> Vec<Vec<i32>> {
let n = elements.len();
let mut result = Vec::new();
for mask in 0..[1] {
let mut subset = Vec::new();
for j in 0..[2] {
if mask & (1 << j) != 0 {
subset.push([3][j]);
}
}
result.push(subset);
}
result
}The function uses 2^n subsets, loops over n elements, and accesses elements by index.
