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 mut it = s.chars().filter(|c| c.is_ascii_alphanumeric());
while let (Some(a), Some(b)) = (it.next(), it.next_back()) {
if !a.eq_ignore_ascii_case(&b) {
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 chars: Vec<u8> = s
.bytes()
.filter(|b| b.is_ascii_alphanumeric())
.map(|b| b.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 mut it = s
.bytes()
.filter(|b| b.is_ascii_alphanumeric())
.map(|b| b.to_ascii_lowercase());
while let Some(a) = it.next() {
match it.next_back() {
Some(b) if a != b => return false,
Some(_) => {}
None => break,
}
}
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<String, usize> = HashMap::new();
for word in text.split_whitespace() {
*counts.entry(word.to_lowercase()).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<String, usize> = HashMap::new();
for word in text.split_whitespace() {
*counts.entry(word.to_lowercase()).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<String, usize> = HashMap::new();
for word in text.split_whitespace() {
*counts.entry(word.to_lowercase()).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>(x: &'a str, y: &'a str) -> &'a 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 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>(x: &'a str, y: &'a str) -> &'a 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 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>(x: &'a str, y: &'a str) -> &'a 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 (left, right) = s.split_once(sep)?;
Some((left.parse().ok()?, right.parse().ok()?))
}
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 (left, right) = s.split_once(sep)?;
Some((left.parse().ok()?, right.parse().ok()?))
}
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 (left, right) = s.split_once(sep)?;
Some((T::from_str(left).ok()?, T::from_str(right).ok()?))
}
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<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<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.
pub struct Fib {
prev: u64,
curr: u64,
}
impl Fib {
pub fn new() -> Self {
Fib { prev: 1, curr: 0 }
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<u64> {
let item = self.curr;
let next = self.prev.checked_add(self.curr)?;
self.prev = self.curr;
self.curr = next;
Some(item)
}
}
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 {
state: Option<(u64, u64)>,
}
impl Fib {
pub fn new() -> Self {
Fib { state: Some((0, 1)) }
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<u64> {
let (a, b) = self.state?;
self.state = b.checked_add(a).map(|sum| (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 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 {
state: Option<(u64, u64)>,
}
impl Fib {
pub fn new() -> Self {
Fib {
state: Some((1, 0)),
}
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<u64> {
let (prev, curr) = self.state.take()?;
if let Some(next) = prev.checked_add(curr) {
self.state = Some((curr, next));
}
Some(curr)
}
}
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, Formatter};
use std::num::ParseFloatError;
#[derive(Debug)]
pub enum TempError {
Empty,
BadUnit(char),
BadNumber(ParseFloatError),
}
impl Display for TempError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
TempError::Empty => write!(f, "empty temperature string"),
TempError::BadUnit(c) => write!(f, "invalid unit character: {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),
TempError::Empty | TempError::BadUnit(_) => None,
}
}
}
impl From<ParseFloatError> for TempError {
fn from(e: ParseFloatError) -> Self {
TempError::BadNumber(e)
}
}
pub fn parse_temp(s: &str) -> Result<f64, TempError> {
let Some(last) = s.chars().next_back() else {
return Err(TempError::Empty);
};
let (num, unit) = s.split_at(s.len() - last.len_utf8());
let value: f64 = num.parse()?;
match unit {
"C" => Ok(value),
"F" => Ok((value - 32.0) * 5.0 / 9.0),
_ => Err(TempError::BadUnit(last)),
}
}
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 input"),
TempError::BadUnit(c) => write!(f, "bad unit character: {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> {
let unit = s.chars().last().ok_or(TempError::Empty)?;
if unit != 'C' && unit != 'F' {
return Err(TempError::BadUnit(unit));
}
let num_part = &s[..s.len() - unit.len_utf8()];
let value: f64 = num_part.parse()?;
Ok(if unit == 'F' {
(value - 32.0) * 5.0 / 9.0
} else {
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.
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 input"),
TempError::BadUnit(c) => write!(f, "bad unit character: {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> {
let mut chars = s.chars();
let unit = chars.next_back().ok_or(TempError::Empty)?;
if unit != 'C' && unit != 'F' {
return Err(TempError::BadUnit(unit));
}
let number: String = chars.collect();
let value: f64 = number.parse()?;
Ok(match unit {
'F' => (value - 32.0) * 5.0 / 9.0,
_ => 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.
use std::thread;
pub fn parallel_sum(data: &[u64], workers: usize) -> u64 {
assert!(workers > 0, "workers must be greater than zero");
if data.is_empty() {
return 0;
}
let workers = workers.min(data.len());
let chunk_size = data.len().div_ceil(workers);
thread::scope(|scope| {
let handles: Vec<_> = data
.chunks(chunk_size)
.map(|chunk| scope.spawn(move || chunk.iter().sum::<u64>()))
.collect();
handles
.into_iter()
.map(|handle| handle.join().expect("worker thread panicked"))
.sum::<u64>()
})
}
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 greater than zero");
if data.is_empty() {
return 0;
}
let len = data.len();
let thread_count = workers.min(len);
let base = len / thread_count;
let remainder = len % thread_count;
let offset = |i: usize| i * base + i.min(remainder);
thread::scope(|scope| {
let handles: Vec<_> = (0..thread_count)
.map(|i| {
let chunk = &data[offset(i)..offset(i + 1)];
scope.spawn(move || chunk.iter().sum::<u64>())
})
.collect();
handles
.into_iter()
.map(|handle| handle.join().expect("worker thread panicked"))
.sum::<u64>()
})
}
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 greater than zero");
if data.is_empty() {
return 0;
}
thread::scope(|scope| {
let chunk_size = data.len().div_ceil(workers);
let handles: Vec<_> = data
.chunks(chunk_size)
.map(|chunk| scope.spawn(move || chunk.iter().sum::<u64>()))
.collect();
handles
.into_iter()
.map(|handle| handle.join().expect("worker thread panicked"))
.sum::<u64>()
})
}
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::FusedIterator;
pub trait PairsExt: Iterator {
fn pairs(self) -> Pairs<Self>
where
Self: Sized,
Self::Item: Clone,
{
Pairs {
iter: self,
prev: None,
}
}
}
impl<I: Iterator> PairsExt for I {}
pub struct Pairs<I>
where
I: Iterator,
I::Item: Clone,
{
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> {
loop {
let item = self.iter.next()?;
match self.prev.take() {
Some(prev) => {
self.prev = Some(item.clone());
return Some((prev, item));
}
None => self.prev = Some(item),
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (lo, hi) = self.iter.size_hint();
let held = usize::from(self.prev.is_some());
let lower = if lo == 0 { 0 } else { lo - 1 + held };
let upper = hi.map(|h| if h == 0 { 0 } else { (h - 1).saturating_add(held) });
(lower, upper)
}
}
impl<I> FusedIterator for Pairs<I>
where
I: Iterator + FusedIterator,
I::Item: Clone,
{
}
impl<I> Clone for Pairs<I>
where
I: Iterator + Clone,
I::Item: Clone,
{
fn clone(&self) -> Self {
Self {
iter: self.iter.clone(),
prev: self.prev.clone(),
}
}
}
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::{ExactSizeIterator, FusedIterator};
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> {
let first = match self.prev.take() {
Some(item) => item,
None => self.iter.next()?,
};
let second = self.iter.next()?;
self.prev = Some(second.clone());
Some((first, second))
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (lower, upper) = self.iter.size_hint();
if self.prev.is_some() {
(lower, upper)
} else {
(
lower.saturating_sub(1),
upper.map(|upper| upper.saturating_sub(1)),
)
}
}
}
impl<I> FusedIterator for Pairs<I>
where
I: FusedIterator,
I::Item: Clone,
{
}
impl<I> ExactSizeIterator for Pairs<I>
where
I: ExactSizeIterator,
I::Item: Clone,
{
fn len(&self) -> usize {
let len = self.iter.len();
if self.prev.is_some() {
len
} else {
len.saturating_sub(1)
}
}
}
pub trait PairsExt: Iterator {
fn pairs(self) -> Pairs<Self>
where
Self: Sized,
Self::Item: Clone,
{
Pairs {
iter: self,
prev: None,
}
}
}
impl<I: Iterator> 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.
use std::iter::FusedIterator;
pub trait PairsExt: Iterator {
fn pairs(self) -> Pairs<Self>
where
Self: Sized,
Self::Item: Clone;
}
impl<I: Iterator> PairsExt for I {
fn pairs(self) -> Pairs<Self>
where
Self: Sized,
Self::Item: Clone,
{
Pairs {
iter: self,
prev: None,
done: false,
}
}
}
pub struct Pairs<I: Iterator> {
iter: I,
prev: Option<I::Item>,
done: bool,
}
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.done {
return None;
}
let prev = match self.prev.take() {
Some(prev) => prev,
None => match self.iter.next() {
Some(first) => first,
None => {
self.done = true;
return None;
}
},
};
match self.iter.next() {
Some(current) => {
self.prev = Some(current.clone());
Some((prev, current))
}
None => {
self.done = true;
None
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
if self.done {
return (0, Some(0));
}
let (lower, upper) = self.iter.size_hint();
if self.prev.is_some() {
(lower, upper)
} else {
(
lower.saturating_sub(1),
upper.map(|u| u.saturating_sub(1)),
)
}
}
}
impl<I> FusedIterator for Pairs<I>
where
I: Iterator,
I::Item: Clone,
{
}
impl<I> Clone for Pairs<I>
where
I: Iterator + Clone,
I::Item: Clone,
{
fn clone(&self) -> Self {
Pairs {
iter: self.iter.clone(),
prev: self.prev.clone(),
done: self.done,
}
}
}
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.replace(Rc::downgrade(parent));
parent.children.borrow_mut().push(child);
}
pub fn sum(&self) -> i32 {
self.value
+ self
.children
.borrow()
.iter()
.map(|child| child.sum())
.sum::<i32>()
}
pub fn depth(&self) -> usize {
self.parent
.borrow()
.upgrade()
.map_or(0, |ancestor| 1 + ancestor.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 {
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>) {
*child.parent.borrow_mut() = Rc::downgrade(parent);
parent.children.borrow_mut().push(child);
}
pub fn sum(&self) -> i32 {
self.value
+ self
.children
.borrow()
.iter()
.map(|child| child.sum())
.sum::<i32>()
}
pub fn depth(&self) -> usize {
let mut depth = 0;
let mut ancestor = self.parent.borrow().clone();
while let Some(node) = ancestor.upgrade() {
depth += 1;
ancestor = node.parent.borrow().clone();
}
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 {
self.value + self.children.borrow().iter().map(|c| c.sum()).sum::<i32>()
}
pub fn depth(&self) -> usize {
match self.parent.borrow().upgrade() {
Some(ancestor) => 1 + ancestor.depth(),
None => 0,
}
}
}