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: String = s.chars()
.filter(|c| c.is_ascii_alphanumeric())
.map(|c| c.to_ascii_lowercase())
.collect();
filtered == filtered.chars().rev().collect::<String>()
}
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: String = s.chars()
.filter(|c| c.is_ascii_alphabetic() || c.is_ascii_digit())
.map(|c| c.to_ascii_lowercase())
.collect();
filtered == filtered.chars().rev().collect::<String>()
}
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 processed: String = s.chars()
.filter(|c| c.is_ascii_alphanumeric())
.map(|c| c.to_ascii_lowercase())
.collect();
processed == processed.chars().rev().collect::<String>()
}
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;
fn word_count(text: &str) -> HashMap<String, usize> {
let mut counts = HashMap::new();
for word in text.split_whitespace() {
let lower_word = word.to_lowercase();
*counts.entry(lower_word).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.
fn longest(a: &str, b: &str) -> &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.
fn longest(s1: &str, s2: &str) -> &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 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.
fn longest(a: &str, b: &str) -> &str {
if a.len() > b.len() {
a
} else if b.len() > a.len() {
b
} else {
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.
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 idx = s.find(sep)?;
let (left, right) = s.split_at(idx);
let left = left.trim();
let right = right.get(1..).unwrap_or_default().trim();
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 split = s.split_once(sep)?;
let (left, right) = split;
Some((T::from_str(left)?, T::from_str(right)?))
}
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 idx = s.find(sep)?;
let (left, right) = s.split_at(idx);
let left = left.trim();
let right = right.get(1..).unwrap_or_default().trim();
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 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.
fn compose<F, G, A, B, C>(f: F, g: G) -> impl Fn(A) -> C + 'static
where
F: Fn(A) -> B + 'static,
G: Fn(B) -> C + 'static,
{
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.
fn compose<F, G, A, B, C>(f: F, g: G) -> Box<dyn Fn(A) -> C + 'static>
where
F: Fn(A) -> B + 'static,
G: Fn(B) -> C + 'static,
{
Box::new(move |x| 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.
fn compose<A, B, C, F, G>(f: F, g: G) -> impl Fn(A) -> C
where
F: Fn(A) -> B,
G: Fn(B) -> C,
{
move |x| 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.
struct Fib {
a: u64,
b: u64,
done: bool,
}
impl Fib {
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 current = self.a;
let new_a = self.b;
let new_b = self.a.checked_add(self.b);
if let Some(new_b) = new_b {
self.a = new_a;
self.b = new_b;
} else {
self.done = true;
}
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.
struct Fib {
current: u64,
next: u64,
done: bool,
}
impl Fib {
fn new() -> Self {
Fib {
current: 0,
next: 1,
done: false,
}
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
let current = self.current;
let next_sum = self.current.checked_add(self.next);
if next_sum.is_none() {
self.done = true;
return Some(current);
}
self.current = self.next;
self.next = next_sum.unwrap();
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.
struct Fib {
a: u64,
b: u64,
}
impl Fib {
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 new_a = self.b;
let new_b = self.a.checked_add(self.b)?;
self.a = new_a;
self.b = new_b;
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 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::num::ParseFloatError;
use std::fmt::Display;
use std::error::Error;
#[derive(Debug)]
enum TempError {
Empty,
BadUnit(char),
BadNumber(ParseFloatError),
}
impl Display for TempError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TempError::Empty => write!(f, "Empty"),
TempError::BadUnit(c) => write!(f, "Bad unit: {}", c),
TempError::BadNumber(e) => write!(f, "Bad number: {}", e),
}
}
}
impl Error for TempError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
TempError::BadNumber(e) => Some(e),
_ => None,
}
}
}
impl From<ParseFloatError> for TempError {
fn from(e: ParseFloatError) -> Self {
TempError::BadNumber(e)
}
}
pub fn parse_temp(s: &str) -> Result<f64, TempError> {
if s.is_empty() {
return Err(TempError::Empty);
}
let unit_char = s.chars().last().unwrap();
if unit_char != 'C' && unit_char != 'F' {
return Err(TempError::BadUnit(unit_char));
}
let num_str = &s[0..s.len() - 1];
let num = num_str.parse::<f64>().map_err(TempError::BadNumber)?;
let celsius = if unit_char == 'F' {
(num - 32.0) * 5.0 / 9.0
} else {
num
};
Ok(celsius)
}
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.
#[derive(Debug)]
enum TempError {
Empty,
BadUnit(char),
BadNumber(std::num::ParseFloatError),
}
impl std::fmt::Display for TempError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TempError::Empty => write!(f, "empty string"),
TempError::BadUnit(c) => write!(f, "bad unit character: {}", c),
TempError::BadNumber(e) => write!(f, "bad number: {}", e),
}
}
}
impl std::error::Error for TempError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
TempError::BadNumber(e) => Some(e),
_ => None,
}
}
}
impl From<std::num::ParseFloatError> for TempError {
fn from(e: std::num::ParseFloatError) -> Self {
TempError::BadNumber(e)
}
}
fn parse_temp(s: &str) -> Result<f64, TempError> {
if s.is_empty() {
return Err(TempError::Empty);
}
let unit_char = s.chars().last().unwrap();
if unit_char != 'C' && unit_char != 'F' {
return Err(TempError::BadUnit(unit_char));
}
let num_str = &s[0..s.len() - 1];
let num = num_str.parse::<f64>().map_err(TempError::BadNumber)?;
let celsius = if unit_char == 'F' {
(num - 32.0) * 5.0 / 9.0
} else {
num
};
Ok(celsius)
}
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::fmt;
use std::error;
use std::num::ParseFloatError;
#[derive(Debug)]
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 string"),
TempError::BadUnit(c) => write!(f, "Invalid unit: {}", c),
TempError::BadNumber(e) => write!(f, "Invalid number: {}", e),
}
}
}
impl error::Error for TempError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
TempError::BadNumber(e) => Some(e),
_ => None,
}
}
}
impl From<ParseFloatError> for TempError {
fn from(e: ParseFloatError) -> Self {
TempError::BadNumber(e)
}
}
fn parse_temp(s: &str) -> Result<f64, TempError> {
if s.is_empty() {
return Err(TempError::Empty);
}
let unit_char = s.chars().last().unwrap();
if unit_char != 'C' && unit_char != 'F' {
return Err(TempError::BadUnit(unit_char));
}
let number_str = &s[0..s.len() - 1];
let temp = number_str.parse::<f64>().map_err(TempError::BadNumber)?;
let celsius = if unit_char == 'F' {
(temp - 32.0) * 5.0 / 9.0
} else {
temp
};
Ok(celsius)
}
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.
use std::thread;
use std::sync::Arc;
fn parallel_sum(data: &[u64], workers: usize) -> u64 {
if workers == 0 {
panic!("workers is 0");
}
if data.is_empty() {
return 0;
}
let len = data.len();
let chunk_size = (len + workers - 1) / workers;
let vec_data = data.to_vec();
let arc_data = Arc::new(vec_data);
let mut handles = vec![];
for i in 0..workers {
let start = i * chunk_size;
let end = (i + 1) * chunk_size;
let end = end.min(len);
let arc_data = Arc::clone(&arc_data);
let handle = thread::spawn(move || {
let slice = &arc_data[start..end];
slice.iter().copied().sum::<u64>()
});
handles.push(handle);
}
handles.into_iter().map(|h| h.join().unwrap()).sum()
}
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 greater than 0");
}
if data.is_empty() {
return 0;
}
let len = data.len();
let chunk_size = (len + workers - 1) / workers;
let mut handles = Vec::with_capacity(workers);
for i in 0..workers {
let start = i * chunk_size;
let end = std::cmp::min((i + 1) * chunk_size, len);
let chunk = &data[start..end];
let handle = std::thread::spawn(move || chunk.iter().sum::<u64>());
handles.push(handle);
}
handles.into_iter().map(|h| h.join().unwrap()).sum()
}
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.
use std::thread;
pub fn parallel_sum(data: &[u64], workers: usize) -> u64 {
if workers == 0 {
panic!("workers is 0");
}
if data.is_empty() {
return 0;
}
let chunk_size = (data.len() + workers - 1) / workers;
let mut handles = vec![];
for i in 0..workers {
let start = i * chunk_size;
let end = (i + 1) * chunk_size;
let end = end.min(data.len());
let chunk = &data[start..end];
let handle = thread::spawn(move || chunk.iter().sum::<u64>());
handles.push(handle);
}
let mut total = 0;
for handle in handles {
total += handle.join().unwrap();
}
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.
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.
pub trait PairsExt: Iterator {
fn pairs(self) -> impl Iterator<Item = (Self::Item, Self::Item)>
where
Self::Item: Clone;
}
impl<T, I> PairsExt for I
where
I: Iterator<Item = T>,
T: Clone,
{
fn pairs(self) -> impl Iterator<Item = (T, T)> {
self.scan(None, move |state, item| {
if let Some(prev) = state.take() {
let output = (prev.clone(), item.clone());
*state = Some(item.clone());
Some(output)
} else {
*state = Some(item.clone());
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.
use std::iter::Iterator;
pub trait PairsExt: Iterator<Item: Clone> {
fn pairs(self) -> impl Iterator<Item = (Self::Item, Self::Item)> {
self.scan(None, move |state: &mut Option<Self::Item>, item| {
let prev = state.take();
if let Some(prev) = prev {
*state = Some(item.clone());
Some((prev, item))
} else {
*state = Some(item.clone());
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.
pub trait PairsExt: Iterator where Self::Item: Clone {
fn pairs(self) -> impl Iterator<Item = (Self::Item, Self::Item)>;
}
struct Pairs<I> {
iter: I,
prev: Option<<I as Iterator>::Item>,
}
impl<I> Iterator for Pairs<I>
where
I: Iterator,
I::Item: Clone,
{
type Item = (I::Item, I::Item);
fn next(&mut self) -> Option<Self::Item> {
let current = self.iter.next()?;
match self.prev {
None => {
self.prev = Some(current.clone());
None
}
Some(prev) => {
let result = (prev, current);
self.prev = Some(current.clone());
Some(result)
}
}
}
}
impl<I> PairsExt for I
where
I: Iterator,
I::Item: Clone,
{
fn pairs(self) -> Pairs<Self> {
Pairs { iter: self, prev: 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 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, RefCell, Weak};
struct TreeNode {
value: i32,
parent: RefCell<Weak<TreeNode>>,
children: RefCell<Vec<Rc<TreeNode>>>,
}
impl TreeNode {
pub fn new(value: i32) -> Rc<Self> {
Rc::new(TreeNode {
value,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![]),
})
}
pub fn add_child(parent: &Rc<Self>, child: Rc<Self>) {
let mut children = parent.children.borrow_mut();
children.push(child.clone());
*child.parent.borrow_mut() = Rc::downgrade(parent);
}
pub fn sum(&self) -> i32 {
let mut total = self.value;
for child in self.children.borrow().iter() {
total += child.sum();
}
total
}
pub fn depth(&self) -> usize {
if let Some(parent) = self.parent.borrow().upgrade() {
parent.depth() + 1
} else {
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.
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<Self> {
Rc::new(TreeNode {
value,
parent: RefCell::new(Weak::new()),
children: RefCell::new(Vec::new()),
})
}
pub fn add_child(parent: &Rc<Self>, child: Rc<Self>) {
parent.children.borrow_mut().push(child.clone());
*child.parent.borrow_mut() = Rc::downgrade(parent);
}
pub fn sum(&self) -> i32 {
let mut total = self.value;
for child in self.children.borrow().iter() {
total += child.sum();
}
total
}
pub fn depth(&self) -> usize {
if let Some(parent) = self.parent.borrow().upgrade() {
1 + parent.depth()
} else {
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.
use std::rc::{Rc, Weak};
use std::cell::RefCell;
struct TreeNode {
value: i32,
parent: RefCell<Weak<TreeNode>>,
children: RefCell<Vec<Rc<TreeNode>>>,
}
impl TreeNode {
fn new(value: i32) -> Rc<TreeNode> {
Rc::new(TreeNode {
value,
parent: RefCell::new(Weak::new()),
children: RefCell::new(Vec::new()),
})
}
fn add_child(parent: &Rc<TreeNode>, child: Rc<TreeNode>) {
parent.children.borrow_mut().push(child.clone());
*child.parent.borrow_mut() = Rc::downgrade(parent);
}
fn sum(&self) -> i32 {
let mut total = self.value;
for child in self.children.borrow().iter() {
total += child.sum();
}
total
}
fn depth(&self) -> usize {
if let Some(parent) = self.parent.borrow().upgrade() {
1 + parent.depth()
} else {
0
}
}
}