Scala 生成随机日期范围,其中范围大小由离散分布决定
我使用以下函数在两个日期之间生成一个随机日期:Scala 生成随机日期范围,其中范围大小由离散分布决定,scala,Scala,我使用以下函数在两个日期之间生成一个随机日期: 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.minus
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
这意味着有40%的可能性日期范围随1天而变化
也
函数的签名应该是dateRange(endDate:LocalDate,daysBack:Integer)
例如,我发送日期范围(“2016-04-03”,600)
,现在返回大小为x的日期范围,介于2016-04-03-600天和2016-04-03之间
,这增加了一个问题,即如果范围缩小,一些范围根本不可能产生,例如本例中的3年范围
我的问题是如何在Scala中实现这一点,我的问题是如何以惯用的方式构造描述分布,以及如何根据允许的输入范围约束范围。试试这个
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
}
def dateRange(日期:字符串,daysBack:Int):Int=
{
val listAvailable=列表(1,7,daysInMonth(日期),DaysInToMonth(日期),365,1095,1095+Math.abs(Random.nextInt)).filter((distribution*100)/maxDistribution}
val值=Random.nextInt(100).toDouble
var指数=0
发现的var=false
var foundIndex=0
var sumValue=0.0
while(索引=值)
{
找到=真
foundIndex=索引
}
索引=索引+1
}
listAvailable(foundIndex)
}
def daysInMonth(日期字符串):Int=
{
//按照日期30或31执行
}
def daysInTwoMonth(日期字符串):Int=
{
//实施
}