Scala 从一个范围到另一个范围采样
我想使用另一个Scala 从一个范围到另一个范围采样,scala,scala-collections,Scala,Scala Collections,我想使用另一个范围对一个范围进行“采样”。例如: def sample(in: Range, by: Range): Range = ??? // note: Range equals broken! assert(sample(3 to 10 , 1 to 2 ).toVector == (4 to 5 ).toVector) assert(sample(3 to 10 , 1 to 4 by 2).toVector == (4 to 6 by 2).toVe
范围
对一个范围
进行“采样”。例如:
def sample(in: Range, by: Range): Range = ???
// note: Range equals broken!
assert(sample(3 to 10 , 1 to 2 ).toVector == (4 to 5 ).toVector)
assert(sample(3 to 10 , 1 to 4 by 2).toVector == (4 to 6 by 2).toVector)
assert(sample(3 to 10 by 2, 1 to 2 ).toVector == (5 to 7 by 2).toVector)
assert(sample(3 to 10 by 2, 1 to 4 by 2).toVector == (5 to 9 by 4).toVector)
如何定义
示例
方法?这里是一个尝试。我还没有测试所有可能的组合。为简单起见,by
参数的起点必须大于或等于零,并且必须有一个正步长
def sample(in: Range, by: Range): Range = {
val drop = by.start
val stepM = by.step
require(drop >= 0 && stepM > 0)
val in1 = in.drop(drop)
val in2 = if (stepM == 1)
in1
else if (in1.isInclusive) // copy-method is protected :(
new Range.Inclusive(start = in1.start, end = in1.end, step = in1.step*stepM)
else
new Range (start = in1.start, end = in1.end, step = in1.step*stepM)
in2.take(by.size)
}
通过将
sample
返回类型更改为IndexedSeq[Int]
,得到了这个简单的解决方案
def sample(in: Range, by: Range): IndexedSeq[Int] = {
in intersect (in.start+by.start to in.start+by.end by by.step)
}
它搜索in
和by
之间的交集,并在in.start
中移动
对于相应重构的断言,这两个
assert(sample(3 to 10 , 1 to 2 ) == (4 to 5 ))
assert(sample(3 to 10 , 1 to 4 by 2) == (4 to 6 by 2))
这两个都失败了
assert(sample(3 to 10 by 2, 1 to 2 ) == (5 to 7 by 2)) // intersect at 5 only
assert(sample(3 to 10 by 2, 1 to 4 by 2) == (5 to 9 by 4)) // empty intersect
我的尝试变得太混乱了,试图在所有情况下都是正确的。