算法导论(第三版)参考答案:练习5.3-1,练习5.3-2,练习5.3-3,练习5.3-4,练习5.3-5,练习5.3-6,练习5.3-7
Exercise 5.3-1
Professor Marceau objects to the loop invariant used in the proof of Lemma 5.5. He questions whether it is true prior to the first iteration. He reasons that we could just as easily declare that an empty subarray contains no 0-permutations. Therefore, the probability that an empty subarray contains a 0-permutation should be 0, thus invalidating the loop invariant prior to the first iteration. Rewrite the procedure RANDOMIZE-IN-PLACE so that its associated loop invariant applies to a nonempty subarray prior to the first iteration, and modify the proof of Lemma 5.5 for your procedure.
Pseudocode
RANDOMIZE-IN-PLACE02(A)
n = A.length
swap A[1] with A[RANDOM(1,n)]
for i = 2 to n
swap A[i] with A[RANDOM(i,n)]
在证明中,初始化部分不再从空数组开始,而是从 A[i] 开始。根据循环不变式可知,初始化部分成立。
Exercise 5.3-2
Professor Kelp decides to write a procedure that produces at random any permutation besides the identity permutation. He proposes the following procedure:
PERMUTE-WITHOUT-IDENTITY(A) n = A.length for i = 1 to n - 1 swap A[i] with A[RANDOM(i + 1, n)]
Does this code do what Professor Kelp intends?
(中英文版的题意貌似不一样,beside?/ except?,这里参考英文原版)
不能,因为每次置换都不可能出现第 i 个元素在相同的位置上,只会产生
Exercise 5.3-3
Suppose that instead of swapping element A[i] with a random element from the subarray A[i…n] , we swapped it with a random element from anywhere in the array:
PERMUTE-WITH-ALL(A) n = A.length for i = 1 to n swap A[i] with A[RANDOM(1,n)]
Does this code produce a uniform random permutation? Why or why not?
不能。有 nn 种方式放置元素,同时又有 n! 种排列。获得等同排列的概率是 1nnn! ,不是 1n! 。
Exercise 5.3-4
Professor Armstrong suggests the following procedure for generating a uniform random permutation:
n = A.length let B[1..n] be a new array offset = RANDOM(1, n) for i = 1 to n dest = i + offset if dest > n dest = dest - n B[dest] = A[i] return B
Show that each element A[i] has a 1/n probability of winding up in any particular position in B . Then show that Professor Armstrong is mistaken by showing that the resulting permutation is not uniformly random.
很容易理解,
这样做只是获得了一个在原数组 A 上的循环置换元素后的数组