public List<String> fillNSlots(int n){ return fillNSlotsWithPrefix(0, n, ""); } private List<String> fillNSlotsWithPrefix(int counter, int n, String prefix){ if (counter==n-1){ return new ArrayList<String>(Arrays.asList(new String[]{prefix + "0", prefix + "1"})); }else{ List<String> result1 = fillNSlotsWithPrefix(counter+1, n , prefix + "0"); result1.addAll(fillNSlotsWithPrefix(counter+1, n , prefix + "1")); return result1; } }
It is not quite there, as there is still a need to hold an intermediate state with a temporary variable, result1 above, which could have been avoided had List supported an API which adds an element and returns itself or returns a new list.
The following is an equivalent implementation in scala:
def fillNSlots(n:Int):List[String] = { fillNSlotsWithPrefix(0,n,"") } def fillNSlotsWithPrefix(counter:Int, n: Int, prefix:String): List[String] = { if (counter==(n-1)) (prefix+"0")::(prefix+"1")::List() else fillNSlotsWithPrefix(counter+1, n, prefix+"0"):::fillNSlotsWithPrefix(counter+1, n, prefix+"1") }
No comments:
Post a Comment