1
\$\begingroup\$

I have a list of timestamp tuples of the form List((startTime,endTime)), which are basically denoting periods of time throughout the day.

For example:

(("2016-03-28 14:00:00","2016-03-28 15:00:00"),
 ("2016-03-28 17:00:00","2016-03-28 21:00:00"), 
 ("2016-03-28 01:00:00","2016-03-28 13:00:00"))

I want to get a list of the durations which are not included in this list.

So the output should be:

(("2016-03-28 00:00:00","2016-03-28 01:00:00"),
 ("2016-03-28 13:00:00","2016-03-28 14:00:00"),
 ("2016-03-28 15:00:00","2016-03-28 17:00:00"),
 ("2016-03-28 17:00:00","2016-03-28 24:00:00"))

Can anyone suggest a good and efficient way of doing that in Scala?

The naive solution that I've tried so far is as follows:

import java.sql.Timestamp
import scala.collection.mutable.ListBuffer

def comparator(first: (Timestamp,Timestamp), second: (Timestamp, Timestamp)) = first._2.getTime <= second._1.getTime

val data = List((Timestamp.valueOf("2016-03-28 00:00:00"),Timestamp.valueOf("2016-03-28 10:00:00")),
  (Timestamp.valueOf("2016-03-28 12:00:00"),Timestamp.valueOf("2016-03-28 15:00:00")),
  (Timestamp.valueOf("2016-03-28 23:00:00"),Timestamp.valueOf("2016-03-28 23:59:59")),
  (Timestamp.valueOf("2016-03-28 16:00:00"),Timestamp.valueOf("2016-03-28 21:00:00"))
).sortWith(comparator)

var emptySlots = new ListBuffer[(Timestamp,Timestamp)]()
var currTime = Timestamp.valueOf("2016-03-28 00:00:00")
var index = 0
var cond = 0
while(cond == 0){

  if (currTime.compareTo(Timestamp.valueOf("2016-03-28 23:59:59")) < 0 && index >= data.size){
    emptySlots += ((currTime,Timestamp.valueOf("2016-03-28 23:59:59") ))
    cond = 1
  }
  else if(index >= data.size)
  {
    cond = 1
  }
  else if(currTime.compareTo(data(index)._1) < 0) {
    emptySlots += ((currTime, data(index)._1))
    currTime = data(index)._2
    index += 1
  }
  else if(currTime.compareTo(data(index)._1) >= 0 && currTime.compareTo(data(index)._2) < 0 ) {
    currTime = data(index)._2
    index += 1
  }
  else if(currTime.compareTo(data(index)._1) > 0 && currTime.compareTo(data(index)._2) > 0 ) {

    index += 1
  }

}

emptySlots.toList
\$\endgroup\$
  • 1
    \$\begingroup\$ Does your code produce the output you want it to? \$\endgroup\$ – Quill Mar 29 '16 at 5:27
  • \$\begingroup\$ Yes, it produces the correct output. but I am looking forward to some other approach which does not use the "var". And may use some filter or other scala functions. \$\endgroup\$ – Sumit Paliwal Mar 29 '16 at 6:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.