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();
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.
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();
filtered.iter().eq(filtered.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 chars: Vec<u8> = s
.bytes()
.filter(|&b| b.is_ascii_alphanumeric())
.map(|b| b.to_ascii_lowercase())
.collect();
let len = chars.len();
for i in 0..len / 2 {
if chars[i] != chars[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 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 map = HashMap::new();
for word in text.split_whitespace() {
let key = word.to_lowercase();
*map.entry(key).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 word_lc = word.to_lowercase();
*counts.entry(word_lc).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 key = word.to_lowercase();
*counts.entry(key).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>(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.
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 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(x: &str, y: &str) -> &str {
if x.len() >= y.len() {
x
} else {
y
}
}
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).ok()?;
let right_val = T::from_str(right).ok()?;
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)).
use std::str::FromStr;
pub fn parse_pair<T: FromStr>(s: &str, sep: char) -> Option<(T, T)> {
let idx = s.find(sep)?;
let (left, rest) = s.split_at(idx);
let right = &rest[sep.len_utf8()..];
let a = T::from_str(left).ok()?;
let b = T::from_str(right).ok()?;
Some((a, 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 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)> {
let idx = s.find(sep)?;
let left = &s[..idx];
let right = &s[idx + 1..];
let left_val = left.parse::<T>().ok()?;
let right_val = right.parse::<T>().ok()?;
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 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
where
F: Fn(A) -> B,
G: Fn(B) -> C,
{
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<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.
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
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.
pub struct Fib {
a: u64,
b: u64,
finished: bool,
}
impl Fib {
pub fn new() -> Self {
Self {
a: 0,
b: 1,
finished: false,
}
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
if self.finished {
return None;
}
let current = self.a;
match self.a.checked_add(self.b) {
Some(next) => {
self.a = self.b;
self.b = next;
}
None => {
self.finished = 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.
pub struct Fib {
a: u64,
b: u64,
finished: bool,
}
impl Fib {
pub fn new() -> Self {
Fib {
a: 0,
b: 1,
finished: false,
}
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
if self.finished {
None
} else {
let current = self.a;
match self.a.checked_add(self.b) {
Some(next) => {
self.a = self.b;
self.b = next;
Some(current)
}
None => {
self.finished = 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.
pub struct Fib {
a: u64,
b: u64,
finished: bool,
}
impl Fib {
pub fn new() -> Self {
Fib {
a: 0,
b: 1,
finished: false,
}
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
if self.finished {
return None;
}
let current = self.a;
match self.a.checked_add(self.b) {
Some(next) => {
self.a = self.b;
self.b = next;
}
None => {
self.finished = 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 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::{self, Display};
#[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 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, "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,
}
}
}
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)?; // unreachable, but satisfies the type checker
let number_part = &s[..s.len() - unit.len_utf8()];
let value: f64 = number_part.parse()?;
match unit {
'C' => Ok(value),
'F' => Ok((value - 32.0) * 5.0 / 9.0),
other => Err(TempError::BadUnit(other)),
}
}
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;
#[derive(Debug)]
pub enum TempError {
Empty,
BadUnit(char),
BadNumber(std::num::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, "bad unit: {}", 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(err: std::num::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().unwrap();
match unit {
'C' | 'F' => {
let unit_len = unit.len_utf8();
let num_str = &s[..s.len() - unit_len];
let number: f64 = num_str.parse().map_err(TempError::BadNumber)?;
let result = if unit == 'C' {
number
} else {
(number - 32.0) * 5.0 / 9.0
};
Ok(result)
}
_ => 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::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 input"),
TempError::BadUnit(ch) => write!(f, "bad unit: {}", ch),
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<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().unwrap();
let num_part = &s[..s.len() - unit.len_utf8()];
let num: f64 = num_part.parse()?;
match unit {
'C' => Ok(num),
'F' => Ok((num - 32.0) * 5.0 / 9.0),
_ => 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.
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.
fn parallel_sum(data: &[u64], workers: usize) -> u64 {
if workers == 0 {
panic!("workers must be > 0");
}
if data.is_empty() {
return 0;
}
let step = (data.len() + workers - 1) / workers; // ceil division
let mut handles = Vec::with_capacity(workers);
for i in 0..workers {
let start = i * step;
let end = std::cmp::min(start + step, data.len());
let slice = data.get(start..end).unwrap_or(&[]);
handles.push(std::thread::spawn(move || slice.iter().sum::<u64>()));
}
handles.into_iter()
.map(|h| h.join().expect("thread panicked"))
.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 {
assert!(workers != 0, "workers must be non-zero");
if data.is_empty() {
return 0;
}
let chunk_size = (data.len() + workers - 1) / workers;
thread::scope(|s| {
let mut handles = Vec::with_capacity(workers);
for i in 0..workers {
let start = i * chunk_size;
if start >= data.len() {
handles.push(s.spawn(|| 0));
continue;
}
let end = usize::min(start + chunk_size, data.len());
let slice = &data[start..end];
handles.push(s.spawn(move || slice.iter().sum::<u64>()));
}
let mut total = 0u64;
for h in handles {
total += h.join();
}
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::Arc;
use std::thread;
fn parallel_sum(data: &[u64], workers: usize) -> u64 {
assert!(workers > 0, "workers must be > 0");
if data.is_empty() {
return 0;
}
let data_arc = Arc::new(data);
let len = data.len();
let chunk = (len + workers - 1) / workers;
let mut handles = Vec::with_capacity(workers);
for i in 0..workers {
let start = i * chunk;
let end = std::cmp::min(start + chunk, len);
let data_arc_clone = Arc::clone(&data_arc);
handles.push(thread::spawn(move || {
let slice = &*data_arc_clone;
if start >= slice.len() {
0
} else {
slice[start..end].iter().sum::<u64>()
}
}));
}
let mut total = 0;
for h in handles {
total += h.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.
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 + Sized
where
Self::Item: Clone,
{
fn pairs(self) -> Pairs<Self> {
Pairs {
iter: self,
prev: None,
}
}
}
pub struct Pairs<I> {
iter: I,
prev: Option<I::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> {
match self.prev.take() {
None => {
let first = self.iter.next()?;
self.prev = Some(first);
self.next()
}
Some(prev) => {
let next = self.iter.next()?;
let result = (prev.clone(), next.clone());
self.prev = Some(next);
Some(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 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 + Sized
where
Self::Item: Clone,
{
fn pairs(self) -> Pairs<Self> {
Pairs {
iter: self,
prev: None,
}
}
}
pub struct Pairs<I>
where
I: Iterator,
{
iter: I,
prev: Option<I::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> {
match self.prev.take() {
None => match self.iter.next() {
None => None,
Some(first) => {
self.prev = Some(first.clone());
self.next()
}
},
Some(prev) => match self.iter.next() {
None => None,
Some(next) => {
self.prev = Some(next.clone());
Some((prev, 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 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) -> Pairs<Self> {
Pairs {
iter: self,
prev: None,
}
}
}
impl<I> PairsExt for I where I: Iterator, I::Item: Clone {}
pub struct Pairs<I> {
iter: I,
prev: Option<I::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> {
if self.prev.is_none() {
self.prev = self.iter.next();
}
let prev = self.prev.as_ref()?;
let next = self.iter.next()?;
let pair = (prev.clone(), next.clone());
self.prev = Some(next);
Some(pair)
}
}
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};
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>) {
child.parent.borrow_mut().replace(Rc::downgrade(parent));
parent.children.borrow_mut().push(child);
}
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 {
let mut depth = 0;
let mut current = self.parent.borrow().upgrade();
while let Some(parent) = current {
depth += 1;
current = parent.parent.borrow().upgrade();
}
depth
}
}
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};
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>) {
*child.parent.borrow_mut() = Rc::downgrade(parent);
parent.children.borrow_mut().push(child);
}
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 {
let mut depth = 0;
let mut current = self;
loop {
let parent_opt = current.parent.borrow().upgrade();
match parent_opt {
Some(p) => {
depth += 1;
current = &*p;
}
None => break,
}
}
depth
}
}
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};
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>) {
child.parent.borrow_mut().replace(Rc::downgrade(parent));
parent.children.borrow_mut().push(child);
}
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 {
let mut depth = 0;
let mut current_parent_opt = self.parent.borrow().upgrade();
while let Some(parent_rc) = current_parent_opt {
depth += 1;
current_parent_opt = parent_rc.parent.borrow().upgrade();
}
depth
}
}