Skip to main content

Find time from time ranges (including overlapping ranges)

 This is a very simple problem. In this trying to find a given time from ranges of times. So, I have a collection which stores different time ranges (including overlapping time ranges). The job is to find or search if a time provided by user exists in time ranges collection.

Example: Let's assume I have following collections of time ranges:

1. 07:00 - 09:00 
2. 13:45 - 15:15
3. 16:25 - 18:10
4. 08:30 - 10:00

Now, need to find if time 09:30 is present in that collection or not. If it finds it shall print true, otherwise false. Similarly it can be use to check other times too.

Solution: To store time ranges, what I did is converted start and end time to decimal numbers respectively and stored them in STL's set (multiset) used to address overlapping ranges. As we know that set data structure in STL is a tree (Red Black Tree / Balanced Binary tree). 

Time Complexity: 
1. set::insert - If N elements are inserted, Nlog(size+N). Implementations may optimize if the range is already sorted. (Reference: set::insert)
2. set::find - Logarithmic in size (size of the set). (Reference: set::find)

The set templates signature in STL is like below:
template < class T,                        // set::key_type/value_type
           class Compare = less<T>,        // set::key_compare/value_compare
           class Alloc = allocator<T>      // set::allocator_type
           > class set;

It has a template argument key_compare. So, we need to provide a compare function which will do comparison with respect to ranges and sort (using strict weak ordering) while storing ranges as well as help us to find if a time is part of any range(s) stored in the set.

To solve this I have followed a structure like header only library and used it in main.cpp. A namespace config has been used to control if seconds need to be processed to generate decimal or not. To do so used inline global variable in config namespace which helped to decouple configuration from API to find date in ranges.

Solution Code:
 // mylib.h
#ifndef MYLIB
#define MYLIB

#include <iostream>
#include <iomanip>
#include <set>
#include <sstream>
#include <string>

using std::tm;
using std::istringstream;
using std::string;
using std::multiset;
using std::pair;

namespace my_lib
{
namespace config
{
inline bool compute_seconds = false;
}

typedef pair<double, double> timeranges;
struct timeRangeCompare
{
bool operator()(const timeranges& lvalue, const timeranges& rvalue) const
{
return lvalue.second < rvalue.first;
}
};

bool isInRange(const multiset<timeranges, timeRangeCompare>& iRanges, 
                double value)
{
return iRanges.find(timeranges(value, value)) != iRanges.end();
}

double convert_StringTime(string& s)
{
std::tm tm;
istringstream ss(s);
double fNumber = 0.;

if (!config::compute_seconds)
{
ss >> std::get_time(&tm, "%H:%M");
fNumber = tm.tm_hour + (tm.tm_min / 60.0);
}
else
{
ss >> std::get_time(&tm, "%T");
fNumber = tm.tm_hour + (tm.tm_min / 60.0) + (tm.tm_sec / 3600.0);
                        /* The construct (tm.tm_min / 60.0) may results in warning 
                       'The left operand of '/' is a garbage value' by clang-tidy tool. 
                        In that case we can replace "%T" format to "%H:%M:%S"*/
}
return fNumber;
}
}

#endif

// main.cpp
#include "mylib.h"

using std::cout;
using std::string;
using std::boolalpha;

int main()
{
    // This part deals with time ranges including overlapping
    multiset<my_lib::timeranges, my_lib::timeRangeCompare> rangesObj;

    // Time range: 1
    string sStartTime{"10:15"};
    string sEndTime{ "12:15" };
    double fStartTime = my_lib::convert_StringTime(sStartTime);
    double fEndTime = my_lib::convert_StringTime(sEndTime);
    rangesObj.insert(my_lib::timeranges(fStartTime, fEndTime));

    // Time range: 2
    sStartTime = "14:30";
    sEndTime = "15:15";
    fStartTime = my_lib::convert_StringTime(sStartTime);
    fEndTime = my_lib::convert_StringTime(sEndTime);
    rangesObj.insert(my_lib::timeranges(fStartTime, fEndTime));

    // Time range: 3. 
    // This is overlapping range with Time range 1(above)
    my_lib::config::compute_seconds = true; // Now seconds will be used to compute number

    sStartTime = "11:30:45";
    sEndTime = "12:40:23";
    fStartTime = my_lib::convert_StringTime(sStartTime);
    fEndTime = my_lib::convert_StringTime(sEndTime);
    rangesObj.insert(my_lib::timeranges(fStartTime, fEndTime));

    // Now check a time if it's within a range 
    // Should display true as it's already in range
    string sTimeToCheck{ "12:10:00" };
    double dToCheck = my_lib::convert_StringTime(sTimeToCheck);
    cout << boolalpha << my_lib::isInRange(rangesObj, dToCheck) << "\n";

    // This one isn't in time slots hence must return false;
    sTimeToCheck = "16:30:00";
    dToCheck = my_lib::convert_StringTime(sTimeToCheck);
    cout << boolalpha << my_lib::isInRange(rangesObj, dToCheck) << "\n";

    return 0;
}

*** VS-2019 is used with flag set to /std:c++17.

Comments

Popular posts from this blog

XOR (Exclusive OR) for branchless coding

The following example shows the array reversing using the  XOR operator . No need to take any additional variable to reverse the array.   int main(int argc, _TCHAR* argv[]) { char str[] = "I AM STUDENT"; int length = strlen(str); for(int i = 0; i < ((length/2)); i++) { str[i] ^= str[length - (1+i)]; str[length - (1+i)] ^= str[i]; str[i] ^= str[length - (1+i)]; } cout << str << endl; return 0; } The above example is one of the uses of XOR but XOR comes in handy when we can do branchless coding  methods like butterfly switch etc. Sometimes this is very effective in speeding up the execution.  Let's see one of the uses of XOR in branchless coding. I am taking a simple example of Y = | X |.  Yes, I am generating abs of a supplied number. So, my function signature/definition in C++ looks like below: int absoluteBranch( int x) {     if (x < 0 ) {         return ...

Reversing char array without splitting the array to tokens

 I was reading about strdup, a C++ function and suddenly an idea came to my mind if this can be leveraged to aid in reversing a character array without splitting the array into words and reconstructing it again by placing spaces and removing trailing spaces. Again, I wanted an array to be passed as a function argument and an array size to be passed implicitly with the array to the function. Assumed, a well-formed char array has been passed into the function. No malformed array checking is done inside the function. So, the function signature and definition are like below: Below is the call from the client code to reverse the array without splitting tokens and reconstructing it. Finally, copy the reversed array to the destination.  For GNU C++, we should use strdup instead _strdup . On run, we get the following output: Demo code

Power of Two

  I n this post will be discussing how to calculate if a number is a power of two or not. As an example, 8 is a power of two but the number 10 is not. There are many ways we can solve this. First , we will take an approach which is simple and iterative. In this case, we will calculate the power of two one by one and check with the supplied number. The below code illustrates it. bool isPowerofTwo(unsigned num) { auto y = 1; while (0 != y) { if (num == y) return true; if (num < y) return false; y <<= 1; } return false; } Second , assuming, the number is a 32-bit number, this is also an iterative solution. In this scenario, iterating all bits and counting the set bits. Any number which is a power of 2 will have only one bit set and the rest will be zeros. As an example, 8 in binary representation is 1000. Using this observation, we can implement an iterative solution. bool isPowerofTwo(unsigned num) { auto one_count = 0; for (auto index = 0; index < ...