I need a way to represent information about Weeks and Days as such:
W1: D1,D2
W2: D1,D5
W3: D3,D2
so that, given my current week and day, I should be able to get the previous day and next day
For ex:
if(currentDay = W2D5)
{
prevDay = W2D1;
nextDay = W3D3;
}
Here are two options I came up with:
-
Use a treemap
TreeMap< Integer,TreeMap< Integer>>
In the outer tree map, store the week number as the key and in the inner tree map, store the
- Use an array
[w1d1,w2d2,w2d1…]
What would be a good data structure to use for such a problem?
Why not just a well-ordered collection on a WeekDay type? (The WeekDay type includes a Week and a Day and provides well-defined ordering.)
If this were the case,
TreeSet<WeekDay>could be used withhigher/lower(or evenheadSet/tailSet).UnfortunatelyTreeSet<WeekDay>(orPriorityQueue) and other standard data-types won’t work because they lack a method of iterating forward/back from a given element. This isn’t strictly true, at leastTreeMapcan be used, just with aO(1)manual look-up using the iterator: however, the required operations to take advantage of theO(lg n)access just aren’t “standard” in aTreeSet.This article on Sorted Lists in Java covers a bunch of interesting things, as well as providing an implementation which could be adapted.Of course, it is also possible to just use an
ArrayListand keep it sorted on update. In that case aCollections.binarySearchcan be used and the index for prev/next are easily provided 🙂Happy coding.