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_alphabetic() || c.is_ascii_digit())
.map(|c| c.to_ascii_lowercase())
.collect();
filtered == filtered.iter().rev().collect::<Vec<char>>()
}
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: String = s.chars()
.filter(|c| c.is_ascii_alphanumeric())
.map(|c| c.to_ascii_lowercase())
.collect();
filtered == filtered.chars().rev().collect::<String>()
}
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: String = s.chars()
.filter(|c| c.is_ascii_alphabetic() || c.is_ascii_digit())
.map(|c| c.to_ascii_lowercase())
.collect();
filtered == filtered.chars().rev().collect::<String>()
}
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 lower = word.to_lowercase();
*counts.entry(lower).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::new();
for word in text.split_whitespace() {
let lower = word.to_lowercase();
*counts.entry(lower).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::new();
for word in text
.split(|c: char| c.is_whitespace())
.filter(|s| !s.is_empty())
.map(|s| s.to_lowercase())
{
*counts.entry(word).or_insert(0) += 1;
}
counts
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write longest, which takes two string slices and returns the longer one by str::len without allocating. On a tie, it returns the first. Its result must be usable as long as both inputs are alive.
fn longest<'a, 'b>(a: &'a str, b: &'b 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 longer<'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.
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 idx = s.find(sep)?;
let (left, right) = s.split_at(idx);
let left = left.trim();
let right = right.get(1..).unwrap_or_default().trim();
T::from_str(left).ok().and_then(|a| T::from_str(right).ok().map(|b| (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)).
fn parse_pair<T: FromStr>(s: &str, sep: char) -> Option<(T, T)> {
let sep_index = s.find(sep)?;
let left_str = &s[..sep_index];
let right_str = &s[sep_index + 1..];
let left = T::from_str(left_str).ok()?;
let right = T::from_str(right_str).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 idx = s.find(sep)?;
let (left, right) = s.split_at(idx);
T::from_str(left).ok().and_then(|l| T::from_str(&right[1..]).map(|r| (l, r)))
}
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.
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.
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 + 'static
where
F: Fn(A) -> B + 'static,
G: Fn(B) -> C + 'static,
{
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.
struct Fib {
current: u64,
next: u64,
overflowed: bool,
}
impl Fib {
fn new() -> Self {
Fib {
current: 0,
next: 1,
overflowed: false,
}
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
if self.overflowed {
return None;
}
let current = self.current;
let new_current = self.next;
let new_next = self.current.checked_add(self.next);
if new_next.is_none() {
self.overflowed = true;
} else {
self.current = new_current;
self.next = new_next.unwrap();
}
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.
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.
struct Fib {
a: u64,
b: u64,
exhausted: bool,
}
impl Fib {
pub fn new() -> Self {
Fib { a: 0, b: 1, exhausted: false }
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
if self.exhausted {
return None;
}
let current = self.a;
let new_a = self.b;
let new_b = self.a.checked_add(self.b);
if new_b.is_none() {
self.exhausted = true;
return Some(current);
}
self.a = new_a;
self.b = new_b.unwrap();
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::fmt;
use std::error::Error;
use std::num::ParseFloatError;
#[derive(Debug)]
enum TempError {
Empty,
BadUnit(char),
BadNumber(ParseFloatError),
}
impl fmt::Display for TempError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TempError::Empty => write!(f, "Empty"),
TempError::BadUnit(c) => write!(f, "Bad unit: {}", c),
TempError::BadNumber(e) => write!(f, "{}", 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)
}
}
fn parse_temp(s: &str) -> Result<f64, TempError> {
if s.is_empty() {
return Err(TempError::Empty);
}
let unit_char = s.chars().last().unwrap();
let unit_str = &s[0..s.len() - 1];
let unit = if unit_char == 'C' {
'C'
} else if unit_char == 'F' {
'F'
} else {
return Err(TempError::BadUnit(unit_char));
};
let num: f64 = unit_str.parse().map_err(TempError::BadNumber)?;
let celsius = if unit == 'C' {
num
} else {
(num - 32.0) * 5.0 / 9.0
};
Ok(celsius)
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Define enum TempError deriving Debug, with the variants Empty, BadUnit(char), and BadNumber(std::num::ParseFloatError), and write parse_temp(s: &str) -> Result<f64, TempError>. The input is a number followed by one unit character, C or F, and the result is in Celsius, so "212F" returns 100.0. An empty string gives Empty. If the last character is neither C nor F, it gives BadUnit with that character, which may be non-ASCII. A number that does not parse gives BadNumber. Implement Display and std::error::Error for TempError, with source() returning the parse error for BadNumber, and implement From<std::num::ParseFloatError> for it.
use std::fmt;
use std::error::Error;
use std::num::ParseFloatError;
#[derive(Debug)]
enum TempError {
Empty,
BadUnit(char),
BadNumber(ParseFloatError),
}
impl fmt::Display for TempError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TempError::Empty => write!(f, "Empty 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,
}
}
}
impl From<ParseFloatError> for TempError {
fn from(e: ParseFloatError) -> Self {
TempError::BadNumber(e)
}
}
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 num_str = &s[0..s.len() - 1];
let temp_f = num_str.parse::<f64>().map_err(TempError::from)?;
if unit_char == 'F' {
Ok((temp_f - 32.0) * 5.0 / 9.0)
} else {
Ok(temp_f)
}
}
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::num::ParseFloatError;
use std::fmt;
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, "invalid unit character: {}", c),
TempError::BadNumber(e) => write!(f, "failed to parse 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)
}
}
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 num_str = &s[0..s.len() - 1];
let temp: f64 = num_str.parse().map_err(TempError::from)?;
let celsius = if unit_char == 'F' {
(temp - 32.0) * 5.0 / 9.0
} else {
temp
};
Ok(celsius)
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
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;
fn parallel_sum(data: &[u64], workers: usize) -> u64 {
if workers == 0 {
panic!("workers is 0");
}
if data.is_empty() {
return 0;
}
let total = data.len();
let chunk_size = total / workers;
let remainder = total % workers;
let mut handles = vec![];
for i in 0..workers {
let start;
let end;
if i < remainder {
start = i * (chunk_size + 1);
end = (i + 1) * (chunk_size + 1);
} else {
start = i * chunk_size + remainder;
end = (i + 1) * chunk_size + remainder;
}
let chunk = &data[start..end];
let handle = thread::spawn(move || {
chunk.iter().sum::<u64>()
});
handles.push(handle);
}
let mut sum = 0;
for handle in handles {
sum += handle.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;
fn parallel_sum(data: &[u64], workers: usize) -> u64 {
if workers == 0 {
panic!("workers is 0");
}
if data.is_empty() {
return 0;
}
let data_vec = data.to_vec();
let mut handles = vec![];
for i in 0..workers {
let start = (data.len() * i) / workers;
let end = (data.len() * (i + 1)) / workers;
let chunk = data_vec[start..end].to_vec();
let handle = thread::spawn(move || {
chunk.iter().sum::<u64>()
});
handles.push(handle);
}
let mut total = 0;
for handle in handles {
total += handle.join().unwrap();
}
total
}
Write Rust for the 2024 edition on stable, using only the standard library. Answer with one ```rust code block that defines what the question describes. Do not include fn main, tests, examples, explanations, or print statements.
Write parallel_sum(data: &[u64], workers: usize) -> u64, which sums data by splitting it across workers threads from std::thread. data is a borrowed slice, and workers may be larger than data.len(). It returns 0 for an empty slice and panics when workers is 0, including when the slice is empty.
use std::thread;
pub fn parallel_sum(data: &[u64], workers: usize) -> u64 {
if workers == 0 {
panic!("workers is 0");
}
if data.is_empty() {
return 0;
}
let n = data.len();
let chunk_size = n / workers;
let remainder = n % workers;
let handles: Vec<_> = (0..workers).map(|i| {
let start = if i < remainder {
i * (chunk_size + 1)
} else {
i * chunk_size + remainder
};
let end = start + if i < remainder { chunk_size + 1 } else { chunk_size };
let data_ref = data;
thread::spawn(move || {
let slice = &data_ref[start..end];
slice.iter().sum::<u64>()
})
}).collect();
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.
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>;
}
pub struct Pairs<I>
where
I: Iterator,
I::Item: Clone,
{
iter: I,
prev: Option<I::Item>,
}
impl<I> Pairs<I>
where
I: Iterator,
I::Item: Clone,
{
fn new(iter: I) -> Self {
Pairs { iter, 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> {
let current = self.iter.next()?;
let prev = self.prev.take();
let prev = match prev {
Some(p) => p,
None => {
self.prev = Some(current.clone());
return None;
}
};
self.prev = Some(current.clone());
Some((prev, current))
}
}
impl<I> PairsExt for I
where
I: Iterator,
I::Item: Clone,
{
fn pairs(self) -> Pairs<Self> {
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.
use std::iter::Iterator;
pub struct Pairs<I> {
iter: I,
prev: Option<<I as Iterator>::Item>,
}
pub trait PairsExt: Iterator where Self::Item: Clone {
fn pairs(self) -> Pairs<Self>;
}
impl<I> PairsExt for I where I: Iterator, I::Item: Clone {
fn pairs(self) -> Pairs<Self> {
Pairs { iter: 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> {
let current = self.iter.next()?;
match self.prev {
Some(prev_val) => {
let result = Some((prev_val.clone(), current.clone()));
self.prev = Some(current);
result
}
None => {
self.prev = Some(current);
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.
pub trait PairsExt: Iterator where Self::Item: Clone {
fn pairs(self) -> Pairs<Self>;
}
struct Pairs<I> {
iter: I,
prev: Option<<I as Iterator>::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 let Some(prev) = self.prev {
let current = self.iter.next()?;
self.prev = Some(current.clone());
return Some((prev, current));
} else {
let first = self.iter.next()?;
let second = self.iter.next()?;
self.prev = Some(second.clone());
return Some((first, second));
}
}
}
impl<I> PairsExt for I where I: Iterator, I::Item: Clone {
fn pairs(self) -> Pairs<Self> {
Pairs {
iter: self,
prev: 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 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::rc::{Rc, Weak};
use std::cell::RefCell;
struct TreeNode {
value: i32,
parent: RefCell<Weak<TreeNode>>,
children: RefCell<Vec<Rc<TreeNode>>>,
}
impl TreeNode {
pub fn new(value: i32) -> Rc<Self> {
Rc::new(TreeNode {
value,
parent: RefCell::new(Weak::new()),
children: RefCell::new(Vec::new()),
})
}
pub fn add_child(parent: &Rc<Self>, child: Rc<Self>) {
let children = parent.children.borrow_mut();
children.push(child.clone());
let parent_weak = Rc::downgrade(parent);
*child.parent.borrow_mut() = parent_weak;
}
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(p) = parent.upgrade() {
p.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::rc::{Rc, RefCell, Weak};
struct TreeNode {
value: i32,
parent: RefCell<Weak<TreeNode>>,
children: RefCell<Vec<Rc<TreeNode>>>,
}
impl TreeNode {
fn new(value: i32) -> Rc<Self> {
Rc::new(TreeNode {
value,
parent: RefCell::new(Weak::new()),
children: RefCell::new(Vec::new()),
})
}
fn add_child(parent: &Rc<Self>, child: Rc<Self>) {
parent.children.borrow_mut().push(child.clone());
child.parent.borrow_mut().replace(Rc::downgrade(parent));
}
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() {
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};
struct TreeNode {
value: i32,
parent: RefCell<Weak<TreeNode>>,
children: RefCell<Vec<Rc<TreeNode>>>,
}
impl TreeNode {
pub fn new(value: i32) -> Rc<Self> {
Rc::new(TreeNode {
value,
parent: RefCell::new(Weak::new()),
children: RefCell::new(Vec::new()),
})
}
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 {
if let Some(parent) = self.parent.borrow().upgrade() {
1 + parent.depth()
} else {
0
}
}
}
pub fn add_child(parent: &Rc<TreeNode>, child: Rc<TreeNode>) {
let mut children = parent.children.borrow_mut();
children.push(child.clone());
*child.parent.borrow_mut() = Rc::downgrade(parent);
}