Restart
Restart

Reputation: 57

How to write an algorithm to sort specified objects?

In my scenario,i have the following objects

<playlist>
  <program id="s63e" start="2011-8-24 16:00:00" end="2011-8-24 17:00:00" priority="2" />
  <program id="sv6w" start="2011-8-24 19:00:00" end="2011-8-24 21:00:00" priority="2" />
  <program id="3b9a" start="2011-8-26 11:00:00" end="2011-8-26 13:00:00" priority="0" />
</playlist>

I wanna sort them by both time and priority.But my mind was totally twisted.

As u can see, a program object have its own timezone,and a priority.

program usually executes when their start time reached ,and end their execution when its end time reached.

But only one program is allowed to execute at one timezone,let's say, when higher priority program is executing,the lower one can't be launched.

A lower priority value has a higher priority.

The sorting result should return the value whose type is Dictionary<DateTime,string> ,the dictionary simply stores which time executes which program, Any thinking way or sorting algorithm is appreciated.

Upvotes: 0

Views: 132

Answers (2)

Daniel B
Daniel B

Reputation: 2887

You have multiple problems / questions, so, let's break it down. I would do the following:

  1. Parse each "program" record into a simple object, with relevant properties for each XML attribute. The result would be an unsorted list of the new class you just created, e.g. List<ProgramEntry>.
  2. Implement an IComparer which compares 2 instances of the above objects, and decides which one comes before the other in a sorted list. There are many examples on how to do this. This is where you would implement your priority vs. timezone logic, so e.g. you could have your comparer check if there is an overlap in start and end times, and if so, use priority to resolve the conflict.
  3. Sort the list created in 1. using this IComparer. This is as simple as saying myList.Sort(MyComparer);. List.Sort automatically uses an efficient algorithm and only invokes your comparison code as few times as possible. (please use proper naming conventions, this is just an example). During the comparison, you could also flag the "losing" record as disabled by setting a property on it.
  4. Add all items from your sorted list to a dictionary, where it hasn't been flagged as disabled.

This is just one way of doing it, I am sure you can come up with other ones, or ones that use a different priority algorithm to determine which records get flagged as disabled (e.g. is one 3-hour long entry with priority 2 better than three 1-hour long records that it overlaps with?).

Upvotes: 1

user557419
user557419

Reputation:

You can use LINQ to both group the items by priority and then sort them by time.

Upvotes: 1

Related Questions