DEV Community

loading...

Discussion on: Daily Challenge #306 - Largest Possible Product

Collapse
qm3ster profile image
Mihail Malo

Rust

#![feature(array_windows)]
pub fn adjacent_product1(nums: &[usize]) -> Option<usize> {
    nums.array_windows().map(|[a, b]| a * b).max()
}
Enter fullscreen mode Exit fullscreen mode

on stable you have the options of instead doing:

pub fn adjacent_product(nums: &[usize]) -> Option<usize> {
    nums.windows(2)
        .filter_map(|slice| match slice {
            [a, b] => Some(a * b),
            _ => None,
        })
        .max()
}
Enter fullscreen mode Exit fullscreen mode

or

pub fn adjacent_product(nums: &[usize]) -> Option<usize> {
    nums.windows(2)
        .map(|slice| match slice {
            [a, b] => a * b,
            _ => unreachable!(), // this could panic at runtime if it could actually be reached
        })
        .max()
}
Enter fullscreen mode Exit fullscreen mode

which produce identical assembly to each other in release mode (meaning the compiler proves different sized slices unreachable without your help)

Generic:

#![feature(array_windows)]
use std::{cmp::Ord, ops::Mul};
pub fn adjacent_product<'a, T: 'a, R>(nums: &'a [T]) -> Option<R>
where
    R: Ord,
    &'a T: Mul<Output = R>,
{
    nums.array_windows().map(|[a, b]| a * b).max()
}
Enter fullscreen mode Exit fullscreen mode

Haha square meters go brr

#[derive(Debug)]
struct M(u8);
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct M2(u16);
impl Mul<Self> for &M {
    type Output = M2;
    fn mul(self, rhs: Self) -> M2 {
        M2((self.0 as u16) * (rhs.0 as u16))
    }
}
fn main() {
    let pogs = [4, 1, 3, 3, 2].map(M);
    println!("{:?} {:?}", &pogs, adjacent_product(&pogs));
}
Enter fullscreen mode Exit fullscreen mode