-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathPowerSet from Set
More file actions
75 lines (68 loc) · 2.17 KB
/
PowerSet from Set
File metadata and controls
75 lines (68 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
Question: We are given a char array, we need to calculate the powerset of the char array
Source: http://www.geeksforgeeks.org/power-set/
Solution:
***************************** PowerSet Of IntegerArray UsingBitIncrement *********************************
package PowerSetFromSet;
import java.util.Scanner;
public class PowerSetOfIntegerArrayUsingBitIncrement {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try{
System.out.println("Enter the size of the integer array");
int n = in.nextInt();
System.out.println("Enter the elements of the integer array for powerset calculation");
int[] set = new int[n];
for(int i=0;i<n;i++)
set[i] = in.nextInt();
printPowerSet(set);
}
finally{
in.close();
}
}
private static void printPowerSet(int[] set) {
for(int i=0;i<(int)Math.pow(2,set.length);i++){
for(int j=0;j<set.length;j++){ // loop which checks which bit is set in integer i
if(((i)&(1<<j))!=0) // HandRun this to understand how to check for set bits in an integer
System.out.print(set[j]);
}
System.out.println();
}
}
}
/*
Analysis:
Time Complexity = O(n*2^n)
Space Complexity = O(1)*/
***************************** PowerSet Of CharacterArray UsingBitIncrement *******************************
package PowerSetFromSet;
import java.util.Scanner;
public class PowerSetOfChracterArrayUsingBitIncrement {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try{
System.out.println("Enter the string for powerset calculation");
String s = in.nextLine();
char[] set = s.toCharArray();
printPowerSet(set);
}
finally{
in.close();
}
}
private static void printPowerSet(char[] set) {
int totalElements = (int)Math.pow(2,set.length);
for(int i=0;i<totalElements;i++){
for(int j=0;j<set.length;j++){
if(((i) & (1<<j))!=0) // For each bit of integer i, check which of the bits are set.
// HandRun the above statement in if condition, to understand how to check for set bits in an integer
System.out.print(set[j]); // If bit is set, then print the corresponding character
}
System.out.println();
}
}
}
/*
Analysis:
Time Complexity = O(n*2^n)
Space Complexity = O(1)*/