val javaBitSet = new java.util.BitSet(5)
javaBitSet.set(0)
javaBitSet.set(1)
javaBitSet.set(3)
javaBitSet.flip(0, 5)
javaBitSet: java.util.BitSet = {2, 4}
你如何习惯性地使用Scala BitSet做到这一点? (为什么这不是一种方法?)
答案 0 :(得分:4)
scala> import collection.immutable.BitSet
import collection.immutable.BitSet
您删除的示例会翻转第2位,但会将第5位关闭:
scala> BitSet(1,2,3) &~ BitSet(2,5)
res3: scala.collection.immutable.BitSet = BitSet(1, 3)
但逻辑xor就是你想要的:
scala> BitSet(1,2,3) ^ BitSet(2,5)
res4: scala.collection.immutable.BitSet = BitSet(1, 3, 5)
或惯用
scala> implicit class `flipper of bits`(val bs: BitSet) extends AnyVal {
| def flip(lo: Int, hi: Int): BitSet = BitSet(lo until hi: _*) ^ bs
| }
defined class flipper$u0020of$u0020bits
scala> BitSet(2,5) flip (1,4)
res5: scala.collection.immutable.BitSet = BitSet(1, 3, 5)
表示“扩展方法”。从范围构建BitSet
效率不高,因为它会调用+
n次。更好的是选择从数组创建的位集的子范围,如下所示。这些箍表明,如你所要求的那样,对远程操作有内置支持会很好。
更新
对于非平凡范围,最好不要从BitSet
创建Range
。
scala> import collection.immutable.BitSet
import collection.immutable.BitSet
scala> val bs = BitSet(1, 69, 188)
bs: scala.collection.immutable.BitSet = BitSet(1, 69, 188)
scala> val lower = 32
lower: Int = 32
scala> val upper = 190
upper: Int = 190
scala> val n = (bs.last max upper) / 64 + 1
n: Int = 3
scala> val arr = Array.tabulate(n)(_ => -1L)
arr: Array[Long] = Array(-1, -1, -1)
scala> val mask = BitSet.fromBitMaskNoCopy(arr).range(lower, upper)
mask: scala.collection.immutable.BitSet = BitSet(32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189)
scala> val res = bs ^ mask
res: scala.collection.immutable.BitSet = BitSet(1, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 189)
scala> res(69)
res0: Boolean = false