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 mut chars: Vec<char> = s.chars()
.filter(|c| c.is_ascii_alphanumeric())
.map(|c| c.to_ascii_lowercase())
.collect();
chars.windows(2).all(|w| w[0] == w[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.
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 mut chars: Vec<char> = s.chars().filter(|c| c.is_ascii_alphanumeric()).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.
fn is_palindrome(s: &str) -> bool {
let mut left = s.chars().filter(|c| c.is_ascii_alphanumeric()).peekable();
let mut right = s.chars().filter(|c| c.is_ascii_alphanumeric()).rev().peekable();
left.next().map(|_| right.next().map(|c| c == left.next().unwrap())).unwrap_or(true)
.unwrap_or(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 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();
let mut words = text.split_whitespace();
while let Some(word) = words.next() {
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 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 map = HashMap::new();
for word in text.split_whitespace() {
let lower = word.to_lowercase();
*map.entry(lower).or_insert(0) += 1;
}
map
}
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.
pub fn longest(a: &str, b: &str) -> &'static 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: &str, b: &str) -> &'static 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 {
s1.len().cmp(&s2.len()).then(some(s1)).unwrap_or(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)>
where
T::Err: std::fmt::Debug,
{
let (left, right) = s.split_once(sep)?;
Some((left.parse()?, right.parse()?))
}
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)>
where
T::Err: std::fmt::Debug,
{
let (left, right) = s.split_once(sep)?;
Some((left.parse::<T>()?, right.parse::<T>()?))
}
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)>
where
T::Err: std::fmt::Debug,
{
let (left, right) = s.split_once(sep)?;
let left = T::from_str(left)?;
let right = T::from_str(right)?;
Some((left, 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 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, T, U>(f: F, g: G) -> impl Fn(T) -> U
where
F: Fn(T) -> T,
G: Fn(T) -> U,
{
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.
pub fn compose<F, G, T, U, V>(f: F, g: G) -> impl Fn(T) -> V
where
F: Fn(T) -> U + Copy,
G: Fn(U) -> V + Copy,
{
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.
pub fn compose<F, G, T, U>(f: F, g: G) -> impl Fn(T) -> U
where
F: Fn(T) -> T,
G: Fn(T) -> U,
{
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.
use std::iter::Iterator;
pub struct Fib {
current: u64,
next: u64,
overflowed: bool,
}
impl Fib {
pub fn new() -> Self {
Fib { current: 0, next: 1, overflowed: false }
}
}
impl Iterator for Fib {
type Item = Option<u64>;
fn next(&mut self) -> Option<Self::Item> {
if self.overflowed {
return None;
}
let result = Some(self.current);
self.current = self.next;
self.next += self.current;
if self.next > u64::MAX {
self.overflowed = true;
}
result
}
}
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.
use std::iter::Iterator;
pub struct Fib {
a: u64,
b: u64,
overflow: bool,
}
impl Fib {
pub fn new() -> Self {
Self {
a: 0,
b: 1,
overflow: false,
}
}
}
impl Iterator for Fib {
type Item = Option<u64>;
fn next(&mut self) -> Self::Item {
if self.overflow {
return None;
}
let next = self.a;
self.a = self.b;
self.b = next.checked_add(self.b).unwrap_or_else(|| {
self.overflow = true;
self.b
});
Some(next)
}
}
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.
use std::iter::Iterator;
pub struct Fib {
a: u64,
b: u64,
overflowed: bool,
}
impl Fib {
pub fn new() -> Self {
Self { a: 0, b: 1, overflowed: false }
}
}
impl Iterator for Fib {
type Item = Option<u64>;
fn next(&mut self) -> Option<Self::Item> {
if self.overflowed {
return None;
}
let next = self.a;
self.a = self.b;
self.b = next.checked_add(self.b)?;
if self.b.is_none() {
self.overflowed = true;
}
Some(next)
}
}
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)]
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 input"),
TempError::BadUnit(c) => write!(f, "invalid temperature unit: '{}'", c),
TempError::BadNumber(e) => write!(f, "invalid temperature number: {}", e),
}
}
}
impl Error for TempError {}
impl From<ParseFloatError> for TempError {
fn from(err: ParseFloatError) -> Self {
TempError::BadNumber(err)
}
}
fn parse_temp(s: &str) -> Result<f64, TempError> {
if s.is_empty() {
return Err(TempError::Empty);
}
let num_str = &s[..s.len() - 1];
let unit = s.chars().last().unwrap();
if unit != 'C' && unit != 'F' {
return Err(TempError::BadUnit(unit));
}
let temp: f64 = num_str.parse().map_err(TempError::from)?;
let celsius = if unit == '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.
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)]
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 input"),
TempError::BadUnit(c) => write!(f, "invalid unit: '{}'", c),
TempError::BadNumber(e) => write!(f, "failed to parse number: {}", e),
}
}
}
impl Error for TempError {}
impl From<ParseFloatError> for TempError {
fn from(err: ParseFloatError) -> Self {
TempError::BadNumber(err)
}
}
fn parse_temp(s: &str) -> Result<f64, TempError> {
if s.is_empty() {
return Err(TempError::Empty);
}
let num_str = &s[..s.len() - 1];
let unit = s.chars().last().ok_or(TempError::BadUnit('?'))?;
let num = num_str.parse::<f64>()?;
if unit != 'C' && unit != 'F' {
return Err(TempError::BadUnit(unit));
}
let temp = if unit == 'F' {
(num - 32.0) * 5.0 / 9.0
} else {
num
};
Ok(temp)
}
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)]
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 input"),
TempError::BadUnit(c) => write!(f, "invalid unit: '{}'", c),
TempError::BadNumber(e) => write!(f, "invalid 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(err: ParseFloatError) -> Self {
TempError::BadNumber(err)
}
}
fn parse_temp(s: &str) -> Result<f64, TempError> {
if s.is_empty() {
return Err(TempError::Empty);
}
let unit = s.chars().last().ok_or(TempError::BadUnit('?'))?;
let num_str = s[..s.len() - 1].trim().ok_or(TempError::Empty)?;
let num = num_str.parse::<f64>()?;
let temp = if unit == 'C' {
num
} else if unit == 'F' {
(num - 32.0) * 5.0 / 9.0
} else {
return Err(TempError::BadUnit(unit));
};
Ok(temp)
}
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::sync::mpsc;
use std::thread;
fn parallel_sum(data: &[u64], workers: usize) -> u64 {
if workers == 0 {
panic!("workers must be greater than zero");
}
let chunk_size = (data.len() + workers - 1) / workers;
let mut handles = Vec::with_capacity(workers);
for i in 0..workers {
let start = i * chunk_size;
let end = if i == workers - 1 {
data.len()
} else {
(i + 1) * chunk_size
};
let chunk = &data[start..end];
let (tx, rx) = mpsc::channel();
let sum = chunk.iter().sum::<u64>();
handles.push(thread::spawn(move || tx.send(sum)));
}
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.
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::sync::mpsc;
use std::thread;
fn parallel_sum(data: &[u64], workers: usize) -> u64 {
if workers == 0 {
panic!("workers must be greater than zero");
}
let len = data.len();
if len == 0 {
return 0;
}
let chunk_size = (len + workers - 1) / workers;
let mut handles = Vec::with_capacity(workers);
let (tx, rx) = mpsc::channel();
for i in 0..workers {
let start = i * chunk_size;
let end = std::cmp::min(start + chunk_size, len);
let chunk = &data[start..end];
let tx = tx.clone();
handles.push(thread::spawn(move || {
let mut sum = 0u64;
for &num in chunk {
sum += num;
}
tx.send(sum).unwrap();
}));
}
let mut total = 0u64;
for _ in 0..workers {
total += rx.recv().unwrap();
}
for handle in handles {
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.
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::sync::mpsc;
use std::thread;
fn parallel_sum(data: &[u64], workers: usize) -> u64 {
if workers == 0 {
panic!("workers cannot be zero");
}
let mut handles = Vec::with_capacity(workers);
let (sender, receiver) = mpsc::channel();
let chunk_size = (data.len() + workers - 1) / workers;
for i in 0..workers {
let chunk_start = i * chunk_size;
let chunk_end = std::cmp::min(chunk_start + chunk_size, data.len());
let chunk = &data[chunk_start..chunk_end];
let sender_clone = sender.clone();
handles.push(thread::spawn(move || {
let mut partial_sum = 0;
for &num in chunk {
partial_sum += num;
}
sender_clone.send(partial_sum).unwrap();
}));
}
let mut total = 0;
for _ in 0..workers {
total += receiver.recv().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.
trait PairsExt {
fn pairs(self) -> PairsSelf;
}
impl<T: Clone + Iterator<Item = T>> PairsExt for T {
fn pairs(self) -> PairsSelf {
PairsSelf::new(self)
}
}
struct PairsSelf<'a, T: 'a> {
inner: std::iter::Peekable<std::iter::TakeWhile<'a, std::iter::ExactSizeKnownSize<T>, T>>,
}
impl<'a, T: Clone + Iterator<Item = T>> Iterator for PairsSelf<'a, T> {
type Item = (T, T);
fn next(&mut self) -> Option<Self::Item> {
let first = self.inner.next()?;
let second = self.inner.peek()?.clone();
self.inner.next();
Some((first, second))
}
}
impl<'a, T: Iterator<Item = T>> PairsSelf<'a, T> {
fn new(mut inner: std::iter::Peekable<std::iter::TakeWhile<'a, std::iter::ExactSizeKnownSize<T>, T>>) -> Self {
Self { inner }
}
}
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, Peekable};
trait PairsExt: Iterator<Item = impl Clone> {
fn pairs(self) -> Pairs;
}
struct Pairs<I: Iterator<Item = I::Item + Clone>> {
iter: Peekable<I>,
}
impl<I: Iterator<Item = I::Item + Clone>> Iterator for Pairs<I> {
type Item = (I::Item, I::Item);
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().zip(self.iter.next())
}
}
impl<I: Iterator<Item = I::Item + Clone>> PairsExt for I {}
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.
trait PairsExt<I: Iterator<Item = I::Item>> {
fn pairs(self) -> Pairs<I>;
}
impl<I: Iterator<Item = I::Item> + Clone> PairsExt<I> for I {
fn pairs(self) -> Pairs<I> {
Pairs(self)
}
}
struct Pairs<I>(I);
impl<I: Iterator<Item = I::Item>> Iterator for Pairs<I> {
type Item = (I::Item, I::Item);
fn next(&mut self) -> Option<Self::Item> {
let mut current = self.0.next()?;
let next = self.0.next()?;
Some((current, next))
}
}
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};
#[derive(Debug)]
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>) {
let mut parent_children = parent.children.borrow_mut();
parent_children.push(child.clone());
child.parent.borrow_mut().replace(Rc::downgrade(parent));
}
fn sum(&self) -> i32 {
let mut total = self.value;
let children = self.children.borrow();
for child in &children {
total += child.sum();
}
total
}
fn depth(&self) -> usize {
let parent = self.parent.borrow().upgrade();
match parent {
Some(parent) => 1 + parent.depth(),
None => 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};
#[derive(Debug)]
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>) {
let mut parent_children = parent.children.borrow_mut();
parent_children.push(child.clone());
let mut parent_parent = parent.parent.borrow_mut();
*parent_parent = Rc::downgrade(&child);
}
fn sum(&self) -> i32 {
let mut total = self.value;
let children = self.children.borrow();
for child in children.iter() {
total += child.sum();
}
total
}
fn depth(&self) -> usize {
let parent = self.parent.borrow().upgrade();
match parent {
Some(parent) => 1 + parent.depth(),
None => 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};
#[derive(Debug)]
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>) {
let mut children = parent.children.borrow_mut();
children.push(child.clone());
child.parent.borrow_mut().replace(Rc::downgrade(parent));
}
fn sum(&self) -> i32 {
let mut total = self.value;
let children = self.children.borrow();
for child in children.iter() {
total += child.sum();
}
total
}
fn depth(&self) -> usize {
let parent = self.parent.borrow().upgrade();
match parent {
Some(parent) => 1 + parent.depth(),
None => 0,
}
}
}