我有以下函数来生成两个日期之间的随机日期:
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))
}
现在我尝试编写一个函数,它返回一个开始和结束日期,其大小为x的开始和结束之间的差异。我希望从我可以指定的离散分布中选择x,例如:
singleDay = .4
week = .1
month = .1
twoMonths = .1
year = .1
3Years = .1
over3Years = .1
这表示日期范围与1天的差异有40%的可能性。
ALSO
该函数的签名应为dateRange(endDate: LocalDate, daysBack: Integer)
例如我发送dateRange("2016-04-03", 600)
,现在返回大小为x的日期范围2016-04-03 - 600days AND 2016-04-03
这增加了一些范围的问题,如果范围要缩小则根本不可能产生,例如这个例子中的3年范围。
我的问题是如何在Scala中完成这个问题,我的问题是如何以惯用的方式构造一个descrite分布以及如何根据允许的输入范围来约束范围。
答案 0 :(得分:1)
试试这个
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
}