Skip to content

Instantly share code, notes, and snippets.

@avianey
Last active April 25, 2020 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avianey/3f65a0f48f27ab433c001d8b3f47108e to your computer and use it in GitHub Desktop.
Save avianey/3f65a0f48f27ab433c001d8b3f47108e to your computer and use it in GitHub Desktop.
Kotlin extensions for java BitSet, with shift left, shit right and shift intersect
infix fun shr(n: Int) {
require(n >= 0) { "'n' must be >= 0" }
if (n == 0 || words.isEmpty()) { return }
val step = n / 64
val shift = n % 64
if (shift == 0 && step == 0) { return }
for (i in words.indices) {
words[i] = when {
i < words.size - 1 - step -> {
if (shift == 0) { words[i + step] }
else { (words[i + step] ushr shift) or (words[i + step + 1] shl (64 - shift)) }
}
i == words.size - 1 - step -> {
words[i + step] ushr shift
}
else /* i > word.size - 1 - step */ -> {
0
}
}
}
}
fun shrIntersect(n: Int, other: BitSet): Boolean {
require(n >= 0) { "'n' must be >= 0" }
if (n == 0 || words.isEmpty()) { return intersects(other) }
val step = n / 64
val shift = n % 64
if (shift == 0 && step == 0) { return intersects(other) }
for (i in words.indices) {
val word = when {
i < words.size - 1 - step -> {
if (shift == 0) { words[i + step] }
else { (words[i + step] ushr shift) or (words[i + step + 1] shl (64 - shift)) }
}
i == words.size - 1 - step -> {
words[i + step] ushr shift
}
else /* i > word.size - 1 - step */ -> {
0
}
}
if (other.words[i] and word != 0L) {
return true
}
}
return false
}
infix fun shl(n: Int) {
require(n >= 0) { "'n' must be >= 0" }
if (n == 0 || words.isEmpty()) { return }
val step = n / 64
val shift = n % 64
if (shift == 0 && step == 0) { return }
for (i in words.size - 1 downTo 0) {
words[i] = when {
i > step -> {
if (shift == 0) { words[i - step] }
else { (words[i - step] shl shift) or (words[i - step - 1] ushr (64 - shift)) }
}
i == step -> {
words[i - step] shl shift
}
else /* i < step */ -> {
0
}
}
}
}
fun shlIntersect(n: Int, other: BitSet): Boolean {
require(n >= 0) { "'n' must be >= 0" }
if (n == 0 || words.isEmpty()) { return intersects(other) }
val step = n / 64
val shift = n % 64
if (shift == 0 && step == 0) { return intersects(other) }
for (i in 0 until min(words.size, other.words.size)) {
val word = when {
i > step -> {
if (shift == 0) { words[i - step] }
else { (words[i - step] shl shift) or (words[i - step - 1] ushr (64 - shift)) }
}
i == step -> {
words[i - step] shl shift
}
else /* i < step */ -> {
0
}
}
if (other.words[i] and word != 0L) {
return true
}
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment