一道演算法題:12個黑球和1個白球圍成一個圓
阿新 • • 發佈:2019-02-03
問題:
桌上有12個黑球和1個白球圍成一個圓,按順時針方向順序數到13就拿走對應的一個球, 如果要求最後拿走的是白球,請問該從哪個球開始數數。
輸出: White ball position from left: 12 round: 2 11 round: 3 10 round: 4 9 round: 2 8 round: 3 7 round: 2 6 round: 7 5 round: 2 4 round: 5 3 round: 7 2 round: 8 1 round: 8
開始的時候,白球位於第8個,也就是前面有7個黑球。
桌上有12個黑球和1個白球圍成一個圓,按順時針方向順序數到13就拿走對應的一個球, 如果要求最後拿走的是白球,請問該從哪個球開始數數。
分析:
從最後一輪開始考慮,按輪次倒推。可以用遞迴法求解。
python程式碼:
N=13 # 把球看做從左到右的一行 print('White ball position from left:') def find_ball(n): if n == 1: return 1 ret = N % n + find_ball(n-1) if ret > n: ret %= n print('%2d round: %d'%(N - n + 1, ret)) return ret find_ball(N)
輸出: White ball position from left: 12 round: 2 11 round: 3 10 round: 4 9 round: 2 8 round: 3 7 round: 2 6 round: 7 5 round: 2 4 round: 5 3 round: 7 2 round: 8 1 round: 8
開始的時候,白球位於第8個,也就是前面有7個黑球。