r/dailyprogrammer • u/jnazario 2 0 • Mar 18 '15
[2015-03-18] Challenge #206 [Intermediate] Maximizing Crop Irrigation
Description
You run a farm which isn't doing so well. Your crops that you planted aren't coming up, and your bills are bigger than your expected proceeds. So, you have to conserve water and focus instead on the plants that are growing. You have a center pivot watering system which has a rotating sprinkler around a central pivot, creating a circular watered area. For this challenge, you just have to decide where to locate it based on this year's crops.
Some notes:
- Because this is a simple grid, we're only dealing with integers in this challenge.
- For partially covered squares, round down: the sprinkler covers the crop if the distance from the sprinkler is less than or equal to the sprinklers radius.
- If you place the sprinkler on a square with a crop, you destroy the crop so handle accordingly (e.g. deduct 1 from the calculation).
- If in the event you find two or more placements that yield identical scores, pick any one of them (or even emit them all if you so choose), this is entirely possible.
Input Description
You'll be given three integers (h w r) which correspond to the number of rows (h) and columns (w) for the ASCII map (respectively) and then the radius (r) of the watering sprinkler. The ASCII map will have a "." for no crop planted and an "x" for a growing crop.
Output Description
You should emit the coordinates (0-indexed) of the row and column showing where to place the center of the sprinkler. Your coordinates should be integers.
Challenge Input
51 91 9
......x...x....x............x............x.................................x...............
.........x...........x...................x.....x...........xx.............x................
...........x.................x.x............x..........................x................x..
......x...x.....................x.....x....x.........x......x.......x...x..................
.x...x.....x................xx...........................x.....xx.....x............x.......
.....xx.......x..x........x.............xx........x.......x.....................x.......x..
...x..x.x..x......x..............................................................x...x.....
........x..x......x......x...x.x....x.......x........x..x...........x.x...x..........xx....
...............x.x....x...........x......x.............x..........................x........
...................x........x..............................................................
..x.x.....................................x..x.x......x......x.............................
......x.............................................................................x..x...
......x....x...............x...............................................................
............x.............x.............................x...............x................x.
..xx........xx............x...x......................x.....................................
........x........xx..............x.....................x.x.......x........................x
.......x....................xx.............................................................
............x...x.........x...xx...............x...........................................
.............................x...............xx..x...........x....x........x...x.......x.x.
..........x.......................x.....................................x..................
...xx..x.x..................x........................x.....................x..x.......x....
.............xx..........x...............x......................x.........x.........x....x.
...............................x.....................x.x...................................
...................x....x............................x...x.......x.............x....x.x....
.x.xx........................x...................................x.....x.......xx..........
.......x...................................................................................
.........x.....x.................x.................x...x.......x..................x........
.......x................x.x...................................x...xx....x.....x...x........
..............................................x..................x.........................
............................x........x.......x............................................x
..x.............x.....x...............x............x...x....x...x..........................
.......................xx.................x...................x...................x.......x
.x.x.............x....x.................................x...........x..x..........x.....x..
...x..x..x......................x...........x..........x.............xxx....x..........x...
...........................................................x...............................
x......x.....x................x...............x....................................x.......
..x...........................x............x..........x....x..............................x
.......................x.......xx...............x...x.x.................x..x............x..
x................x.......x........x.............................x.x.x...................x.x
.......................x...x.......................................................x.......
.x..................x.....x..........................................x...........x.........
.x...................x........x.................x..........xx..................x..x........
.x..........x...x...........................x.x....................x..x.......x............
.............x...x..................x................x..x.x.....xxx..x...xx..x.............
.x...................x.x....x...x.................x.............................x.....x....
......................x.x........x...........x...................................x......x..
................x....................................x....x....x......x..............x..x..
......x.........................................x..x......x.x.......x......................
.x..............................x..........x.x....x.................x......................
x..x...........x..x.x...x..........................................x..............xx.......
..xx......x.......x.x.................x......................................x.............Bonus
Emit the map with the circle your program calculated drawn.
Credit
This challenge was inspired by a question on IRC from user whatiswronghere.
Notes
Have a cool idea for a challenge? Submit it to /r/DailyProgrammer_Ideas!
6
u/Godspiral 3 3 Mar 18 '15 edited Mar 18 '15
In J, makes a circle function of indexes in a square, then cuts map into squares with maximum circle indexes. (doesn't adjust if center is destroyed because only one was at maximum)
map =. '.x' i. > cutLF wdclippaste '' NB. input to boolean
cutoff drawing,
4
u/adrian17 1 4 Mar 18 '15
(Python 3) First a solution: this is definitely not an intended way of solving this - I'm taking every point and trying out a couple of random points around it. It's obviously based on luck and can sometimes not find the best solution. Why this way? Look below.
Output:
Okay, rambling starts here. So i thought "what if we could place the sprinkler on any real coordinate, like in real world?" (or "what if the coordinates are big enough that a simple iteration over all points is impossible") Here are a couple of solutions:
First one looks for the best one by checking random points and, when it finds them, look around these more, in case it finds a better point nearby - so it's basically a Monte Carlo method. (My solution above is actually a simplified version of this one). Solution (37 crops): image, zoomed image. Solution for at least 35 crops coverage: image - you can see it covering (11, 10), the original solution.
The second one is quite slow, as it's basically iterating over every point in a dense grid, then plots the results for all the points: image. I absolutely love how this map looks; if you put the real map under this plot, it would be a really useful map in real life :D
The last one was /u/XenophonOfAthens's (...I think) idea: as the best area is always limited by the "circles" around each point (as seen on the map above), the only points you have to check are the ones on the circle around each point, and more specifically, on intersections of these circles. Works nicely, nothing really to say about it.
1
u/Godd2 Mar 18 '15
For clarification, does the sprinkler with radius 1 only water the tile that the sprinkler is on or also the top, left, right, and bottom tiles?
vs
3
u/lukz 2 0 Mar 18 '15
vbscript
I wanted to do a simple solution. I just search for the maximum coverage of the fields. I did an improved output, it shows a map with + marking the sprinkler position and * marking all irrigated crops. I also prepared a set of simple tests.
Simple tests
Code
3
u/adrian17 1 4 Mar 18 '15 edited Mar 18 '15
Ugly J. Naive iteration over all coordinates. edit: removed unboxing in tight loop. I thought that it would speed it up just a bit, but nope.
Result:
3
u/dohaqatar7 1 1 Mar 18 '15
A neat bonus you could add:
Accept a list of radii and then execute as normal (should be interesting because of overlapping regions of the circles).
3
u/chunes 1 2 Mar 18 '15 edited Mar 18 '15
Java with bonus. Efficiency is O( hw*4r2 ) because I'm using bounding boxes of size radius. As long as 4r2 is less than hw, there are savings. Worst case would be O( h2 * w2 ) if the circle's bounding box is big enough to cover the entire field.
Output:
3
u/marchelzo Mar 18 '15
Solution in Python with time complexity O( w h r2 ). I use a dictionary with
(col, row)coordinates as keys, and the number of crops reached by the sprinkler at those coordinates as values. For each crop, I increment the dictionary value of surrounding squares. At the end, the key with the maximum value is the coordinate pair of the optimal sprinkler location.3
u/NasenSpray 0 1 Mar 20 '15
C++ AMP, because why not
Output:
Description:
I wanted to create a solution that runs all of the processing on the GPU:
CPU is only doing input/output.
5
u/KevinTheGray Mar 18 '15 edited Mar 18 '15
Here's my solution in Swift.
Also, what's the solution? I probably messed something up. I screwed up my x's and y's quite a few times doing this.
My output:
2
u/krismaz 0 1 Mar 18 '15
In Nim. It's a rather horrible worst case Θ(h2 w2 ).
I guess circular range search could be used instead.
2
u/Lyrrad0 Mar 18 '15
Here's my Java solution. It's a bit inefficient ( O(h2 w2 ))
Solution:
2
u/semsemdavinci Mar 18 '15 edited Mar 18 '15
A bit lengthy, I know.. But what do you think? any suggestions? here's my solution on python:
and output:
2
u/Godd2 Mar 18 '15 edited Mar 19 '15
Here's mine in Ruby. It runs in O(pr2 + wh) where p is the number of plants in the field, r is the radius of the sprinkler, and w and h are the width and height of the field respectively.
I prefabricate a set of relative indices that a sprinkler could water, then I iterate over every tile, and if it's a plant, I add one to every tile surrounding the plant that could water that plant (unless the tile is outside the field, of course).
This cuts out calculation for barren tiles, but I have to add wh in case the field is huge and completely barren, in which case I at least have to check if every tile is a plant (so it could be bigger than pr2 ). Worst case is that every tile is a plant, in which case it's O(whr2 ).
Output
Edit: Here is a refactored version of the code which is much more readable: https://github.com/nicklink483/dailyprogrammer/blob/master/206/intermediate.rb
2
u/[deleted] Mar 18 '15 edited Mar 18 '15
My solution in C.
Complexity: O( H W Radius² ) ---- (Suggestions on how to improve this?)
TIL a really important lesson: using i,j as variables for iterating is a really bad idea when the problem is relatively complex.
I struggled with a bug for about 10 minutes, then decided to use row, col, v_shift and h_shift instead of i,j,k,l and it was so much easier.
Fun problem, thanks!
3
u/wizao 1 0 Mar 18 '15 edited Mar 18 '15
Bonus Haskell:
Result:
1
u/[deleted] Mar 18 '15 edited Mar 18 '15
Python 2: Greedy search
1
u/liaobaishan Mar 18 '15
ruby:
output:
1
u/minikomi Mar 19 '15 edited Mar 19 '15
Racket (without input parsing.. full version here) :
1
u/kirsybuu 0 1 Mar 19 '15
D Language with bonus
Challenge Output:
1
u/cauchy37 Mar 19 '15 edited Mar 19 '15
My C++11 solution. Pointing out any mistakes and/or errors are appreciated.
edit: fixed some things.
And the result:
1
u/Scara95 Mar 19 '15 edited Mar 19 '15
That's my (suboptimal) Nial solution. It cuts map and apply a mask obtained in a way similar to the J solution.
Edit: This is output:
1
u/mdscruggs Mar 20 '15 edited Mar 20 '15
I've been working on a Python (currently 3.x) genetic algorithm library (for fun) and even though this problem is better solved with direct solutions, wanted to try it out.
Here's the module where I implement the solution as a GA (the source code is also here):
1
u/Scroph 0 0 Mar 20 '15
My solution in the C language. At first I wanted to make the data structures local to the main function and pass them to the others as arguments when needed, but it soon got messy and ended up making them global.
Output :
1
u/fbWright Mar 22 '15
Python 3
What I do is first calculating for every point how many crops can be reached from that point (actually, I find every crop and add 1 to each point that can be reached from there, and then subtract 1 from all the crops tiles), then I iterate through the map and find the best point.
For fun I wanted to see a gradient map of the irrigation; it was actually rather simple adding that (4 lines), and it shows some interesting patterns.
1
u/franza73 Mar 22 '15 edited Mar 23 '15
Perl solution
Output:
1
u/h2g2_researcher Mar 23 '15
So I do these on my lunch breaks at work. That means more complex ones can take me longer. Anyway...
For this one I decided to go a bit extra. A brute force search, in this case, still works within a few seconds, but with O(hwr*r) complexity it becomes problematic on very large grids or large radii. (Doubling the search resolution would make it take 16 times longer!) This is made more problematic by the way that storing an array of arrays to keep the data has terrible cache performance.
So the first thing I did was write a class to swizzle the data using texture swizzling, and store everything in a single buffer. The
TiledArrayclass is a window into this buffer and allows lookup using x/y co-ordinates. The effect of swizzling is the data is recursively split into tiles, each tile is contiguous memory. This makes reading everything near a certain point (like a circle) far more cache friendly.My next thought was that I could analyse each tile to count the plants on each one. Then I could do a search starting on the densest tiles and moving to the less dense ones, until I get to tiles with not enough plants on them, and did an analysis to create a "size cache" which can tell you the number of plants on any given tile.
The problem with this, I realised, was that it would only really work with very small radii circles (because I can only reject tiles if the circle fits entirely within the tile) and with large amounts of clumping neither of which really applied: whatever order I searched in, I would end up searching the entire grid anyway. What's more: by just accepting that I will search the entire grid I can easily split it into multiple threads and use threading to speed up the search 4-fold instead. (More, if I have more hardware threads.)
The next thing I realised was when I was writing the code to count the number of plants within a given circle: I could use the size cache to speed this up. By checking if a tile lay entirely within the circle I could short-circuit much of the search. I'd only have to examine individual squares close to the edges, but could take broad strokes around the centre.
As such, the search cost can be reduced to (I believe) log(r) instead r*r. This means massive grids can be far more efficiently searched.
(Many of these techniques shamelessly pilfered from texture processing algorithms, by the way.)
My code is here: http://pastebin.com/tyjH2M9u
1
u/[deleted] Apr 05 '15 edited Apr 05 '15
Here is a solution in Rust. I am not sure if it's correct but I am creating a square around the dot with a side equal to the radius. I am then checking for each dot of the square if it is in the circle and if it is a 'x' to add it's score to the overall around the dot.
EDIT: The answer for a radius of 9 is 34 at 10,11.
1
u/broken_broken_ May 07 '15
Just a reminder: the mathematical formula to check whether a point p(px, py) is inside a circle C with center c(cx, cy) and radius r is the following:
But because computing square roots is slow, it is way faster for the computer to do this:
which is mathematically equivalent.
Just saw some codes using the first formula instead of the second, you might gain some performances!
0
u/[deleted] Mar 18 '15
[deleted] — view deleted comment
0
u/[deleted] Mar 20 '15
[deleted] — view deleted comment