June 26, 2013 by Marco Cecconi
TL;DR: Not only I did get an answer by an egregious reader (hi Emmet!), but it was a really good one.
The way to solve the problem is to use an algorithm known as "earliest deadline first": you sort by ascending end date and then proceed in order, excluding the family members that overlap.
It's fairly easy to convince ourselves that it returns a optimal solution by following this line of reasoning.
Let's prove that it's exactly one:There are two possibilities. Either this subset overlaps with the rest of the visits, or it does not.
In both cases, of course, the best possible choice is our choice (it's the one the ends the earliest — leaves more days for the rest —and by construction it does not overlap with the rest of the set).
This is guaranteed to give us an optimal solution. ∎
My solution implements this line of thought and uses recursion:
public IEnumerable<Relative> ScheduleVisits(IEnumerable<Relative> visitRequests)
{
return SubSchedule(visitRequests.OrderBy(r => DateTime.Parse(r.End)));
}
private IEnumerable<Relative> SubSchedule(IEnumerable<Relative> input)
{
if (!input.Any()) return input;
var first = input.First();
return new[] { first }.Union(SubSchedule(input.SkipWhile(r => DateTime.Parse(r.Start) < DateTime.Parse(first.End))));
}
His solution, instead uses a straight for
loop. Much simpler!
public IEnumerable<Relative> ScheduleVisits(IEnumerable<Relative> visitRequests)
{
var orderedByEnd = visitRequests.OrderBy(v => DateTime.Parse(v.End));
var ret = new List<Relative>();
var prevEnd = DateTime.MinValue;
foreach (var request in orderedByEnd)
{
if (DateTime.Parse(request.Start) >= prevEnd)
{
ret.Add(request);
prevEnd = DateTime.Parse(request.End);
}
}
return ret;
}
And you, how did you solve it?
Hi, I'm Marco Cecconi. I am the founder of Intelligent Hack, developer, hacker, blogger, conference lecturer. Bio: ex Stack Overflow core team, ex Toptal EM.
Read moreMarch 12, 2023 by Marco Cecconi
Stack Overflow could benefit from adopting a using conversational AI to provide specific answers
Read moreOctober 15, 2021 by Marco Cecconi
Multiple people with my name use my email address and I can read their email, chaos ensues!
Read moreSeptember 29, 2021 by Marco Cecconi
After years of building, our top-notch consultancy to help start-ups and scale-ups create great, scalable products, I think it is high time I added an update to how it is going and what's next for us.
Read moreFebruary 03, 2021 by Marco Cecconi
A lesson in building communities by Stack Overflow's most prominent community manager emeritus, Shog9
Read moreDecember 02, 2020 by Marco Cecconi
Some lessons learned over the past 8 years of remote work in some of the best remote companies on the planet
Read more$ wget -O - hackurls.com/ascii | less
Read more…