我需要给定2个单独的来访者匹配,这是通过案例类定义的2个到达顺序。
我还定义了一个contains函数,该函数根据返回布尔值的开始时间和结束时间将一个元素与另一个元素进行比较。
我需要以产生3个序列的方式拆分2个序列,例如:
我有一个通过partition
函数的解决方案的一部分:
def contains(as: Seq[websiteVisitsWindow], bs: Seq[websiteVisitsWindow]): (Seq[websiteVisitsWindow], Seq[websiteVisitsWindow]) = {
bs match {
case Seq() => (Nil, as)
case bs => as.partition(a => bs.exists(b => b.contains(a)))
}
}
这会在上方产生点1和2
contains(a,b)
res2: (Seq[websiteVisitsWindow], Seq[websiteVisitsWindow]) =
(List(websiteVisitsWindow(1,1,2)),List(websiteVisitsWindow(0,0,1),
websiteVisitsWindow(3,3,11)))
case class websiteVisitsWindow(start: Int, end: Int, visitors: Int) {
def contains(other: websiteVisitsWindow): Boolean = other.start >= this.start && other.end <= this.end
}
val a = Seq(websiteVisitsWindow(start = 0, end = 0, visitors = 1), websiteVisitsWindow(start = 1, end = 1, visitors = 2), websiteVisitsWindow(start = 3, end = 3, visitors = 11))
val b = Seq(websiteVisitsWindow(start = 1, end = 1, visitors = 2), websiteVisitsWindow(start = 4, end = 4, visitors = 60))
我需要的结果是:
(List(websiteVisitsWindow(1,1,2)),List(websiteVisitsWindow(0,0,1),
websiteVisitsWindow(3,3,11)), List(websiteVisitsWindow(4,4,60))
我已经有一个函数定义:
def intersectionAndLeftOver(as: Seq[websiteVisitsWindow], bs: Seq[websiteVisitsWindow]): (Seq[websiteVisitsWindow], Seq[websiteVisitsWindow], Seq[websiteVisitsWindow])
有人问我可以将其作为递归来执行,此刻,我只是想获得不递归的序列结果,然后从那里去。
我尝试了以下操作:
def intersectionAndLeftOver(as: Seq[websiteVisitsWindow], bs: Seq[websiteVisitsWindow]): (Seq[websiteVisitsWindow], Seq[websiteVisitsWindow], Seq[websiteVisitsWindow]) = {
(as, bs) match {
case (Nil, Nil) => (Nil, Nil, Nil)
case (_, Nil) => (Nil, as, Nil)
case (Nil, _) => (Nil, bs, Nil)
case (as, bs) =>
(as.partition(a => bs.exists(b => b.contains(a))), as.filter(a => !(bs.exists(b => b.contains(a)) )))
}
}
当然,结果返回的是(分区,Seq),而不是返回的类型(Seq,Seq,Seq)。
答案 0 :(得分:0)
我现在有一个可以“工作”的解决方案:
def intersectionAndLeftOver(as: Seq[websiteVisitsWindow], bs: Seq[websiteVisitsWindow]): (Seq[websiteVisitsWindow], Seq[websiteVisitsWindow], Seq[websiteVisitsWindow]) = {
(as, bs) match {
case (Nil, Nil) => (Nil, Nil, Nil)
case (_, Nil) => (Nil, as, Nil)
case (Nil, _) => (Nil, bs, Nil)
case (as, bs) =>
(as.intersect(bs), as.diff(bs), bs.diff(as))
}
}
它没有像执行递归方式那样优化,我可以看到它何时会中断(例如,如果1个序列仅具有开始/结束但所有访问者值都设置为0,而另一个序列具有正确设置的所有信息),稍后需要解决