I want to split a bitset in more chunks. The splitting function depends on the cardinality of the bitset, which is the number of bits set to true. For example I have this BitSet with the cardinality 4:
INPUT: 101101
The desired output is the following:
OUTPUT: 100000 - 001000 - 000100 - 000001
Using the Java library called BitSet is there a function or a possible way to achieve that?
The following code applies every possible mask with a single bit set and only keeps the non-zero results:
int[] split(int input) {
return IntStream.iterate(Integer.reverse(1), mask -> mask >>> 1)
.limit(Integer.SIZE)
.map(mask -> input & mask)
.filter(result -> result != 0)
.toArray();
}
Yes. Using basic operation AND.
Basicaly:
xxxxxx AND 110000 = xx0000.
Repeat procedure for all subsequences.
You need some loops here:
You should to find the positions of 1 then you can make a loop like this :
then If the position exist in the List then print 1 else print 0
public static void main(String[] args) {
String Input = "101101";
//find positions
List<Integer> listPositivePosition = new ArrayList<>();
for(int i = 0; i<Input.length(); i++){
if(Input.charAt(i)=='1'){
listPositivePosition.add(i);
}
}
for(int i = 0; i<listPositivePosition.size(); i++){
for(int j = 0; j<Input.length(); j++){
//If the position exist in the List then print 1 else print 0
if(j == listPositivePosition.get(i)){
System.out.print("1");
}else{
System.out.print("0");
}
}
System.out.println();
}
}
Hope this can help you.
Please forgive my method naming convention :)
public static void main(String[] args) {
final String a = "100100";
System.out.println(Arrays.toString(foo(a)));
}
private static String[] foo(String a) {
final long counted = IntStream.range(0, a.length()).filter(i -> a.charAt(i) == '1').count();
final String[] ret = new String[(int) counted];
int index = 0;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == '1') {
ret[index] = ret(a, i);
index++;
}
}
return ret;
}
private static String ret(String a, int i) {
final StringBuilder sb = new StringBuilder(a.replaceAll(".", "0"));
sb.setCharAt(i, '1');
a = sb.toString();
return a;
}
Pure Java and easy-to-read solution:
List<String> binSplitter(String input) {
String str = new String(new char[input.length()]).replace("\0", "0");
List<String> chunks = new ArrayList<>();
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '1') {
chunks.add(str.substring(0, i) + "1" + str.substring(i + 1, input.length()));
}
}
return chunks;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.