Interview Question
Java DevelopersCountry: United States
Interview Type: Phone Interview
Does Map<K,V> return the entries in sorted order of the keys? If not, then you will get the wrong answer.
Tested and works.
/*Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz".
For numbers which are multiples of both three and five print "FizzBuzz".
Additionally, instead of printing "Fizz" or "Buzz", create a lookup such that 3 --> "Fizz", 5 --> "Buzz", 7 --> "Woof" and so on. The signature of the method would be:
List<String> fizzbuzz(int start, int end, Map<Integer, String> lookups) { ..}
The expected output is of the format : 15:FizzBuzz, 21:FizzWoof, 105: FizzBuzzWoof, etc*/
public static void fizzBuzzStuffs() {
boolean is3 = false, is5 = false, is7 = false;
String out = "";
for (int i = 0; i < 100; i++) {
is3 = isMultOf(i, 3);
is5 = isMultOf(i, 5);
is7 = isMultOf(i, 7);
out = "";
if (!is3 && !is5 && !is7) {
System.out.println(i);
} else {
out = "";
if (is3){out += "Fizz"; }
if (is5){out += "Buzz"; }
if (is7){out += "Wolf"; }
System.out.println(out);
}
}
}
public static boolean isMultOf(int val, int mult) {
return val%mult == 0;
}
public static void main(String[] args) {
Map<Integer, String> lookups = new HashMap<Integer, String>();
lookups.put(3, "Fizz");
lookups.put(5, "Buzz");
lookups.put(7, "Wolf");
fizzbuzz(-10, 120, lookups);
}
public static List<String> fizzbuzz(int start, int end, Map<Integer, String> lookups) {
List<String> list = new ArrayList<String>(end-start+1);
Set<Entry<Integer, String>> entrySet = lookups.entrySet();
String out = "";
for (int i = start; i < end+1; i++) {
out = i+": ";
for (Entry<Integer, String> entry: entrySet) {
if (isMultOf(i, entry.getKey())){
out+= entry.getValue();
}
}
list.add(i-start, out);
System.out.println(out);//TODO for testing purposes.
}
return list;
}
public static boolean isMultOf(int val, int mult) {
return val%mult == 0;
}
What is wrong with this answer:
- java.strat October 16, 2013