actually I want to write all subsets of a given set in this way:
for example if my set is A:{1,2}
I want to have {}, {1}, {2}, {1,2}
this is what I tried:
static void printSubsets(java.util.Set<Integer> a) {
int n = a.size();
// Run a loop for printing all 2^n
// subset one by one
for (int i = 0; i < (1 << n); i++) {
System.out.print("{");
// Print current subset
for (int j = 0; j < n; j++) {
// (1<<j) is a number with jth bit 1
// so when we 'and' them with the
// subset number we get which numbers
// are present in the subset and which
// are not
if ((i & (1 << j)) > 0)
System.out.print(a.toArray()[j] + ",");
if (j == n - 1)
System.out.print(a.toArray()[j]);
}
System.out.print("} , ");
}
}
and this is the out put {}, {1,}, {2,}, {1,2,},
my problem is with ,
. I do not want to have ,
at the end of every subset and at the end of the whole output. Can you help me solve this problem to have a output like {}, {1}, {2}, {1,2}
? and at the end i want to sort them
If you are allow to use Guava you can take advantage of its Sets
class and Sets.combinations(Set<E> set, int size)
method:
static void printSubsets(Set<Integer> a) {
String combinations = IntStream.rangeClosed(0, a.size()).boxed()
.flatMap(i -> Sets.combinations(a, i).stream()
.sorted(Comparator.comparingInt(Collections::max)))
.map(subSet -> subSet.stream().sorted().map(String::valueOf)
.collect(Collectors.joining(",", "{", "}")))
.collect(Collectors.joining(" , "));
System.out.println(combinations);
}
Then:
Set<Integer> set = Set.of(1, 2);
printSubsets(set);
Output:
{} , {1} , {2} , {1,2}
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.