Links from class:
Permutations and combinations
To illustrate how to generate all combinations, see the following code that prints out all possible subsets of the Teenage Mutant Ninja Turtles.
public class TMNTDemo {
String[] tmnt = { "donatello", "leonardo", "michaelangelo", "raphael" };
int nTmnt = tmnt.length;
/*
* Prints all 2^n subsets of the Teenage Mutant Ninja Turtles
*/
public static void main(String[] args) {
new TMNTDemo().run();
}
public void run() {
for (int mask = 0; mask < (1 << nTmnt); mask++) {
System.out.printf("Subset %2d [%04d]:", mask, Integer.parseInt(Integer.toString(mask, 2)));
System.out.println(getSet(mask));
}
}
public String getSet(int mask) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nTmnt; i++) {
if ((mask & (1 << i)) != 0) {
sb.append(String.format(" %15s", tmnt[i]));
} else {
sb.append(String.format(" %15s", ""));
}
}
return sb.toString();
}
}
Here is the Java code for the next permutation. Feel free to treat it as a black box, but if you’d like to learn more check here or here.
private boolean nextPerm(int[] a) {
if (a.length <= 1) return false;
int i = a.length - 1;
while (a[i - 1] >= a[i]) {
if (--i == 0) return false;
}
int j = a.length;
while (a[j - 1] <= a[i - 1]) {
if (--j == 0) return false;
}
swap(a, i - 1, j - 1);
i++;
j = a.length;
while (i < j) {
swap(a, i - 1, j - 1);
i++; j--;
}
return true;
}
For next class
Assigned readings:
- Read sections 3.1 and 3.2
Assigned problems:
-
Lotto – Hints:
- How can you use bitmasks to help you generate all subsets?
- Look back to Hamming Distance problem and solution in Class 03.
-
Citizen Attention Offices – Hints:
- Use complete search over all possible combinations of office placements. For example, offices can be placed at { 1, 2, 3, 4, 5 }, { 1, 2, 3, 4, 6 }, …, { 21, 22, 23, 24, 25 }.
- The simplest way to generate all combinations for this problem is by using 5 nested loops, the ith loop generating the ith element of the subset. (Is there another way?)
-
Date Bugs – Hints:
- Generate all the years the computers could possibly be from their start date to 9999. Is there a year that all computers share? How can you find such a shared year, what data structure is best to keep track of that?
- Make sure you don’t include year 10,000 because you will get wrong answer!
-
Ecosystem – Bonus
-
Blocks – Bonus