Generating all combinations with repetition using MATLAB

We can use the bijection mentioned in the wikipedia article, which maps combinations without repetition of type n+k-1 choose k to k-multicombinations of size n. We generate the combinations without repetition and map them using bsxfun(@minus, nchoosek(1:n+k-1,k), 0:k-1);. This results in the following function: function combs = nmultichoosek(values, k) %// Return number of multisubsets or … Read more

Variable amount of nested for loops

Recursion can solve this problem neatly: function callManyTimes(maxIndices, func) { doCallManyTimes(maxIndices, func, [], 0); } function doCallManyTimes(maxIndices, func, args, index) { if (maxIndices.length == 0) { func(args); } else { var rest = maxIndices.slice(1); for (args[index] = 0; args[index] < maxIndices[0]; ++args[index]) { doCallManyTimes(rest, func, args, index + 1); } } } Call it like … Read more

Combinatoric ‘N choose R’ in java math?

The Formula It’s actually very easy to compute N choose K without even computing factorials. We know that the formula for (N choose K) is: N! ——– (N-K)!K! Therefore, the formula for (N choose K+1) is: N! N! N! N! (N-K) —————- = ————— = ——————– = ——– x —– (N-(K+1))!(K+1)! (N-K-1)! (K+1)! (N-K)!/(N-K) K!(K+1) … Read more

Convert a map of lists into a list of maps

You can first iterate through map entries and represent list elements as Map<String,Integer> and get a stream of lists of maps, and then reduce this stream to a single list. Try it online! Map<String, List<Integer>> mapOfLists = new LinkedHashMap<>(); mapOfLists.put(“a”, List.of(1, 2, 3)); mapOfLists.put(“b”, List.of(4, 5, 6)); mapOfLists.put(“c”, List.of(7)); List<Map<String, Integer>> listOfMaps = mapOfLists.entrySet().stream() // … Read more