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.
use std::ascii::AsciiExt;
fn is_palindrome(s: &str) -> bool {
let mut left = 0;
let mut right = s.len().saturating_sub(1);
while left < right {
while left < right && !s.as_bytes()[left].is_ascii_alphanumeric() {
left += 1;
}
while left < right && !s.as_bytes()[right].is_ascii_alphanumeric() {
right -= 1;
}
if left < right {
let left_char = s.as_bytes()[left].to_ascii_lowercase();
let right_char = s.as_bytes()[right].to_ascii_lowercase();
if left_char != right_char {
return false;
}
left += 1;
right -= 1;
}
}
true
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write is_palindrome(s: &str) -> bool. Consider only ASCII letters and digits, ignoring ASCII case and every other character. A string with none of those characters is a palindrome.
fn is_palindrome(s: &str) -> bool {
let mut left = 0;
let mut right = s.len().saturating_sub(1);
while left < right {
let l = s.as_bytes()[left];
let r = s.as_bytes()[right];
if !(l.is_ascii_alphanumeric() && r.is_ascii_alphanumeric()) {
if l.is_ascii_alphanumeric() {
right -= 1;
} else if r.is_ascii_alphanumeric() {
left += 1;
} else {
left += 1;
right -= 1;
}
continue;
}
let l_lower = l.to_ascii_lowercase();
let r_lower = r.to_ascii_lowercase();
if l_lower != r_lower {
return false;
}
left += 1;
right -= 1;
}
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.
use std::ascii::AsciiExt;
fn is_palindrome(s: &str) -> bool {
let mut left = 0;
let mut right = s.len().saturating_sub(1);
while left < right {
let l_char = s.as_bytes()[left];
let r_char = s.as_bytes()[right];
if !l_char.is_ascii_alphanumeric() || !r_char.is_ascii_alphanumeric() {
if !l_char.is_ascii_alphanumeric() {
left += 1;
}
if !r_char.is_ascii_alphanumeric() {
right -= 1;
}
continue;
}
let l_lower = l_char.to_ascii_lowercase();
let r_lower = r_char.to_ascii_lowercase();
if l_lower != r_lower {
return false;
}
left += 1;
right -= 1;
}
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> {
text.split_whitespace()
.map(|word| word.to_lowercase())
.fold(HashMap::new(), |mut acc, word| {
*acc.entry(word).or_insert(0) += 1;
acc
})
}
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> {
text.split_whitespace()
.map(|word| word.to_lowercase())
.fold(HashMap::new(), |mut acc, word| {
*acc.entry(word).or_insert(0) += 1;
acc
})
}
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> {
text.split_whitespace()
.filter_map(|word| {
let lower_word = word.to_lowercase();
if lower_word.is_empty() {
None
} else {
Some(lower_word)
}
})
.fold(HashMap::new(), |mut acc, word| {
*acc.entry(word).or_insert(0) += 1;
acc
})
}
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.
use std::mem;
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.
use std::borrow::Cow;
fn longest<'a>(a: &'a str, b: &'a str) -> Cow<'a, str> {
if a.len() >= b.len() {
Cow::Borrowed(a)
} else {
Cow::Borrowed(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.
use std::cmp;
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 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 parts: Vec<&str> = s.splitn(2, sep).collect();
if parts.len() != 2 {
return None;
}
match (parts[0].parse::<T>(), parts[1].parse::<T>()) {
(Ok(a), Ok(b)) => Some((a, b)),
_ => 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.
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 parts: Vec<&str> = s.splitn(2, sep).collect();
if parts.len() != 2 {
return None;
}
let left = parts[0].parse::<T>().ok()?;
let right = parts[1].parse::<T>().ok()?;
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 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 parts: Vec<&str> = s.splitn(2, sep).collect();
if parts.len() != 2 {
return None;
}
match (parts[0].parse::<T>(), parts[1].parse::<T>()) {
(Ok(a), Ok(b)) => Some((a, b)),
_ => 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.
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.
use std::ops::Fn;
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.
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.
use std::marker::PhantomData;
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.
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.
use std::marker::PhantomData;
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.
use std::iter::Iterator;
pub struct Fib {
current: u64,
next: u64,
}
impl Fib {
pub fn new() -> Self {
Fib { current: 0, next: 1 }
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
if self.current > u64::MAX - self.next {
return None;
}
let result = self.current;
self.current = self.next;
self.next = result.wrapping_add(self.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 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,
}
impl Fib {
pub fn new() -> Self {
Fib { a: 0, b: 1 }
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
let current = self.a;
if current > u64::MAX - self.b {
return None;
}
self.a = self.b;
self.b += current;
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.
use std::iter::Iterator;
pub struct Fib {
current: u64,
next: u64,
}
impl Fib {
pub fn new() -> Self {
Fib { current: 0, next: 1 }
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
let item = self.current;
if item == u64::MAX - 1 && self.next == u64::MAX {
None
} else {
self.current = self.next;
self.next = match self.current.checked_add(self.next) {
Some(val) => val,
None => return None,
};
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 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;
use std::error::Error;
#[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, "bad unit '{}'", c),
TempError::BadNumber(_) => write!(f, "invalid number"),
}
}
}
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 last_char = s.chars().last().ok_or(TempError::Empty)?;
let s = &s[..s.len() - 1];
let num: f64 = s.parse()?;
let unit = last_char;
if unit == 'C' {
Ok(num)
} else if unit == 'F' {
Ok((num - 32.0) * 5.0 / 9.0)
} else {
Err(TempError::BadUnit(unit))
}
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define enum TempError deriving Debug, with the variants Empty, BadUnit(char), and BadNumber(std::num::ParseFloatError), and write parse_temp(s: &str) -> Result<f64, TempError>. The input is a number followed by one unit character, C or F, and the result is in Celsius, so "212F" returns 100.0. An empty string gives Empty. If the last character is neither C nor F, it gives BadUnit with that character, which may be non-ASCII. A number that does not parse gives BadNumber. Implement Display and std::error::Error for TempError, with source() returning the parse error for BadNumber, and implement From<std::num::ParseFloatError> for it.
use std::fmt;
use std::num::ParseFloatError;
use std::error::Error;
#[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 temperature string"),
TempError::BadUnit(c) => write!(f, "invalid unit '{}'", c),
TempError::BadNumber(_) => write!(f, "invalid temperature number"),
}
}
}
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 last_char = s.chars().last().ok_or(TempError::Empty)?;
let num_str = &s[..s.len() - 1];
let unit = match last_char {
'C' | 'F' => last_char,
_ => return Err(TempError::BadUnit(last_char)),
};
let temp = num_str.parse::<f64>()?;
match unit {
'C' => Ok(temp),
'F' => Ok((temp - 32.0) * 5.0 / 9.0),
_ => unreachable!(),
}
}
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;
use std::error::Error;
#[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 last_char = s.chars().last().ok_or(TempError::Empty)?;
let num_str = &s[..s.len() - 1];
let num = num_str.parse::<f64>()?;
let temp = match last_char {
'C' => num,
'F' => (num - 32.0) * 5.0 / 9.0,
_ => return Err(TempError::BadUnit(last_char)),
};
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::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::thread;
fn parallel_sum(data: &[u64], workers: usize) -> u64 {
assert_ne!(workers, 0, "Workers cannot be 0");
if data.is_empty() {
return 0;
}
let chunk_size = (data.len() + workers - 1) / workers;
let total = Arc::new(AtomicU64::new(0));
let total_clone = total.clone();
let handles: Vec<_> = (0..workers)
.map(|i| {
let start = i * chunk_size;
let end = std::cmp::min(start + chunk_size, data.len());
let chunk = &data[start..end];
thread::spawn(move || {
let partial_sum: u64 = chunk.iter().sum();
total_clone.fetch_add(partial_sum, Ordering::Relaxed);
})
})
.collect();
for handle in handles {
handle.join().unwrap();
}
total.load(Ordering::Relaxed)
}
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 0");
}
if data.is_empty() {
return 0;
}
let chunk_size = (data.len() + workers - 1) / workers;
let (tx, rx) = mpsc::channel();
let mut handles = vec![];
for i in 0..workers {
let start = i * chunk_size;
let end = if i == workers - 1 {
data.len()
} else {
(i + 1) * chunk_size
};
let tx = tx.clone();
let chunk = &data[start..end];
handles.push(thread::spawn(move || {
tx.send(chunk.iter().sum()).unwrap();
}));
}
let mut sum = 0;
for _ in 0..workers {
sum += rx.recv().unwrap();
}
handles.into_iter().for_each(|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::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::thread;
fn parallel_sum(data: &[u64], workers: usize) -> u64 {
if workers == 0 {
panic!("workers cannot be 0");
}
let total = Arc::new(AtomicU64::new(0));
let chunk_size = (data.len() + workers - 1) / workers;
thread::scope(|s| {
for i in 0..workers {
let total = Arc::clone(&total);
let start = i * chunk_size;
let end = if i == workers - 1 { data.len() } else { start + chunk_size };
s.spawn(move || {
let partial_sum: u64 = data[start..end].iter().sum();
total.fetch_add(partial_sum, Ordering::Relaxed);
});
}
});
total.load(Ordering::Relaxed)
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define an extension trait PairsExt that adds a method .pairs() to every iterator whose items implement Clone. It returns a lazy iterator of consecutive overlapping pairs, so (1..4).pairs() yields (1, 2) then (2, 3). A source with fewer than two items yields nothing, and an infinite source must work.
use std::iter::{Peekable, Iterator};
trait PairsExt<I: Iterator> {
fn pairs(self) -> impl Iterator<Item = (I::Item, I::Item)>;
}
impl<I: Iterator + Clone> PairsExt<I> for I {
fn pairs(mut self) -> impl Iterator<Item = (I::Item, I::Item)> {
let mut peekable = self.peekable();
std::iter::from_fn(move || {
if let (Some(a), Some(b)) = (peekable.next(), peekable.peek()) {
Some((a, b.clone()))
} else {
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;
trait PairsExt: Iterator {
fn pairs(self) -> impl Iterator<Item = (Self::Item, Self::Item)> + '_
where
Self::Item: Clone,
{
self.scan((), |_, item| {
let item = item.clone();
Some(item)
}).tuple_windows()
}
}
impl<T: Iterator> PairsExt for 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.
Define an extension trait PairsExt that adds a method .pairs() to every iterator whose items implement Clone. It returns a lazy iterator of consecutive overlapping pairs, so (1..4).pairs() yields (1, 2) then (2, 3). A source with fewer than two items yields nothing, and an infinite source must work.
use std::iter::Peekable;
use std::clone::Clone;
trait PairsExt: Iterator {
fn pairs(self) -> Pairs<Self>
where
Self: Sized,
Self::Item: Clone,
{
Pairs::new(self.peekable())
}
}
impl<T: Iterator> PairsExt for T {}
struct Pairs<I> {
inner: Peekable<I>,
}
impl<I> Pairs<I> {
fn new(inner: Peekable<I>) -> Self {
Self { inner }
}
}
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 next = self.inner.next()?;
let peeked = self.inner.peek()?.clone();
self.inner.next();
Some((next, peeked))
}
}
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)]
pub struct TreeNode {
pub value: i32,
pub parent: RefCell<Weak<TreeNode>>,
pub children: RefCell<Vec<Rc<TreeNode>>>,
}
impl TreeNode {
pub fn new(value: i32) -> Rc<TreeNode> {
Rc::new(TreeNode {
value,
parent: RefCell::new(Weak::new()),
children: RefCell::new(Vec::new()),
})
}
pub fn add_child(parent: &Rc<TreeNode>, child: Rc<TreeNode>) {
parent.children.borrow_mut().push(child.clone());
child.parent.replace(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 {
let parent = self.parent.borrow();
if let Some(parent) = parent.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::cell::RefCell;
use std::rc::{Rc, Weak};
#[derive(Debug)]
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>) {
parent.children.borrow_mut().push(child.clone());
child.parent.borrow_mut().set_weak(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 {
let parent = self.parent.borrow();
if let Some(parent) = parent.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::cell::RefCell;
use std::rc::{Rc, Weak};
#[derive(Debug)]
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>) {
parent.children.borrow_mut().push(child.clone());
child.parent.replace(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 {
let parent = self.parent.borrow();
if parent.strong_count() == 0 {
0
} else {
1 + parent.upgrade().unwrap().depth()
}
}
}