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)
- }
- }
#[cfg(test)] mod tests { use super::*; use rand::prelude::*; #[test] fn test_some() { let mut rng = thread_rng(); for _ in 0..100 { let mut forest: [[char; 10]; 10] = [['🌲'; 10]; 10]; let i = rng.gen_range(0..10); let j = rng.gen_range(0..10); forest[i][j] = '🍄'; assert_eq!(forest.position_2d('🍄'), Some((i, j))); } } #[test] fn test_none() { let forest: [[char; 10]; 10] = [['🌲'; 10]; 10]; assert_eq!(forest.position_2d('🍄'), None); } }
- #[cfg(test)]
- mod tests {
- use super::*;
- use rand::prelude::*;
- #[test]
- fn test_some() {
- let mut rng = thread_rng();
- for _ in 0..100 {
let mut forest: [[char;10];10] = [['🌲';10];10];- let mut forest: [[char; 10]; 10] = [['🌲'; 10]; 10];
- let i = rng.gen_range(0..10);
- let j = rng.gen_range(0..10);
- forest[i][j] = '🍄';
assert_eq!(find_the_magick_mushroom(forest), Some((i, j)));- assert_eq!(forest.position_2d('🍄'), Some((i, j)));
- }
- }
- #[test]
- fn test_none() {
let forest: [[char;10];10] = [['🌲';10];10];- let forest: [[char; 10]; 10] = [['🌲'; 10]; 10];
assert_eq!(find_the_magick_mushroom(forest), None);- assert_eq!(forest.position_2d('🍄'), None);
- }
}- }
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)
- }