I have found this code to solve Knapsack Problem using brute force mechanism (this is mostly for learning, so no need to point out dynamic is more efficient). I got the code to
Apparently the code parts in question are checks for a certain bit being set, as indicated by the comments. The condition
((i >> j) & 1) != 1
is true if and only if the j
-th bit of i
is zero; the condition
((bestPosition >> j) & 1) == 1
is true if and only if the j
-th bit of bestPosition
is one. Concerning the bigger picture, apparently the implementation uses int
to model a set of items, where the j
-th bit is set if and only if the j
-th item is included in the set; consequently, membership tests can be done by bit checks. The implementation enumerates all subsets of the items (using int
to represent them) to perform exhaustive search.
Note that the Delphi implementation for sets uses the same approach, but hides the bit indexing from client code.