我正在尝试实现一个功能:
def NumberPartition(InputNum:Int,outputListSize:Int):List[Range]
这样:
NumberPartition(8,3)=List(Range(0,3),Range(3,6),Range(6,8))
即。它会创建n-1
等长范围(长度= ceil(InputNum/outputListSize)
)加上最后一个/第一个稍小的范围。
我想使用这个函数来聚集一个令人尴尬的并行程序,该程序由n个子程序组成,这些子程序将由n
任务/线程进行批处理。
在Scala中执行此操作的最惯用方法是什么?
我认为使用Range步骤可能会有所帮助:
def rangeHeads(n:Int,len:Int):Range=Range(0,n,ceil(n/len))//type conversion for ceil() omitted here.
rangeHeads(8,3)//Range(0, 3, 6)
我只需要一个(1,2,3,4)->((1,2),(2,3),(3,4))
答案 0 :(得分:2)
虽然这不是您正在寻求的确切输出,但也许这将是一个很好的指导:
scala> def numberPartition(inputNum: Int, outputListSize: Int): List[List[Int]] = {
(0 to inputNum).toList.grouped(outputListSize).toList
}
numberPartition: numberPartition[](val inputNum: Int,val outputListSize: Int) => List[List[Int]]
scala> numberPartition(8, 3)
res0: List[List[Int]] = List(List(0, 1, 2), List(3, 4, 5), List(6, 7, 8))
答案 1 :(得分:0)
def roundedUpIntDivide(a:Int,b:Int):Int=a/b + (if(a%b==0) 0 else 1)
def partitionToRanges(n:Int,len:Int): List[(Int, Int)] ={
(Range(0,n,roundedUpIntDivide(n,len)):+n)
.sliding(2)
.map(x => (x(0),x(1)))
.toList
}
感谢@jwvh建议sliding()
答案 2 :(得分:0)
def numberPartition(inputNum: Int, outputListSize: Int): List[(Int, Int)] = {
val range = 0.until(inputNum).by(inputNum/outputListSize + 1).:+(inputNum)
range.zip(range.tail).toList
}
注意:
0.until(inputNum)
是独家范围[0, inputNum)
; .by(inputNum/outputListSize + 1)
是步骤; .:+(inputNum)
它会加回范围上限; range.zip(range.tail)
从列表中构建情侣,等于.sliding(2).map { case Seq(x,y) => (x,y) }