Skip to content

Instantly share code, notes, and snippets.

@osgix
Created May 10, 2017 08:45
Show Gist options
  • Save osgix/d79d822685224b872e6b2509be3b34b1 to your computer and use it in GitHub Desktop.
Save osgix/d79d822685224b872e6b2509be3b34b1 to your computer and use it in GitHub Desktop.
Creating output of given names in order that each name is followed by other with starting letter same with preceding one.
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
public class ChainOfNames {
public static void main(String[] args) {
String[] names = new String[] { "Raymond", "Nora", "Daniel", "Louie", "Peter", "Esteban" };
String chainOfNames = createChain(names);
System.out.println(chainOfNames);
// outputs: Peter,Raymond,Daniel,Louie,Esteban,Nora
}
private static String createChain(String[] names) {
Map<String, String> firstCharacterIndex = new HashMap<>();
Map<String, String> lastCharacterIndex = new HashMap<>();
for (int i = 0; i < names.length; i++) {
String name = names[i];
String firstCharacter = getFirstCharacter(name);
String lastCharacter = getLastCharacter(name);
firstCharacterIndex.put(firstCharacter, name);
lastCharacterIndex.put(lastCharacter, name);
}
Deque<String> nameChain = new ArrayDeque<>();
String head = names[0];
String tail = names[0];
nameChain.add(names[0]);
while (nameChain.size() < names.length) {
String lastCharacter = getLastCharacter(tail);
if (firstCharacterIndex.containsKey(lastCharacter)) {
String nextName = firstCharacterIndex.get(lastCharacter);
nameChain.addLast(nextName);
tail = nextName;
} else {
String firstCharacter = getFirstCharacter(head);
if (lastCharacterIndex.containsKey(firstCharacter)) {
String nextName = lastCharacterIndex.get(firstCharacter);
nameChain.addFirst(nextName);
head = nextName;
}
}
}
return String.join(",", nameChain);
}
private static String getFirstCharacter(String name) {
return name.substring(0, 1).toLowerCase();
}
private static String getLastCharacter(String name) {
int nameLength = name.length();
return name.substring(nameLength - 1, nameLength).toLowerCase();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment