110 likes | 124 Views
Explore algorithms to find rank and subset in lexicographic order, next k-subset, ranking, and unranking of k-subsets with examples. Learn about Binary Reflected Gray Code for conversion and Generic Backtracking Algorithm.
E N D
Week 5 Courtesy of Sheridan Houghten
Lexicographic Order – Subsets of {1, …, n}(See KS, algorithm 2.1) Algorithm to find rank of subset T: FindRank(n, T) { rank = 0; for (i = 1; i <= n; i++) if i is in T rank = rank + 2^(n-i); return rank; }
Lexicographic Order – Subsets of {1, …, n}(see KS, algorithm 2.2) Algorithm to find subset that has rank r: Unrank(int n, int r) { T = {}; for (i = n; i >= 1; i--) { if ((r % 2) == 1) T = T U {i}; r = r/2; // integer division! } return T; }
Lexicographically-next k-subset of {1,…,n}(see KS, algorithm 2.6) KSubsetLexSuccessor(T, k, n) { U = T; // find rightmost element that can increase i = k; while (i >= 1) and (t[i] == n-k+i) i--; if (i == 0) return undefined; else { u[i] = t[i]+1; for j = i+1 to k u[j] = u[j-1] + 1; return U; } }
Lexicographic Order of k-Subsets – Ranking(see KS, algorithm 2.7) KSubsetLexRank(T, k, n) { r = 0; t[0] = 0; for i = 1 to k { for j = (t[i-1]+1) to (t[i]-1) r = r + (n-j) choose (k-i) } return r; }
Lexicographic Order of k-Subsets – Unranking(see KS, algorithm 2.8) KSubsetLexUnrank(rank, k, n) { x = 1; for i = 1 to k { while (n-x) choose (k-i) <= rank { rank = rank - (n-x) choose (k-i); x++; } t[i] = x; x++; } return T; }
011 111 010 110 001 101 000 100 Binary Reflected Gray Code Gn Note: Demonstrated in class how to convert a binary word to its equivalent Gray code word using XOR. Demonstrated in class how to convert a Gray code word into its equivalent binary Using XOR. These methods can be used as the basis for ranking and unranking algorithms. G1= [0,1] G2= [00,01,11,10] G3= [000,001,011,010,110,111,101,100] G4= [0000,0001,0011,0010,0110,0111,0101,0100, 1100,1101,1111,1110,1010,1011,1001,1000] (etc.)
Generic Backtracking Algorithm backtrack(X, c, n){ // X = <x1, …, xc-1 > is a partial solution. // c = current level; n = final level. // We are attempting to find xc compute candidates for level c; for each candidate x { if(x1, …, xc-1, x) is an acceptable partial soln { xc = x; // choose the candidate if(c < n) backtrack(X, c+1, n); else process solution; } } }
Acceptable – n-Queens Problem acceptable(p, c, r) { //check in p[1..c-1] for entry in row r for(j = 1; j < c; j++){ if(p[j] == r) return false; } //check in p[1..c-1] for entry in diag. for(j = 1; j < c; j++){ if(c – j == abs(r - p[j])) return false; } return true; }