fnwater_bombs(spec:&str,width:usize)->usize{letresult=spec.split("Y")// split into sections// for each section, see how many bombs it takes to handle:.map(|xs|((xs.len()asf64)/(widthasf64)).ceil().trunc()asusize)// sum:.fold(0,|acc,n|acc+n);result}fnmain(){assert_eq!(water_bombs("xxYxx",2),2);assert_eq!(water_bombs("xxYxx",1),4);assert_eq!(water_bombs("xxxxYxYx",5),3);assert_eq!(water_bombs("xxxxYxYx",2),4);assert_eq!(water_bombs("xxxxxYxYx",2),5);assert_eq!(water_bombs("xxxxYxYx",4),3);assert_eq!(water_bombs("xxYxx",3),2);}
It seems to be a simple yet interesting also..
The idea to find the minimum number of waterbombs can be found by :
say Test: waterbombs("xxxxYxYx", 4)
step1 : split first param by 'Y'
step2: set second param as width
step3: find the mod of length of substring by width value
step4: sum up the mod value that is your minimum number of waterbombs
Step 3 is not quite correct, I think; you'd need to get the ceiling of the width of the string divided by the width of the bomb. ("xxxxx", 2) is 3, since two bombs will take out 4 squares of fire and leave 1 more to mop up.
E: My JS solution
var waterbombs = (fireString, bombWidth) => {
const fires = fireString.split("Y");
let bombsNeeded = 0;
for (let fire in fires) {
bombsNeeded += Math.ceil(fire.length / bombWidth);
}
return bombsNeeded;
}
Python solution 🐍
Regexp was my first thought too
Javascript:
Rust:
Here is the simple solution with Python and it uses math.ceil, a for loop and a string splitting:
You can use the built-in
sumfunction to simplify your solution.Thanks for your simplify code snippets.
But I want to make my code snippets readable :).
In C with O(n):
It seems to be a simple yet interesting also..
The idea to find the minimum number of waterbombs can be found by :
say Test: waterbombs("xxxxYxYx", 4)
step1 : split first param by 'Y'
step2: set second param as width
step3: find the mod of length of substring by width value
step4: sum up the mod value that is your minimum number of waterbombs
Step 3 is not quite correct, I think; you'd need to get the ceiling of the width of the string divided by the width of the bomb. ("xxxxx", 2) is 3, since two bombs will take out 4 squares of fire and leave 1 more to mop up.
E: My JS solution
yes, you are right brother
Talk is cheap, show me the code ;)
C
Assuming the input for the fire area is always correct.
Test
Quite more complex Python, although I love the regex option
JS Solution:
JS solution with just a regular expression:
Nim:
Javascript solution
this is a 1D plane