Skip to content

Latest commit

 

History

History
71 lines (65 loc) · 1.88 KB

1136.md

File metadata and controls

71 lines (65 loc) · 1.88 KB

题目:通过实验检查表 1.1.10 中的乱序代码是否能够产生预期的效果。编写程序 ShuffleTest,接受命令行参数M和N,将大小为M的数组打乱N次且再每次打乱之前豆浆数组重新初始化为a[i]=i。打印一个 MxM 的表格,对于所有的列 j,行 i 表示的是 i 在打乱后落到 j 的位置的次数。数组中的所有元素的值都应该接近于 N/M。

附表 1.1.10 的 shuffle 程序:

def shuffle(a):
    n = len(a)
    for i in range(0, n):
        # 产生 i 到 n 之间的随机整数 r,交换a[r]和a[i]
        r = random.randint(i, n-1)
        temp = a[i]
        a[i] = a[r]
        a[r] = temp

计算次数的稍微有点绕,想一下就好。

def shuffleTest(self, m, n):
    def shuffle(a):
        n = len(a)
        for i in range(0, n):
            # 产生 i 到 n 之间的随机整数 r,交换a[r]和a[i]
            r = random.randint(i, n-1)
            temp = a[i]
            a[i] = a[r]
            a[r] = temp
    res = [[0 for i in range(0, m)] for i in range(0, m)]
    l = [0 for i in range(0, m)]
    for i in range(0, n):
        for j in range(0, m):
            l[j] = j
        print(f'before shuffle:{l}')
        shuffle(l)
        print(f'after shuffle:{l}')
        for j in range(0, m):
            idxAfter = l.index(j)
            res[j][idxAfter] += 1
    for i in range(0, m):
        print('------------------')
        print(f'row{i}:')
        s = ''
        for j in range(0, m):
            s += f'{res[i][j]} '
        print(s)

当 m = 7,n = 200 时:

row0:
23 34 30 27 30 27 29 
------------------
row1:
30 36 31 25 29 24 25 
------------------
row2:
28 24 28 35 35 28 22 
------------------
row3:
26 21 36 28 24 30 35 
------------------
row4:
34 25 29 27 12 38 35 
------------------
row5:
22 35 21 33 28 24 37 
------------------
row6:
37 25 25 25 42 29 17