Wednesday, October 24, 2018

Find out possible short names for a given company name or a String

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class ShortNameGenerator {

public static void main(String[] args) {
String companyName = "Advitha Technoloigies";
showPossibleShortNames(companyName);
}

private static void showPossibleShortNames(String companyName) {
String words[] = companyName.split(" ");

List<Integer> indexes = new ArrayList<Integer>();
StringBuilder builder = null;
Set<String> shortNames = new LinkedHashSet<String>();
int wordTobeIncremented = 0;
String companyNameWithoutSpaces = companyName.replaceAll(" ", "");
while(true) {
builder = new StringBuilder();
for(int wordIndex = 0; wordIndex < words.length; wordIndex++) {
if(wordTobeIncremented == words.length) {
wordTobeIncremented = 0;
}
String word = words[wordIndex];
if(shortNames.isEmpty()) {
builder.append(word.charAt(0));
indexes.add(wordIndex, 1);
} else {
if(wordIndex == wordTobeIncremented) {
if(indexes.get(wordIndex) < word.length()) {
indexes.set(wordIndex, indexes.get(wordIndex) + 1);
}
}
builder.append(word.substring(0, indexes.get(wordIndex)));
}
}
if(!shortNames.isEmpty()) {
wordTobeIncremented++;
}
shortNames.add(builder.toString());
if(builder.toString().equalsIgnoreCase(companyNameWithoutSpaces)) {
break;
}
}
Iterator<String> shortNamesIterator = shortNames.iterator();
while(shortNamesIterator.hasNext()) {
System.out.println(shortNamesIterator.next());
}
}

}


Output:
---------
AT
AdT
AdTe
AdvTe
AdvTec
AdviTec
AdviTech
AdvitTech
AdvitTechn
AdvithTechn
AdvithTechno
AdvithaTechno
AdvithaTechnol
AdvithaTechnolo
AdvithaTechnoloi
AdvithaTechnoloig
AdvithaTechnoloigi
AdvithaTechnoloigie
AdvithaTechnoloigies