You are an aerial firefighter (someone who drops water on fires from above in order to extinguish them) and your goal is to work out the minimum amount of bombs you need to drop in order to fully extinguish the fire (the fire department has budgeting concerns and you can't just be dropping tons of bombs, they need that money for the annual Christmas party).
The given string is a 2D plane of random length consisting of two characters:
x representing fire
Y representing buildings
Water that you drop cannot go through buildings and therefore individual sections of fire must be addressed separately. Your water bombs can only extinguish contiguous sections of fire up to a width (parameter w). You must return the minimum number of waterbombs it would take to extinguish the fire in the string.
Note: all inputs will be valid.
Examples
"xxYxx" and w = 3 --> 2 waterbombs needed
"xxYxx" and w = 1 --> 4
"xxxxYxYx" and w = 5 --> 3
"xxxxxYxYx" and w = 2 --> 5
Tests
waterbombs("xxxxYxYx", 4)
waterbombs("xxYxx", 3)
Good luck!
This challenge comes from coderors on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (20)
Python solution 🐍
Regexp was my first thought too
Javascript:
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
sum
function to simplify your solution.Thanks for your simplify code snippets.
But I want to make my code snippets readable :).
In C with O(n):
Rust:
JS solution with just a regular expression:
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 ;)
JS Solution:
Quite more complex Python, although I love the regex option
C
Assuming the input for the fire area is always correct.
Test