- Is there any ways to remove totalPermutationCount() from the interface because the only purpose of the method is to get permutationCombination value from the concrete class, if there are more concrete class or more instance variable then interface will become clumps and large.
- Is there any other best approach other than constructor to assign values to the instance variable, that the entire class depends on.
Refer to how I have used and please help me to get better.
Interface
interface Word {
void performPermutation();
int totalPermutationCount();
}
Interface Implementation
class WordImpl implements Word{
// "word" is to store the word from the user
private String word;
// "convert" is to convert the word into a char array to perform the logic
private char[] convert;
// "permutationCombination" is to find the total number of combination that is done
private int permutationCombination = 0;
// Constructor
public WordImpl(String wordCom){
setWord(wordCom);
}
//getter setter of word instance variable
public void setWord(String wordCom){
if(!wordCom.isEmpty() && wordCom.trim().length() > 0){
word = wordCom;
}else{
word = "Default";
}
convertToChar();
}
// convert the given word to char array
private void convertToChar(){
convert = new char[word.length()];
for(int i = 0 ; i < word.length() ; i++){
convert[i] = word.charAt(i);
}
}
public int totalPermutationCount(){
return permutationCombination;
}
// -------------------------------- Below is the Temporary Logic Ignore it ---------------------------------------------
private void performSwap(char[] list , int from, int to){
char temp;
temp = list[from];
list[from] = list[to];
list[to] = temp;
}
public void performPermutation(){
char[] list = convert;
Set<String> listData = new HashSet<>();
System.out.println(convert);
for (int i = 0 ; i < word.length() ; i++){
for (int j = i + 1 , reverse = i - 1 ; j < word.length() || reverse >= 0 ; j++ , reverse--){
if(j < word.length()){
performSwap(list,i,j);
System.out.println(convertToString(list));
list = convert;
permutationCombination++;
}
if(reverse >= 0 && i != 0){
performSwap(list,i,reverse);
System.out.println(convertToString(list));
list = convert;
permutationCombination++;
}
}
}
}
// ----------------------------------------------------------------------------------------
private String convertToString(char[] list){
String value = "";
for(int i = 0 ; i < word.length() ; i++){
value = value + list[i];
}
return value;
}}
Main Class
public class MyClass {
public static void main(String args[]) {
Word wordImplReference = new WordImpl("home");
wordImplReference.performPermutation();
System.out.println(wordImplReference.totalPermutationCount());
}
}
Aucun commentaire:
Enregistrer un commentaire