公式 int new_pos = (pos + delta + 9) % 9;
是一個常見的 循環數組索引計算 方法,用于處理圓圈排列中的位置計算。這個公式可以總結出一個普遍的規律,適用于任何循環數組或圓圈排列的場景。
普遍規律
假設有一個長度為 ( n ) 的循環數組(或圓圈排列),當前索引為 pos
,需要計算移動 delta
步后的新索引 new_pos
。公式如下:
new_pos = (pos + delta + n) \% n
解釋:
-
pos + delta
:- 表示從當前位置
pos
移動delta
步。 delta
可以是正數(向右移動)或負數(向左移動)。
- 表示從當前位置
-
+ n
:- 確保
pos + delta
的結果是非負數,避免負數取模的問題。 - 例如,如果
pos + delta
是負數,加上n
后會變成正數。
- 確保
-
% n
:- 對結果取模,確保新索引在
[0, n-1]
范圍內,實現循環效果。
- 對結果取模,確保新索引在
應用場景
這個公式適用于以下場景:
-
圓圈排列:
- 例如題目中的 9 只盤子排成一個圓圈。
- 當移動到第 9 個位置時,下一個位置應該是第 1 個位置(循環)。
-
循環數組:
- 例如環形緩沖區、循環隊列等數據結構。
- 當索引超出數組范圍時,自動回到數組開頭。
-
周期性移動:
- 例如模擬時鐘的指針移動、周期性任務調度等。
示例
示例 1:圓圈排列
假設有一個長度為 5 的圓圈排列,當前索引為 2
,需要向左移動 3 步(delta = -3
)。
int n = 5; // 圓圈長度
int pos = 2; // 當前位置
int delta = -3; // 向左移動 3 步int new_pos = (pos + delta + n) % n;
// 計算過程:
// pos + delta = 2 + (-3) = -1
// -1 + 5 = 4
// 4 % 5 = 4
// 結果:new_pos = 4
示例 2:循環數組
假設有一個長度為 4 的循環數組,當前索引為 3
,需要向右移動 2 步(delta = 2
)。
int n = 4; // 數組長度
int pos = 3; // 當前位置
int delta = 2; // 向右移動 2 步int new_pos = (pos + delta + n) % n;
// 計算過程:
// pos + delta = 3 + 2 = 5
// 5 + 4 = 9
// 9 % 4 = 1
// 結果:new_pos = 1
公式的變體
如果 delta
始終是非負數(例如只向右移動),可以省略 + n
的步驟:
new_pos = (pos + delta ) \% n
示例:
int n = 5; // 圓圈長度
int pos = 3; // 當前位置
int delta = 4; // 向右移動 4 步int new_pos = (pos + delta) % n;
// 計算過程:
// pos + delta = 3 + 4 = 7
// 7 % 5 = 2
// 結果:new_pos = 2
總結
公式 int new_pos = (pos + delta + n) % n;
是一個通用的循環索引計算方法,適用于任何圓圈排列或循環數組的場景。它的核心思想是通過取模運算實現循環效果,并通過 + n
確保索引始終為非負數。