use arboriter::{for_tree, prune};
fn main() {
println!("String Generation Examples");
println!("========================");
println!("\n1. Generate Strings of 'a' and 'b'");
println!("-------------------------------");
generate_strings("ab");
println!("\n2. Generate Balanced Parentheses");
println!("------------------------------");
generate_balanced_parens(3);
println!("\n3. Generate Binary Numbers");
println!("------------------------");
generate_binary_numbers(4); }
fn generate_strings(alphabet: &str) {
println!("Generating strings using alphabet '{}' with length <= 3:", alphabet);
let mut strings = Vec::new();
for_tree!(s in String::new(); |s| s.len() <= 3; |s| {
let mut branches: Vec<String> = Vec::new();
for c in alphabet.chars() {
branches.push(format!("{}{}", s, c));
}
branches
} => {
println!("Generated: \"{}\"", s);
strings.push(s.clone());
if s.len() == 3 {
prune!(); }
});
println!("Total strings generated: {}", strings.len());
}
fn generate_balanced_parens(n: usize) {
println!("Generating balanced parentheses with at most {} pairs:", n);
for_tree!(state in ("".to_string(), 0, 0); |state| state.1 <= n; |state| {
let (s, open, close) = state.clone(); let mut branches = Vec::new();
if open < n {
branches.push((format!("{}(", s), open + 1, close));
}
if close < open {
branches.push((format!("{})", s), open, close + 1));
}
branches
} => {
let (s, open, close) = state.clone();
if open == close && open > 0 {
println!("Generated: {}", s);
}
});
}
fn generate_binary_numbers(max_bits: usize) {
println!("Generating binary numbers up to {} bits:", max_bits);
for_tree!(num in "".to_string(); |num| num.len() <= max_bits; |num| {
let mut branches = Vec::new();
branches.push(format!("{}0", num));
branches.push(format!("{}1", num));
branches
} => {
if !num.is_empty() {
if let Ok(value) = u32::from_str_radix(&num, 2) {
println!("Binary: {}, Decimal: {}", num, value);
}
}
if num.len() == max_bits {
prune!(); }
});
}