{ 'a', 'b', 'c', 'd'}
then the answer should be
ab, ac, ad, bc, bd, abc, abd, acd, bcd, abcd.
Given below is the implementation:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package combinations; | |
import java.util.*; | |
import java.math.*; | |
public class combPowerSet { | |
//printing the charachters as per the number sent. | |
void printNumber(int number, char [] items) | |
{ | |
String digitString = Integer.toString(number); | |
char [] digitStringArray = digitString.toCharArray(); | |
int length = digitStringArray.length; | |
for ( int i=0; i<length; i++) | |
{ | |
System.out.print(items[Character.getNumericValue(digitStringArray[i])-1]); | |
} | |
System.out.println(); | |
} | |
//checking if the number follows the required pattern. | |
boolean checkCondition(int number, int itemSize) | |
{ | |
boolean validNumber = true; | |
String digitString = Integer.toString(number); | |
char [] digitStringArray = digitString.toCharArray(); | |
int length = digitStringArray.length; | |
for ( int i=0; i<length; i++) | |
{ | |
for( int j = i+1; j < length; j++) | |
{ | |
int x = Character.getNumericValue(digitStringArray[i]); | |
int y = Character.getNumericValue(digitStringArray[j]); | |
if (x > itemSize-1 || y > itemSize || x > y || x==y) | |
{ | |
validNumber = false; | |
break; | |
} | |
} | |
if (validNumber == false) break; | |
} | |
return validNumber; | |
} | |
void printCombinations(char [] items) | |
{ | |
double maxDigit = 0; | |
int itemSize = items.length; | |
for(int i=1; i<=itemSize; i++) | |
{ | |
maxDigit = maxDigit + i*Math.pow(10,itemSize-i); | |
} | |
for(int x=12; x<=maxDigit; x++) | |
{ | |
if(checkCondition(x, itemSize)) | |
{ | |
printNumber(x, items); | |
} | |
} | |
} | |
public static void main(String [] args) | |
{ | |
char [] arr = { 'a','b', 'c','d', 'e'}; | |
combPowerSet obj = new combPowerSet(); | |
obj.printCombinations(arr); | |
} | |
} |
No comments:
Post a Comment