Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write is_palindrome(s: &str) -> bool. Consider only ASCII letters and digits, ignoring ASCII case and every other character. A string with none of those characters is a palindrome.
pub fn is_palindrome(s: &str) -> bool {
let chars: Vec<char> = s
.chars()
.filter(|c| c.is_ascii_alphanumeric())
.map(|c| c.to_ascii_lowercase())
.collect();
chars.iter().eq(chars.iter().rev())
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write is_palindrome(s: &str) -> bool. Consider only ASCII letters and digits, ignoring ASCII case and every other character. A string with none of those characters is a palindrome.
pub fn is_palindrome(s: &str) -> bool {
let filtered: Vec<char> = s
.chars()
.filter(|c| c.is_ascii_alphanumeric())
.map(|c| c.to_ascii_lowercase())
.collect();
let len = filtered.len();
for i in 0..len / 2 {
if filtered[i] != filtered[len - 1 - i] {
return false;
}
}
true
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write is_palindrome(s: &str) -> bool. Consider only ASCII letters and digits, ignoring ASCII case and every other character. A string with none of those characters is a palindrome.
fn is_palindrome(s: &str) -> bool {
let filtered: Vec<char> = s
.chars()
.filter(|c| c.is_ascii_alphanumeric())
.map(|c| c.to_ascii_lowercase())
.collect();
filtered == filtered.iter().rev().collect::<Vec<char>>()
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write word_count(text: &str) -> HashMap<String, usize>, importing HashMap yourself. Words are separated by any whitespace and compared in lowercase, and the map's keys are lowercase. Punctuation is part of a word.
use std::collections::HashMap;
pub fn word_count(text: &str) -> HashMap<String, usize> {
let mut counts = HashMap::new();
for word in text.split_whitespace() {
let lower = word.to_lowercase();
*counts.entry(lower).or_insert(0) += 1;
}
counts
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write word_count(text: &str) -> HashMap<String, usize>, importing HashMap yourself. Words are separated by any whitespace and compared in lowercase, and the map's keys are lowercase. Punctuation is part of a word.
use std::collections::HashMap;
pub fn word_count(text: &str) -> HashMap<String, usize> {
let mut counts = HashMap::new();
for word in text.split_whitespace() {
let lower = word.to_lowercase();
*counts.entry(lower).or_insert(0) += 1;
}
counts
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write word_count(text: &str) -> HashMap<String, usize>, importing HashMap yourself. Words are separated by any whitespace and compared in lowercase, and the map's keys are lowercase. Punctuation is part of a word.
use std::collections::HashMap;
pub fn word_count(text: &str) -> HashMap<String, usize> {
let mut counts = HashMap::new();
for word in text.split_whitespace() {
let lower = word.to_lowercase();
*counts.entry(lower).or_insert(0) += 1;
}
counts
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write longest, which takes two string slices and returns the longer one by str::len without allocating. On a tie, it returns the first. Its result must be usable as long as both inputs are alive.
pub fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() {
a
} else {
b
}
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write longest, which takes two string slices and returns the longer one by str::len without allocating. On a tie, it returns the first. Its result must be usable as long as both inputs are alive.
pub fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() {
a
} else {
b
}
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write longest, which takes two string slices and returns the longer one by str::len without allocating. On a tie, it returns the first. Its result must be usable as long as both inputs are alive.
pub fn longest<'a>(s1: &'a str, s2: &'a str) -> &'a str {
if s1.len() >= s2.len() {
s1
} else {
s2
}
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write parse_pair<T: FromStr>(s: &str, sep: char) -> Option<(T, T)>, importing FromStr yourself. Split s at the first occurrence of sep and parse both sides as T. Return None if sep does not occur or if either side fails to parse. sep may be any Unicode character. parse_pair::<u32>("400x600", 'x') returns Some((400, 600)).
use std::str::FromStr;
pub fn parse_pair<T: FromStr>(s: &str, sep: char) -> Option<(T, T)> {
s.split_once(sep)
.and_then(|(left, right)| {
T::from_str(left)
.ok()
.and_then(|l| T::from_str(right).ok().map(|r| (l, r)))
})
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write parse_pair<T: FromStr>(s: &str, sep: char) -> Option<(T, T)>, importing FromStr yourself. Split s at the first occurrence of sep and parse both sides as T. Return None if sep does not occur or if either side fails to parse. sep may be any Unicode character. parse_pair::<u32>("400x600", 'x') returns Some((400, 600)).
use std::str::FromStr;
fn parse_pair<T: FromStr>(s: &str, sep: char) -> Option<(T, T)> {
let mut parts = s.splitn(2, sep);
let left = parts.next()?;
let right = parts.next()?;
let left_val = T::from_str(left)?;
let right_val = T::from_str(right)?;
Some((left_val, right_val))
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write parse_pair<T: FromStr>(s: &str, sep: char) -> Option<(T, T)>, importing FromStr yourself. Split s at the first occurrence of sep and parse both sides as T. Return None if sep does not occur or if either side fails to parse. sep may be any Unicode character. parse_pair::<u32>("400x600", 'x') returns Some((400, 600)).
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write compose(f, g), generic over the argument and result types. f and g are closures implementing Fn. It returns a closure implementing Fn that maps x to g(f(x)), and the returned closure must be usable after the function that called compose has returned.
pub fn compose<F, G, A, B, C>(f: F, g: G) -> Box<dyn Fn(A) -> C>
where
F: Fn(A) -> B + 'static,
G: Fn(B) -> C + 'static,
{
Box::new(move |x: A| g(f(x)))
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write compose(f, g), generic over the argument and result types. f and g are closures implementing Fn. It returns a closure implementing Fn that maps x to g(f(x)), and the returned closure must be usable after the function that called compose has returned.
pub fn compose<F, G, A, B, C>(f: F, g: G) -> impl Fn(A) -> C + 'static
where
F: Fn(A) -> B,
G: Fn(B) -> C,
{
Box::new(move |x: A| g(f(x)))
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write compose(f, g), generic over the argument and result types. f and g are closures implementing Fn. It returns a closure implementing Fn that maps x to g(f(x)), and the returned closure must be usable after the function that called compose has returned.
pub fn compose<F, G, A, B>(f: F, g: G) -> impl Fn(A) -> B + 'static
where
F: Fn(A) -> B,
G: Fn(B) -> A,
{
move |x: A| g(f(x))
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define Fib, with a constructor Fib::new(), and implement Iterator<Item = u64> for it. It yields the Fibonacci numbers 0, 1, 1, 2, 3, 5, and so on. It yields every Fibonacci number that fits in a u64, then None from then on. Tests run with overflow checks on.
pub struct Fib {
a: u64,
b: u64,
exhausted: bool,
}
impl Fib {
pub fn new() -> Self {
Fib {
a: 0,
b: 1,
exhausted: false,
}
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
if self.exhausted {
return None;
}
let current = self.a;
self.a = self.b;
// Check if next Fibonacci number (self.a + self.b) would overflow
if let Some(next_b) = self.a.checked_add(self.b) {
self.b = next_b;
Some(current)
} else {
// Overflow detected, stop yielding
self.exhausted = true;
None
}
}
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define Fib, with a constructor Fib::new(), and implement Iterator<Item = u64> for it. It yields the Fibonacci numbers 0, 1, 1, 2, 3, 5, and so on. It yields every Fibonacci number that fits in a u64, then None from then on. Tests run with overflow checks on.
pub struct Fib {
a: u64,
b: u64,
}
impl Fib {
pub fn new() -> Self {
Fib { a: 0, b: 1 }
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
let current = self.a;
let next_a = self.a.checked_add(self.b);
if let Some(val) = next_a {
self.a = self.b;
self.b = val;
} else {
// Overflow detected, stop iterator
// This handles the case where the next Fibonacci number doesn't fit
return None;
}
Some(current)
}
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define Fib, with a constructor Fib::new(), and implement Iterator<Item = u64> for it. It yields the Fibonacci numbers 0, 1, 1, 2, 3, 5, and so on. It yields every Fibonacci number that fits in a u64, then None from then on. Tests run with overflow checks on.
pub struct Fib {
a: u64,
b: u64,
done: bool,
}
impl Fib {
pub fn new() -> Self {
Fib { a: 0, b: 1, done: false }
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
let a = self.a;
// Check if a + b would overflow
let (sum, overflow) = a.overflowing_add(self.b);
if overflow {
self.done = true;
return None;
}
// Check if next iteration (b + sum) would overflow
let (next_sum, next_overflow) = self.b.overflowing_add(sum);
if next_overflow {
self.done = true;
return None;
}
self.a = self.b;
self.b = sum;
Some(a)
}
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define enum TempError deriving Debug, with the variants Empty, BadUnit(char), and BadNumber(std::num::ParseFloatError), and write parse_temp(s: &str) -> Result<f64, TempError>. The input is a number followed by one unit character, C or F, and the result is in Celsius, so "212F" returns 100.0. An empty string gives Empty. If the last character is neither C nor F, it gives BadUnit with that character, which may be non-ASCII. A number that does not parse gives BadNumber. Implement Display and std::error::Error for TempError, with source() returning the parse error for BadNumber, and implement From<std::num::ParseFloatError> for it.
use std::error::Error;
use std::fmt;
#[derive(Debug)]
pub enum TempError {
Empty,
BadUnit(char),
BadNumber(std::num::ParseFloatError),
}
impl From<std::num::ParseFloatError> for TempError {
fn from(err: std::num::ParseFloatError) -> Self {
TempError::BadNumber(err)
}
}
impl Error for TempError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
TempError::BadNumber(err) => Some(err),
_ => None,
}
}
}
impl fmt::Display for TempError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TempError::Empty => write!(f, "Empty"),
TempError::BadUnit(unit) => write!(f, "BadUnit({})", unit),
TempError::BadNumber(err) => write!(f, "BadNumber: {}", err),
}
}
}
pub fn parse_temp(s: &str) -> Result<f64, TempError> {
if s.is_empty() {
return Err(TempError::Empty);
}
let unit = s.chars().last().expect("Non-empty string");
if unit == 'C' || unit == 'F' {
let number_str = &s[..s.len() - 1];
match number_str.parse::<f64>() {
Ok(val) => {
let celsius = if unit == 'F' {
(val - 32.0) * 5.0 / 9.0
} else {
val
};
Ok(celsius)
}
Err(e) => Err(TempError::BadNumber(e)),
}
} else {
Err(TempError::BadUnit(unit))
}
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define enum TempError deriving Debug, with the variants Empty, BadUnit(char), and BadNumber(std::num::ParseFloatError), and write parse_temp(s: &str) -> Result<f64, TempError>. The input is a number followed by one unit character, C or F, and the result is in Celsius, so "212F" returns 100.0. An empty string gives Empty. If the last character is neither C nor F, it gives BadUnit with that character, which may be non-ASCII. A number that does not parse gives BadNumber. Implement Display and std::error::Error for TempError, with source() returning the parse error for BadNumber, and implement From<std::num::ParseFloatError> for it.
use std::error::Error;
use std::fmt;
use std::num::ParseFloatError;
#[derive(Debug)]
pub enum TempError {
Empty,
BadUnit(char),
BadNumber(ParseFloatError),
}
impl fmt::Display for TempError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TempError::Empty => write!(f, "Empty"),
TempError::BadUnit(c) => write!(f, "BadUnit({:?})", c),
TempError::BadNumber(e) => write!(f, "BadNumber({})", e),
}
}
}
impl Error for TempError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
if let TempError::BadNumber(e) = self {
Some(e)
} else {
None
}
}
}
impl From<ParseFloatError> for TempError {
fn from(err: ParseFloatError) -> Self {
TempError::BadNumber(err)
}
}
pub fn parse_temp(s: &str) -> Result<f64, TempError> {
if s.is_empty() {
return Err(TempError::Empty);
}
let unit = s.chars().last().ok_or(TempError::Empty)?;
if unit != 'C' && unit != 'F' {
return Err(TempError::BadUnit(unit));
}
let num_str = &s[..s.len() - 1];
match num_str.parse::<f64>() {
Ok(val) => Ok(if unit == 'F' {
(val - 32.0) * 5.0 / 9.0
} else {
val
}),
Err(e) => Err(TempError::BadNumber(e)),
}
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define enum TempError deriving Debug, with the variants Empty, BadUnit(char), and BadNumber(std::num::ParseFloatError), and write parse_temp(s: &str) -> Result<f64, TempError>. The input is a number followed by one unit character, C or F, and the result is in Celsius, so "212F" returns 100.0. An empty string gives Empty. If the last character is neither C nor F, it gives BadUnit with that character, which may be non-ASCII. A number that does not parse gives BadNumber. Implement Display and std::error::Error for TempError, with source() returning the parse error for BadNumber, and implement From<std::num::ParseFloatError> for it.
use std::error::Error;
use std::fmt;
use std::num::ParseFloatError;
#[derive(Debug)]
pub enum TempError {
Empty,
BadUnit(char),
BadNumber(Box<ParseFloatError>),
}
impl From<ParseFloatError> for TempError {
fn from(err: ParseFloatError) -> Self {
TempError::BadNumber(Box::new(err))
}
}
impl fmt::Display for TempError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TempError::Empty => write!(f, "Empty"),
TempError::BadUnit(unit) => write!(f, "Invalid unit: {}", unit),
TempError::BadNumber(e) => write!(f, "{}", e),
}
}
}
impl Error for TempError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
TempError::BadNumber(e) => Some(e.as_ref()),
_ => None,
}
}
}
pub fn parse_temp(s: &str) -> Result<f64, TempError> {
if s.is_empty() {
return Err(TempError::Empty);
}
let unit = s.chars().last().ok_or(TempError::Empty)?;
if unit != 'C' && unit != 'F' {
return Err(TempError::BadUnit(unit));
}
let num_str = &s[..s.len() - unit.len_utf8()];
let value = num_str.parse::<f64>()?;
if unit == 'F' {
Ok((value - 32.0) * 5.0 / 9.0)
} else {
Ok(value)
}
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write parallel_sum(data: &[u64], workers: usize) -> u64, which sums data by splitting it across workers threads from std::thread. data is a borrowed slice, and workers may be larger than data.len(). It returns 0 for an empty slice and panics when workers is 0, including when the slice is empty.
pub fn parallel_sum(data: &[u64], workers: usize) -> u64 {
if workers == 0 {
panic!("workers must be > 0");
}
if data.is_empty() {
return 0;
}
let len = data.len();
let chunk_size = len.saturating_add(workers - 1) / workers;
let mut handles = Vec::with_capacity(workers);
for i in 0..workers {
let start = i.saturating_mul(chunk_size);
let end = start.saturating_add(chunk_size);
let end = end.min(len);
if start >= end {
continue;
}
let slice = &data[start..end];
let handle = std::thread::spawn(move || {
slice.iter().sum()
});
handles.push(handle);
}
let mut total = 0u64;
for handle in handles {
total += handle.join().expect("thread panicked");
}
total
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write parallel_sum(data: &[u64], workers: usize) -> u64, which sums data by splitting it across workers threads from std::thread. data is a borrowed slice, and workers may be larger than data.len(). It returns 0 for an empty slice and panics when workers is 0, including when the slice is empty.
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write parallel_sum(data: &[u64], workers: usize) -> u64, which sums data by splitting it across workers threads from std::thread. data is a borrowed slice, and workers may be larger than data.len(). It returns 0 for an empty slice and panics when workers is 0, including when the slice is empty.
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define an extension trait PairsExt that adds a method .pairs() to every iterator whose items implement Clone. It returns a lazy iterator of consecutive overlapping pairs, so (1..4).pairs() yields (1, 2) then (2, 3). A source with fewer than two items yields nothing, and an infinite source must work.
use std::iter::Peekable;
pub trait PairsExt {
fn pairs(&self) -> PairsIterator<Self>;
}
pub struct PairsIterator<I> {
iter: Peekable<I>,
prev: Option<I::Item>,
}
impl<I> PairsExt for I
where
I: Iterator,
I::Item: Clone,
{
fn pairs(&self) -> PairsIterator<Self> {
PairsIterator {
iter: Peekable::new(self),
prev: None,
}
}
}
impl<I> Iterator for PairsIterator<I>
where
I: Iterator,
I::Item: Clone,
{
type Item = (I::Item, I::Item);
fn next(&mut self) -> Option<Self::Item> {
match self.iter.next() {
Some(curr) => {
if let Some(prev) = self.prev.take() {
self.prev = Some(curr.clone());
Some((prev, curr))
} else {
self.prev = Some(curr.clone());
None
}
}
None => None,
}
}
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define an extension trait PairsExt that adds a method .pairs() to every iterator whose items implement Clone. It returns a lazy iterator of consecutive overlapping pairs, so (1..4).pairs() yields (1, 2) then (2, 3). A source with fewer than two items yields nothing, and an infinite source must work.
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define an extension trait PairsExt that adds a method .pairs() to every iterator whose items implement Clone. It returns a lazy iterator of consecutive overlapping pairs, so (1..4).pairs() yields (1, 2) then (2, 3). A source with fewer than two items yields nothing, and an infinite source must work.
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define TreeNode with exactly these fields: value: i32, parent: RefCell<Weak<TreeNode>>, and children: RefCell<Vec<Rc<TreeNode>>>, importing those types from the standard library. Write TreeNode::new(value: i32) -> Rc<TreeNode>. Write TreeNode::add_child(parent: &Rc<TreeNode>, child: Rc<TreeNode>), which also sets the child's parent. Write sum(&self) -> i32, the total of this node and all its descendants, and depth(&self) -> usize, the number of ancestors, which is 0 for a root.
use std::rc::{Rc, Weak};
use std::cell::RefCell;
use std::vec::Vec;
use std::mem;
pub struct TreeNode {
pub value: i32,
pub parent: RefCell<Weak<TreeNode>>,
pub children: RefCell<Vec<Rc<TreeNode>>>,
}
impl TreeNode {
pub fn new(value: i32) -> Rc<TreeNode> {
Rc::new(TreeNode {
value,
parent: RefCell::new(Weak::new()),
children: RefCell::new(Vec::new()),
})
}
pub fn add_child(parent: &Rc<TreeNode>, child: Rc<TreeNode>) {
parent.children.borrow_mut().push(child.clone());
let _ = mem::replace(&mut child.borrow_mut().parent.borrow_mut(), Weak::downgrade(parent));
}
pub fn sum(&self) -> i32 {
let mut total = self.value;
for child_rc in self.children.borrow() {
total += child_rc.borrow().sum();
}
total
}
pub fn depth(&self) -> usize {
if self.parent.borrow().upgrade().is_none() {
0
} else {
self.parent.borrow().upgrade().unwrap().depth() + 1
}
}
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define TreeNode with exactly these fields: value: i32, parent: RefCell<Weak<TreeNode>>, and children: RefCell<Vec<Rc<TreeNode>>>, importing those types from the standard library. Write TreeNode::new(value: i32) -> Rc<TreeNode>. Write TreeNode::add_child(parent: &Rc<TreeNode>, child: Rc<TreeNode>), which also sets the child's parent. Write sum(&self) -> i32, the total of this node and all its descendants, and depth(&self) -> usize, the number of ancestors, which is 0 for a root.
use std::cell::RefCell;
use std::rc::{Rc, Weak};
struct TreeNode {
value: i32,
parent: RefCell<Weak<TreeNode>>,
children: RefCell<Vec<Rc<TreeNode>>>,
}
impl TreeNode {
pub fn new(value: i32) -> Rc<TreeNode> {
Rc::new(TreeNode {
value,
parent: RefCell::new(Weak::new()),
children: RefCell::new(Vec::new()),
})
}
pub fn add_child(parent: &Rc<TreeNode>, child: Rc<TreeNode>) {
parent.children.borrow_mut().push(child.clone());
*child.parent.borrow_mut() = Rc::downgrade(parent);
}
pub fn sum(&self) -> i32 {
self.value + self.children.borrow().iter().map(|c| c.sum()).sum()
}
pub fn depth(&self) -> usize {
self.parent.borrow().upgrade().map(|p| p.depth() + 1).unwrap_or(0)
}
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define TreeNode with exactly these fields: value: i32, parent: RefCell<Weak<TreeNode>>, and children: RefCell<Vec<Rc<TreeNode>>>, importing those types from the standard library. Write TreeNode::new(value: i32) -> Rc<TreeNode>. Write TreeNode::add_child(parent: &Rc<TreeNode>, child: Rc<TreeNode>), which also sets the child's parent. Write sum(&self) -> i32, the total of this node and all its descendants, and depth(&self) -> usize, the number of ancestors, which is 0 for a root.