I have the following function to generate a random date between two dates:
val random = new Random(System.nanoTime)
def randomStartTime(days: Integer): LocalDateTime = {
// Uses to=today and randomly selects a from day maximum days back in time
val to = LocalDateTime.now()
val from = to.minusDays(days)
val diff = SECONDS.between(from, to)
from.plusSeconds(random.nextInt(diff.toInt))
}
Now I try to write a function that returns a start and end date with a diff between start and stop of size x. I want x to be selected from a discrete distribution that I can specify, for example:
singleDay = .4
week = .1
month = .1
twoMonths = .1
year = .1
3Years = .1
over3Years = .1
This says that there is a 40% chance of a date range diffing with 1day.
ALSO
the signature of the function should be dateRange(endDate: LocalDate, daysBack: Integer)
For example I send in dateRange("2016-04-03", 600)
, now return a daterange of size x between 2016-04-03 - 600days AND 2016-04-03
This adds the problem of some ranges are not possible to produce at all if the range is to narrow, for example the 3year range in this example.
The question I have is how this should be done in Scala, the problem im having is how to construct a descrite distribution in an idiomatic way and how to constrain the range based on the allowed input range.
Try this
def dateRange(date : String, daysBack : Int) : Int =
{
val listAvailable = List(1,7,daysInMonth(date), daysInTwoMonth(date), 365, 1095, 1095 + Math.abs(Random.nextInt)).filter(_ < daysBack)
val listDistribution = List(40.0,10.0,10.0,10.0,10.0,10.0,10.0).take(listAvailable.size)
val maxDistribution = listDistribution.sum
val listDistributionUpdated = listDistribution.map{distribution => (distribution * 100) / maxDistribution}
val value = Random.nextInt(100).toDouble
var index = 0
var found = false
var foundIndex = 0
var sumValue = 0.0
while(index < listDistribution.size && !found)
{
sumValue = sumValue + listDistribution(index)
if(sumValue >= value)
{
found = true
foundIndex = index
}
index = index + 1
}
listAvailable(foundIndex)
}
def daysInMonth(date String): Int =
{
//implement according to date 30 or 31
}
def daysInTwoMonth(date String): Int =
{
//implement
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments