Ad
Code
Diff
  • trait Array2d<T: PartialEq> {
        fn position_2d(&self, element: T) -> Option<(usize, usize)>;
    }
    
    impl<T: PartialEq, const I: usize, const J: usize> Array2d<T> for [[T; I]; J] {
        fn position_2d(&self, element: T) -> Option<(usize, usize)> {
            use itertools::Itertools;
            (0..I)
                .cartesian_product(0..J)
                .find(|&(i, j)| self[i][j] == element)
        }
    }
    • fn find_the_magick_mushroom(forest: [[char;10];10]) -> Option<(usize, usize)> {
    • forest
    • .into_iter()
    • .enumerate()
    • .map(|(i, row)| row.into_iter().enumerate().map(move |(j, plant)| ((i, j), plant)))
    • .flatten()
    • .find(|&(_, plant)| plant == '🍄')
    • .map(|(coords, _)| coords)
    • trait Array2d<T: PartialEq> {
    • fn position_2d(&self, element: T) -> Option<(usize, usize)>;
    • }
    • impl<T: PartialEq, const I: usize, const J: usize> Array2d<T> for [[T; I]; J] {
    • fn position_2d(&self, element: T) -> Option<(usize, usize)> {
    • use itertools::Itertools;
    • (0..I)
    • .cartesian_product(0..J)
    • .find(|&(i, j)| self[i][j] == element)
    • }
    • }
Code
Diff
  • use std::ops::{Add, Sub, Mul, Div};
    
    fn calculator<T, C>(operator: C, lhs: T, rhs: T) -> T
    where
        T: Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T>,
        C: Into<char>,
    {
        let op = match operator.into() {
            '+' => T::add,
            '-' => T::sub,
            '*' => T::mul,
            '/' => T::div,
            _ => unimplemented!(),
        };
        op(lhs, rhs)
    }
    • fn calculator(operator: char, num1: i32, num2: i32) -> i32 {
    • match operator {
    • '+' => num1 + num2,
    • '-' => num1 - num2,
    • '*' => num1 * num2,
    • '/' => num1 / num2,
    • _ => panic!("Invalid operator: '{operator}'.")
    • }
    • use std::ops::{Add, Sub, Mul, Div};
    • fn calculator<T, C>(operator: C, lhs: T, rhs: T) -> T
    • where
    • T: Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T>,
    • C: Into<char>,
    • {
    • let op = match operator.into() {
    • '+' => T::add,
    • '-' => T::sub,
    • '*' => T::mul,
    • '/' => T::div,
    • _ => unimplemented!(),
    • };
    • op(lhs, rhs)
    • }