Skip to content

Commit 74c2bc8

Browse files
committed
Add util/bitops
1 parent 5a6faf5 commit 74c2bc8

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

lib/cpalgo/util/bitops.hpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#pragma once
2+
3+
#include <functional>
4+
#include <stdexcept>
5+
6+
// Iterates subsets of given bitset `S`.
7+
//
8+
// S = b0101
9+
// bs = { 0101, 0100, 0001, 0000 }
10+
//
11+
// Time: O(2**M)
12+
// where M is the bit count of the given bitset
13+
//
14+
inline void iterate_subsets(
15+
int S,
16+
std::function<void(int)> const& f
17+
) {
18+
if (S < 0) throw std::out_of_range("S");
19+
for (auto bs = S; true; bs = (bs - 1) & S) {
20+
f(bs);
21+
if (bs == 0) break;
22+
}
23+
}

lib/cpalgo/util/tests/bitops_test.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#include <bits/stdc++.h>
2+
#include "gtest/gtest.h"
3+
#include "cpalgo/util/bitops.hpp"
4+
5+
using namespace std;
6+
7+
TEST(BitOpsTest, IterateSubsets) {
8+
9+
int S = (1 << 0) | (1 << 2) | (1 << 3);
10+
set<int> subsets;
11+
iterate_subsets(S, [&](int bs) {
12+
subsets.insert(bs);
13+
});
14+
set<int> expected_subsets = {
15+
(1 << 0) | (1 << 2) | (1 << 3),
16+
(1 << 2) | (1 << 3),
17+
(1 << 0) | (1 << 3),
18+
(1 << 3),
19+
(1 << 0) | (1 << 2),
20+
(1 << 2),
21+
(1 << 0),
22+
0
23+
};
24+
25+
EXPECT_EQ(expected_subsets, subsets);
26+
27+
}

0 commit comments

Comments
 (0)