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 f: Vec<u8> = s.bytes()
.filter(|&b| b.is_ascii_alphanumeric())
.map(|b| b.to_ascii_lowercase())
.collect();
let n = f.len();
for i in 0..n / 2 {
if f[i] != f[n - 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.
fn is_palindrome(s: &str) -> bool {
let b = s.as_bytes();
let mut left = 0;
let mut right = b.len().saturating_sub(1);
loop {
if left >= right {
break true;
}
while left < right && !b[left].is_ascii_alphanumeric() {
left += 1;
}
while left < right && !b[right].is_ascii_alphanumeric() {
right -= 1;
}
if left >= right {
break true;
}
let l = b[left];
let r = b[right];
let l_norm = if l.is_ascii_uppercase() { l.to_ascii_lowercase() } else { l };
let r_norm = if r.is_ascii_uppercase() { r.to_ascii_lowercase() } else { r };
if l_norm != r_norm {
return false;
}
left += 1;
right -= 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 v: Vec<u8> = s.bytes()
.filter(|&b| b.is_ascii_alphanumeric())
.map(|b| b.to_ascii_lowercase())
.collect();
let n = v.len();
v[..n / 2].iter().eq(v[n - n / 2..].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 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 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 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 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 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;
pub fn parse_pair<T: FromStr>(s: &str, sep: char) -> Option<(T, T)> {
let (left, right) = s.split_once(sep)?;
let a = left.parse::<T>().ok()?;
let b = right.parse::<T>().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;
fn parse_pair<T: FromStr>(s: &str, sep: char) -> Option<(T, T)> {
let (left, right) = s.split_once(sep)?;
let left = left.parse().ok()?;
let right = right.parse().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 (a, b) = s.split_once(sep)?;
Some((a.parse().ok()?, b.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 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, 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.
pub 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: 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.
pub 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.
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::mem;
pub struct Fib {
state: State,
}
enum State {
Normal(u64, u64),
Last(u64),
Done,
}
impl Fib {
pub fn new() -> Self {
Fib {
state: State::Normal(0, 1),
}
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<u64> {
match mem::replace(&mut self.state, State::Done) {
State::Done => {
self.state = State::Done;
None
}
State::Last(a) => {
self.state = State::Done;
Some(a)
}
State::Normal(a, b) => {
let val = a;
match b.checked_add(a) {
Some(c) => self.state = State::Normal(b, c),
None => self.state = State::Last(b),
}
Some(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.
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,
done: bool,
}
impl Fib {
pub fn new() -> Self {
Fib { a: 0, b: 1, done: false }
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
let current = self.a;
match self.a.checked_add(self.b) {
Some(next) => {
self.a = self.b;
self.b = next;
}
None => {
self.done = true;
}
}
Some(current)
}
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define Fib, with a constructor Fib::new(), and implement Iterator<Item = u64> for it. It yields the Fibonacci numbers 0, 1, 1, 2, 3, 5, and so on. It yields every Fibonacci number that fits in a u64, then None from then on. Tests run with overflow checks on.
pub struct Fib {
state: FibState,
}
enum FibState {
Normal(u64, u64),
Final(u64),
Done,
}
impl Fib {
pub fn new() -> Self {
Fib { state: FibState::Normal(0, 1) }
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
match self.state {
FibState::Done => None,
FibState::Final(v) => {
self.state = FibState::Done;
Some(v)
}
FibState::Normal(a, b) => {
let v = a;
match a.checked_add(b) {
Some(s) => self.state = FibState::Normal(b, s),
None => self.state = FibState::Final(b),
}
Some(v)
}
}
}
}
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 => f.write_str("empty temperature string"),
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_char = s.chars().last().unwrap();
if unit_char != 'C' && unit_char != 'F' {
return Err(TempError::BadUnit(unit_char));
}
let split_pos = s.len() - unit_char.len_utf8();
let num_str = &s[..split_pos];
let value: f64 = num_str.parse()?;
if unit_char == 'F' {
Ok((value - 32.0) * 5.0 / 9.0)
} else {
Ok(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::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 => f.write_str("empty temperature string"),
TempError::BadUnit(c) => write!(f, "invalid unit: {c}"),
TempError::BadNumber(e) => write!(f, "invalid 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();
let num_str = &s[..s.len() - unit.len_utf8()];
let value: f64 = num_str.parse()?;
match unit {
'C' => Ok(value),
'F' => Ok((value - 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.
Define enum TempError deriving Debug, with the variants Empty, BadUnit(char), and BadNumber(std::num::ParseFloatError), and write parse_temp(s: &str) -> Result<f64, TempError>. The input is a number followed by one unit character, C or F, and the result is in Celsius, so "212F" returns 100.0. An empty string gives Empty. If the last character is neither C nor F, it gives BadUnit with that character, which may be non-ASCII. A number that does not parse gives BadNumber. Implement Display and std::error::Error for TempError, with source() returning the parse error for BadNumber, and implement From<std::num::ParseFloatError> for it.
#[derive(Debug)]
pub enum TempError {
Empty,
BadUnit(char),
BadNumber(std::num::ParseFloatError),
}
impl std::fmt::Display for TempError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TempError::Empty => write!(f, "empty string"),
TempError::BadUnit(c) => write!(f, "bad unit: {}", 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 mut chars = s.chars();
let unit = chars.next_back().unwrap();
let num_str = chars.as_str();
if unit != 'C' && unit != 'F' {
return Err(TempError::BadUnit(unit));
}
let value: f64 = num_str.parse().map_err(TempError::from)?;
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.
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 {
assert!(workers != 0, "workers must be greater than 0");
if data.is_empty() {
return 0;
}
let len = data.len();
std::thread::scope(|s| {
let mut handles = Vec::with_capacity(workers);
for i in 0..workers {
let start = i * len / workers;
let end = (i + 1) * len / workers;
let chunk = &data[start..end];
handles.push(s.spawn(move || chunk.iter().sum::<u64>()));
}
handles.into_iter().map(|h| h.join().unwrap()).sum()
})
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write parallel_sum(data: &[u64], workers: usize) -> u64, which sums data by splitting it across workers threads from std::thread. data is a borrowed slice, and workers may be larger than data.len(). It returns 0 for an empty slice and panics when workers is 0, including when the slice is empty.
use std::thread;
pub fn parallel_sum(data: &[u64], workers: usize) -> u64 {
assert!(workers != 0);
if data.is_empty() {
return 0;
}
thread::scope(|s| {
let mut handles = Vec::with_capacity(workers);
let len = data.len();
for w in 0..workers {
let start = w * len / workers;
let end = (w + 1) * len / workers;
let chunk = &data[start..end];
handles.push(s.spawn(move || chunk.iter().copied().sum::<u64>()));
}
let mut total = 0u64;
for h in handles {
total += h.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.
fn parallel_sum(data: &[u64], workers: usize) -> u64 {
assert!(workers != 0, "workers must be non-zero");
if data.is_empty() {
return 0;
}
let len = data.len();
let chunk_size = (len + workers - 1) / workers;
std::thread::scope(|s| {
let mut handles = Vec::with_capacity(workers);
for w in 0..workers {
let start = w * chunk_size;
if start >= len {
handles.push(s.spawn(|| 0));
} else {
let end = (start + chunk_size).min(len);
let chunk = &data[start..end];
handles.push(s.spawn(move || chunk.iter().sum::<u64>()));
}
}
let mut total = 0u64;
for h in handles {
total += h.join().unwrap();
}
total
})
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define an extension trait PairsExt that adds a method .pairs() to every iterator whose items implement Clone. It returns a lazy iterator of consecutive overlapping pairs, so (1..4).pairs() yields (1, 2) then (2, 3). A source with fewer than two items yields nothing, and an infinite source must work.
pub trait PairsExt: Iterator
where
Self::Item: Clone,
{
fn pairs(self) -> Pairs<Self>
where
Self: Sized;
}
pub struct Pairs<I: Iterator> {
inner: I,
prev: Option<I::Item>,
}
impl<I> PairsExt for I
where
I: Iterator,
I::Item: Clone,
{
fn pairs(self) -> Pairs<Self>
where
Self: Sized,
{
Pairs { inner: self, prev: None }
}
}
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.inner.next();
if self.prev.is_none() {
return None;
}
}
let curr = self.inner.next()?;
let prev = self.prev.take().unwrap();
self.prev = Some(curr.clone());
Some((prev, 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 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 struct Pairs<I: Iterator> {
iter: I,
prev: Option<I::Item>,
}
impl<I: Iterator> Pairs<I> {
fn new(mut iter: I) -> Self {
Self {
iter,
prev: iter.next(),
}
}
}
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 prev = self.prev.take()?;
let curr = self.iter.next()?;
self.prev = Some(curr.clone());
Some((prev, curr))
}
}
pub trait PairsExt: Iterator
where
Self::Item: Clone,
{
fn pairs(self) -> Pairs<Self>
where
Self: Sized;
}
impl<I> PairsExt for I
where
I: Iterator,
I::Item: Clone,
{
fn pairs(self) -> Pairs<Self>
where
Self: Sized,
{
Pairs::new(self)
}
}
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>
where
Self: Sized;
}
impl<T> PairsExt for T
where
T: Iterator,
T::Item: Clone,
{
fn pairs(self) -> Pairs<Self>
where
Self: Sized,
{
Pairs { iter: self, prev: None }
}
}
pub struct Pairs<I: Iterator> {
iter: I,
prev: Option<I::Item>,
}
impl<I: Iterator> Iterator for Pairs<I>
where
I::Item: Clone,
{
type Item = (I::Item, I::Item);
fn next(&mut self) -> Option<Self::Item> {
if let Some(prev) = self.prev.take() {
let curr = self.iter.next()?;
self.prev = Some(curr.clone());
Some((prev, curr))
} else {
let first = self.iter.next()?;
let second = self.iter.next()?;
self.prev = Some(second.clone());
Some((first, second))
}
}
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define TreeNode with exactly these fields: value: i32, parent: RefCell<Weak<TreeNode>>, and children: RefCell<Vec<Rc<TreeNode>>>, importing those types from the standard library. Write TreeNode::new(value: i32) -> Rc<TreeNode>. Write TreeNode::add_child(parent: &Rc<TreeNode>, child: Rc<TreeNode>), which also sets the child's parent. Write sum(&self) -> i32, the total of this node and all its descendants, and depth(&self) -> usize, the number of ancestors, which is 0 for a root.
use std::cell::RefCell;
use std::rc::{Rc, Weak};
struct TreeNode {
value: i32,
parent: RefCell<Weak<TreeNode>>,
children: RefCell<Vec<Rc<TreeNode>>>,
}
impl TreeNode {
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>) {
*child.parent.borrow_mut() = Rc::downgrade(parent);
parent.children.borrow_mut().push(child);
}
fn sum(&self) -> i32 {
let mut total = self.value;
for child in self.children.borrow().iter() {
total += child.sum();
}
total
}
fn depth(&self) -> usize {
if let Some(parent) = self.parent.borrow().upgrade() {
parent.depth() + 1
} else {
0
}
}
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define TreeNode with exactly these fields: value: i32, parent: RefCell<Weak<TreeNode>>, and children: RefCell<Vec<Rc<TreeNode>>>, importing those types from the standard library. Write TreeNode::new(value: i32) -> Rc<TreeNode>. Write TreeNode::add_child(parent: &Rc<TreeNode>, child: Rc<TreeNode>), which also sets the child's parent. Write sum(&self) -> i32, the total of this node and all its descendants, and depth(&self) -> usize, the number of ancestors, which is 0 for a root.
use std::cell::RefCell;
use std::rc::{Rc, Weak};
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 {
let mut total = self.value;
for child in self.children.borrow().iter() {
total += child.sum();
}
total
}
pub fn depth(&self) -> usize {
match self.parent.borrow().upgrade() {
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};
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 {
let mut total = self.value;
for child in self.children.borrow().iter() {
total += child.sum();
}
total
}
pub fn depth(&self) -> usize {
let parent_opt = self.parent.borrow().upgrade();
match parent_opt {
Some(parent) => 1 + parent.depth(),
None => 0,
}
}
}