fninfected(map:&str)->f64{#[derive(Debug)]enumCell{Uninfected,Infected,Ocean,}letmutmap:Vec<_>=map.chars().map(|c|matchc{'0'=>Cell::Uninfected,'1'=>Cell::Infected,'X'=>Cell::Ocean,_=>panic!("Illegal cell type {}",c),}).collect();fnpropagate<'a>(cells:implIterator<Item=&'amutCell>){letmutinfecting=false;forcellincells{matchcell{Cell::Uninfected=>{ifinfecting{*cell=Cell::Infected;}}Cell::Infected=>{infecting=true;}Cell::Ocean=>{infecting=false;}}}}propagate(map.iter_mut());propagate(map.iter_mut().rev());letmutinfected=0usize;letmuttotal=0usize;forcellinmap{matchcell{Cell::Uninfected=>{total+=1;}Cell::Infected=>{total+=1;infected+=1;}Cell::Ocean=>{}}}iftotal==0{0.0}else{100.0*infectedasf64/totalasf64}}fnmain(){assert_eq!(infected("01000000X000X011X0X"),73.33333333333333);assert_eq!(infected("01X000X010X011XX"),72.72727272727273);assert_eq!(infected("XXXXX"),0.0);assert_eq!(infected("00000000X00X0000"),0.0);assert_eq!(infected("0000000010"),100.0);assert_eq!(infected("000001XXXX0010X1X00010"),100.0);assert_eq!(infected("X00X000000X10X0100"),42.857142857142854);}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Rust: