独家或N位集之间 [英] Exclusive or between N bit sets

查看:160
本文介绍了独家或N位集之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现使用位集在Java程序,我被困在下面的操作:

I am implementing a program in Java using BitSets and I am stuck in the following operation:

给定N位集返回一个位集合与0,如果有多于1之一的所有位集,否则为1

Given N BitSets return a BitSet with 0 if there is more than 1 one in all the BitSets, and 1 otherwise

作为一个例子,假设我们有这3套:

As an example, suppose we have this 3 sets:


  • 10010

  • 01011

  • 00111

  • 10010
  • 01011
  • 00111

11100期望的结果

11100 expected result

有关以下几组:


  • 10010

  • 01011

  • 00111

  • 10100

  • 00101

  • 10010
  • 01011
  • 00111
  • 10100
  • 00101

01000期望的结果

01000 expected result

我试图做到这一点的独家使用逐位操作,我已经意识到我需要的是字面上的唯一或全部集之间,而不是在一个迭代的方式,
所以我十分赞同做什么难住了。这甚至可能?

I am trying to do this exclusive with bit wise operations, and I have realized that what I need is literally the exclusive or between all the sets, but not in an iterative fashion, so I am quite stumped with what to do. Is this even possible?

我想,以避免检查每组每一位,并保持一个计数器在每个位置上昂贵的解决方案...

I wanted to avoid the costly solution of having to check each bit in each set, and keep a counter for each position...

感谢您的帮助。

编辑:有些人问,这是一个项目,我工作的一部分。我建立一个时间表发生器和软约束的根本之一就是没有学生应该只有1班1天,所以那些设置重新present与会学生中的每个小时,我想过滤的谁只有1级。

Edit : as some people asked, this is part of a project I'm working on. I am building a time table generator and basically one of the soft constraints is that no student should have only 1 class in 1 day, so those Sets represent the attending students in each hour, and I want to filter the ones who have only 1 class.

推荐答案

您可以做你想要与两个值是什么。一个具有设置至少一次的位,第二个有那些设置不止一次。的组合可用于确定这些设置一次,没有更多的

You can do what you want with two values. One has the bits set at least once, the second has those set more than once. The combination can be used to determine those set once and no more.

int[] ints = {0b10010, 0b01011, 0b00111, 0b10100, 0b00101};
int setOnce = 0, setMore = 0;
for (int i : ints) {
    setMore |= setOnce & i;
    setOnce |= i;
}
int result = setOnce & ~setMore;
System.out.println(String.format("%5s", Integer.toBinaryString(result)).replace(' ', '0'));

打印

01000

这篇关于独家或N位集之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆