We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Hackerland Radio Transmitters
Hackerland Radio Transmitters
Sort by
recency
|
421 Discussions
|
Please Login in order to post a comment
Maybe not the shortest or most efficient solution but I'm sharing anyway because it illustrates the use of loop invariants (the loop maintains a certain condition). Because of the loop invariant, I was able to debug it without a debugger or even print statements.
The idea behind my algo is to start at the leftmost house, go to the rightmost house I can place an antenna, and then go to the rightmost house that is covered by that antenna I placed.
So how did I implement this? I set up the variables
landiso that in every iteration of the while loop I can be sure that an antenna placed at housex[i]will reach houselor that the antenna placed at houselwill reach housex[i]. For example, in the first iteration,lis the leftmost house andi=0sox[i]is also the leftmost house. In this instance, an antenna placed at housex[i]will certainly reach houselbecause they're the same house.So that condition is the loop invariant. Then, when I need to update
landi, I just need to make sure I don't violate the loop invariant. I initially had a bug in my code because of how I updatediandlwhen I went too far right. But I was able to debug without a debugger or even print statements because I just asked myself if loop invariant is still true after the variable update.Hope the code below is clear and that this has been helpful!
def hackerlandRadioTransmitters(x, k): x = sorted(set(x)) count = 0 next_start = -float('inf')
In Python, don't forget to run set on the house locations ("x") first. We only need to order the unique house locations.
Java. Not the best solution, I think, but it works.