我正在努力撰寫以下內容(使用 GAS):
我有 14 個盒子,它們要么是空的,要么是空的,我需要跟蹤哪些盒子是空的。我的想法是使用 base2 控制值來跟蹤哪些框是空的。
為了說明,我將使用一個只有 3 個框的示例
我認為以下方案可行:
- 所有框為空:0 控制值
- 只有框 1 為空:1 個控制值
- 只有框 2 為空:2 控制值
- 框 1 和 2 為空:3 控制值
- 只有框 3 為空:4 控制值
- 框 1 和 3 為空:5 個控制值
- 框 2 和 3 為空:6 個控制值
- 沒有空框:7 控制值
我需要一種演算法來知道哪些盒子是空的,以及如何在盒子被填充和/或清空時更新控制值。
我假設(d)必須存在可以使用此功能的演算法,因此這種base2系列的使用有一個我可以用來谷歌的名稱,對吧?
如果這是這個問題的錯誤地方,請告訴我。謝謝你。
uj5u.com熱心網友回復:
(我支持空通常是 0 位,滿是 1 位的評論,但我可以使用它。)
只需使用按位運算子
x & 1 # True if box 1 is empty
x & 2 # True if box 2 is empty
x & 4 # True if box 3 is empty
要切換盒子是空的還是滿的:
x ^ 1 # Switches box 1
x ^ 2 # Switches box 2
x ^ 4 # Switches box 3
要確保一個框是空的:
x & 1 # Box 1 is empty
x & 2 # Box 2 is empty
x & 4 # Box 3 is empty
唯一棘手的是保證一個盒子是滿的。
(x & 1) ^ 1 # Box 1 is full
(x & 2) ^ 2 # Box 2 is full
(x & 4) ^ 4 # Box 3 is full
按位與 (&)
按位異或 (^)
uj5u.com熱心網友回復:
這被稱為bitmasks
。在計算機科學中,掩碼或位掩碼是用于按位運算的資料,尤其是在位域中。
您可以將問題的狀態表示為一個bool
陣列,例如:bool is_empty[14];
但這需要O(N)
記憶體,N
您擁有的盒子的數量在哪里。除了使用這個陣列,您還可以使用 的概念來用單個數字bitmasks
的一??位來表示每個框。我們以三個盒子為例:
decimal binary meaning
0 000 All three boxes are empty
1 001 Box 1 is full
2 010 Box 2 is full
3 011 Boxes 1, 2 are full
4 100 Box 3 is full
5 101 Boxes 1, 3 are full
6 110 Boxes 2, 3 are full
7 111 All three boxes are full
要檢查是否i
設定了位,只需檢查是否mask & 1<<i
不等于零。
要打開位i
,您執行mask = mask | 1<<i;
要關閉位i
,請執行mask = mask & ~(1<<i)
要切換位i
,請執行mask = mask ^ 1<<i
。
的一個常見用途bitmasks
是從一組數字中生成所有子集,這里是C
這樣做的:
#include <iostream>
#include <vector>
int main(){
std::vector<int>a{1, 2, 3};
int n = static_cast<int>(a.size());
for(int mask = 0;mask < (1<<n);mask ){
std::vector<int>subset;
for(int i = 0;i < n;i ){
if(mask & 1<<i){
subset.push_back(a[i]);
}
}
for(auto &&num: subset)std::cout << num << " ";
std::cout << std::endl;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/505883.html