跟进我的previous bit-twiddling question ,现在我正在寻找减少使用那个方法的方法(尽管是一个无缓冲的版本,因为数组的生命只是这个对象)。这是 power set 的迭代器方法一些长碱基
;集合的实际内容未存储 - 这会占用大量内存,并且只有在想要遍历集合时才会对单个成员感兴趣 - 因此成员由迭代器生成。
但是,这些成员需要首先按大小顺序(而不是字典顺序)返回 - 即,按位数“排序”。
下面是我的(工作)第一次剪辑;优化成瘾者有什么建议吗?这个我敢肯定有更明显的削减。
public Iterator<Long> iterator() { return new Iterator<Long>(){
private boolean hasNext = true;
@Override public boolean hasNext() { return hasNext; }
private final long[] split = BitTwiddling.decompose(base);
int size = 0;
private long next = 0;
private long lastOfSize = 0;
private long firstOfSize = 0;
int[] positions = new int[split.length];
@Override
public Long next() {
long result = next;
if (next == lastOfSize) {
if (size == split.length) {
hasNext = false;
return result;
}
next = (firstOfSize |= split[size]);
lastOfSize |= split[split.length - ++size];
for(int i=0; i<size; i++) positions[i] = i;
} else {
if (positions[size-1] == split.length-1) {
int index = size-1;
int ref = split.length - 1;
while (positions[index] == ref) { index--; next ^= split[ref--]; }
next ^= split[positions[index]++];
next |= split[positions[index++]];
do {
next |= split[positions[index] = positions[index-1]+1];
} while (++index < size);
} else {
next ^= split[positions[size-1]++];
next |= split[positions[size-1]];
}
}
return result;
}
最佳答案
关于java - Java 中的位旋转 - 幂集,按大小排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3970784/