There is a question in Elements of Programming Interviews that I have tried to solve but was unsuccessful.
Assume we are given an array of intervals of the form (d1, d2)
where d1
and d2
are values in degrees representing the start and end angles of an arc, where 0 degrees is the y-axis. These intervals can overlap, and you can have an interval like (350, 10)
. What is the minimum number of rays you can shoot to intersect all the intervals? A ray can be represented as an angle in degrees from the y-axis.
I've tried sorting by endpoints and seeing if each endpoint intersects wit hthe next interval, but I couldn't figure out how to deal with the overlapping intervals such as (340, 350), (350, 20)
.
create table
tab
of all used angles (interval edges)should contain only distinct angles
set all arcs as unused
find angle from
tab
which intersects most unused arc'sadd it as ray
exclude this angle from
tab
set all intersected rays as used
loop #2 until no unused arc or angle is left
This will significantly decrease the number of rays but will not ensure optimal solution !!! For really optimal solution you would need to use genere & test approach instead. Here some C++ code for this:
And overview:
As you can see it cast the rays through edge points if you need different rays you need to tweak this a bit (like use mid angle of the common overlap that would lead to more rays of coarse). The code is far from optimized I coded it just for fun right now ...
To improve this you can sort the lists and use ranged searches instead (similar to merging sorted lists) In current state of code there is no advantage taken from the sorting ...