|
| 1 | +# ⚡ BitSet ⚡ |
| 2 | + |
| 3 | +This is a simple, though very fast, bitset implementation in Go derived from the [yourbasic/bit](github.com/yourbasic/bit) package. |
| 4 | + |
| 5 | +## Installation |
| 6 | + |
| 7 | +```go |
| 8 | +go get github.com/KernelPryanic/bitset |
| 9 | +``` |
| 10 | + |
| 11 | +## Usage |
| 12 | + |
| 13 | +### Creating BitSets |
| 14 | + |
| 15 | +```go |
| 16 | +// Create an empty bitset |
| 17 | +empty := bitset.New() |
| 18 | + |
| 19 | +// Create a bitset with initial values |
| 20 | +set := bitset.New(1, 3, 5, 7) |
| 21 | +``` |
| 22 | + |
| 23 | +### Basic Operations |
| 24 | + |
| 25 | +```go |
| 26 | +// Add elements |
| 27 | +set.Add(9) // Add single element |
| 28 | +set.AddRange(2, 5) // Add range [2,3,4] |
| 29 | + |
| 30 | +// Check membership |
| 31 | +exists := set.Contains(3) // true |
| 32 | +absent := set.Contains(6) // false |
| 33 | + |
| 34 | +// Remove elements |
| 35 | +set.Delete(3) // Remove single element |
| 36 | +set.DeleteRange(2, 5) // Remove range [2,3,4] |
| 37 | + |
| 38 | +// Get set information |
| 39 | +size := set.Size() // Number of elements |
| 40 | +isEmpty := set.Empty() // Check if set is empty |
| 41 | +max := set.Max() // Get maximum element |
| 42 | + |
| 43 | +// Iterate through elements |
| 44 | +set.Visit(func(n int) bool { |
| 45 | + fmt.Printf("%d ", n) |
| 46 | + return false // Return true to stop iteration |
| 47 | +}) |
| 48 | +``` |
| 49 | + |
| 50 | +### Set Operations |
| 51 | + |
| 52 | +```go |
| 53 | +set1 := bitset.New(1, 2, 3, 4, 5) |
| 54 | +set2 := bitset.New(4, 5, 6, 7, 8) |
| 55 | + |
| 56 | +// Create new sets from operations |
| 57 | +intersection := bitset.And(set1, set2) // Elements in both sets |
| 58 | +union := bitset.Or(set1, set2) // Elements in either set |
| 59 | +symDiff := bitset.Xor(set1, set2) // Elements in one set but not both |
| 60 | +diff := bitset.AndNot(set1, set2) // Elements in set1 but not in set2 |
| 61 | + |
| 62 | +// Modify existing sets |
| 63 | +set1.And(set2) // Keep only elements present in both sets |
| 64 | +set1.Or(set2) // Add all elements from set2 |
| 65 | +set1.Xor(set2) // Keep elements present in one set but not both |
| 66 | +set1.AndNot(set2) // Remove all elements present in set2 |
| 67 | +``` |
| 68 | + |
| 69 | +### Navigation |
| 70 | + |
| 71 | +```go |
| 72 | +set := bitset.New(1, 3, 5, 7, 9) |
| 73 | + |
| 74 | +// Find next/previous elements |
| 75 | +next := set.Next(4) // Returns 5 (next element after 4) |
| 76 | +prev := set.Prev(6) // Returns 5 (previous element before 6) |
| 77 | + |
| 78 | +// Copy sets |
| 79 | +copy := set.Copy() // Create a new copy |
| 80 | +set2 := bitset.New() |
| 81 | +set2.Set(set) // Replace contents of set2 with set |
| 82 | +``` |
| 83 | + |
| 84 | +### String Representation |
| 85 | + |
| 86 | +```go |
| 87 | +set := bitset.New(1, 2, 3, 5, 7, 8, 9, 10) |
| 88 | +fmt.Println(set) // Outputs: {1..3 5 7..10} |
| 89 | +``` |
0 commit comments