Skip to content

Instantly share code, notes, and snippets.

@fouad-j
Last active December 29, 2015 18:41
Show Gist options
  • Save fouad-j/ba17ea78ea300034f0bc to your computer and use it in GitHub Desktop.
Save fouad-j/ba17ea78ea300034f0bc to your computer and use it in GitHub Desktop.
import java.util.Map;
import java.util.TreeMap;
public class FooBarQix {
// TreeMap sort key 3 > 5 > 7 for priority
private static final TreeMap<Integer, String> FOOBARQIX = new TreeMap<Integer, String>() {{
put(7, "Qix");
put(3, "Foo");
put(5, "Bar");
}};
public static void main(String[] args) {
// final result of algorithm
String result = "";
// current nbr in loop for traitement
String currentNbr;
for (int i=1; i<=100 ; i++) {
currentNbr = null;
// divisors first
currentNbr = stringFromDiv(i);
currentNbr += stringFromNbr(i);
// if current nbr has no divier and no numbre, we keep its value
if(currentNbr.isEmpty()){
currentNbr = String.valueOf(i);
}
result += currentNbr;
result +="\n";
}
System.out.println(result);
}
private static String stringFromNbr(int nbr){
StringBuilder out = new StringBuilder();
// convert nbr to string and then to array character for replace char by char
for(char c : String.valueOf(nbr).toCharArray()){
// check if nbr is in FOOBARQIX
if(FOOBARQIX.containsKey(Character.getNumericValue(c))){
out.append(FOOBARQIX.get(Character.getNumericValue(c)));
}
}
return out.toString();
}
private static String stringFromDiv(int nbr){
StringBuilder out = new StringBuilder();
// parse FOOBARQIX and we check if nbr has divider
for(Map.Entry<Integer,String> entry : FOOBARQIX.entrySet()) {
if(nbr % entry.getKey() == 0){
out.append(entry.getValue());
}
}
return out.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment