Skip to content

Instantly share code, notes, and snippets.

@programaths
Created July 30, 2015 17:51
Show Gist options
  • Save programaths/b0c6779f4b122246c1a1 to your computer and use it in GitHub Desktop.
Save programaths/b0c6779f4b122246c1a1 to your computer and use it in GitHub Desktop.
import java.text.DateFormat
import java.time.LocalDate
import java.util
import java.util.*
/*
Given a list of people with their birth and end years (all between 1900 and 2000),
find the year with the most number of people alive.
See http://qr.ae/RAG2zH
*/
data class dates(val start:LocalDate,val end: LocalDate);
data class dateTag(val date:LocalDate,val opening:Boolean);
fun mostPeopleAlive(dates: List<dates>):Pair<Int,Int>{
if(dates.size()==0) return Pair(0,0)
val sortedTaggedDates=dates
.flatMap { t-> listOf(dateTag(t.start,true),dateTag(t.end,false)) }
.sortBy( comparator { a, b -> a.date.compareTo(b.date) })
var opened=0
var closed=0;
var lastDate=sortedTaggedDates.get(0).date
var lastYear=Int.MIN_VALUE
var maxValue=0
var maxYear=lastDate.getYear()
for(i in sortedTaggedDates.indices){
if(sortedTaggedDates[i].opening){
opened++;
}
if(!sortedTaggedDates[i].opening){
closed++;
}
if(opened>maxValue){
maxValue=opened
maxYear=sortedTaggedDates[i].date.getYear()
}
if(lastYear!=sortedTaggedDates[i].date.getYear()){
lastYear=sortedTaggedDates[i].date.getYear()
opened-=closed;
closed=0;
}
}
return Pair(maxYear,maxValue);
}
fun main(args:Array<String>){
var dates=arrayOf(
dates(start = LocalDate.of(2001,1,1),end = LocalDate.of(2002,5,1)),
dates(start = LocalDate.of(2001,2,1),end = LocalDate.of(2003,1,1)),
dates(start = LocalDate.of(2001,3,1),end = LocalDate.of(2003,3,1)),
dates(start = LocalDate.of(2001,5,1),end = LocalDate.of(2001,10,1)),
dates(start = LocalDate.of(2002,1,1),end = LocalDate.of(2003,2,1)),
dates(start = LocalDate.of(2001,6,1),end = LocalDate.of(2002,3,1)),
dates(start = LocalDate.of(2002,4,1),end = LocalDate.of(2002,7,1)),
dates(start = LocalDate.of(2001,7,1),end = LocalDate.of(2002,6,1))
);
print(mostPeopleAlive(dates.asList()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment