Skip to content
Merged

Comp #31

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
go: [ '1.24.0' ]
go: [ '1.26' ]
steps:
- uses: actions/checkout@v3

Expand Down
2 changes: 1 addition & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
version: "2"

run:
go: "1.24"
go: "1.26"
timeout: 5m
tests: false
issues-exit-code: 1
Expand Down
302 changes: 297 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,305 @@
# Algorithms

Algorithmic calculation methods
[![Go Reference](https://pkg.go.dev/badge/go.osspkg.com/algorithms.svg)](https://pkg.go.dev/go.osspkg.com/algorithms)
[![Go 1.26+](https://img.shields.io/badge/go-1.26%2B-00ADD8?logo=go&logoColor=white)](https://go.dev/)
[![License](https://img.shields.io/badge/license-BSD--3--Clause-blue.svg)](LICENSE)

## Install
A collection of generic algorithms, encoders, graphs, filters, and data
structures for Go.

```shell
go get -u go.osspkg.com/algorithms
The module is intentionally split into focused subpackages. Import only the
package you need; the module root does not expose a general-purpose API.

## Requirements

- Go 1.26 or newer

## Installation

```bash
go get go.osspkg.com/algorithms@latest
```

## Packages

| Package | Provides | Guide |
| --- | --- | --- |
| [`comp`](https://pkg.go.dev/go.osspkg.com/algorithms/comp) | Hamming, Levenshtein, Damerau-Levenshtein, LCS, and Jaro-style sequence comparison | [README](comp/README.md) |
| [`sorts`](https://pkg.go.dev/go.osspkg.com/algorithms/sorts) | Bubble, cocktail, heap, insertion, merge, and selection sort; slice reversal | [README](sorts/README.md) |
| [`graph/dfs`](https://pkg.go.dev/go.osspkg.com/algorithms/graph/dfs) | Generic depth-first topological sorting with cycle detection | [README](graph/dfs/README.md) |
| [`graph/kahn`](https://pkg.go.dev/go.osspkg.com/algorithms/graph/kahn) | String-keyed Kahn topological sorting with dependency subgraphs | [README](graph/kahn/README.md) |
| [`encoding/base62`](https://pkg.go.dev/go.osspkg.com/algorithms/encoding/base62) | Configurable Base62 encoding for `uint64` values | [README](encoding/base62/README.md) |
| [`encoding/otp`](https://pkg.go.dev/go.osspkg.com/algorithms/encoding/otp) | TOTP/HOTP generation and `otpauth` URLs | [README](encoding/otp/README.md) |
| [`encoding/token`](https://pkg.go.dev/go.osspkg.com/algorithms/encoding/token) | Compact `T64` identifiers with text, binary, and SQL integration | [README](encoding/token/README.md) |
| [`structs/bitmap`](https://pkg.go.dev/go.osspkg.com/algorithms/structs/bitmap) | Concurrent growable bitmap | [README](structs/bitmap/README.md) |
| [`structs/bloom`](https://pkg.go.dev/go.osspkg.com/algorithms/structs/bloom) | Space-efficient Bloom filter with persistence support | [README](structs/bloom/README.md) |
| [`trees/btree`](https://pkg.go.dev/go.osspkg.com/algorithms/trees/btree) | Concurrent generic B-tree | [README](trees/btree/README.md) |

## Usage

### Compare sequences

Comparers work with any `comparable` element type. `Similarity` returns a score
from `0` to `100`; use `[]rune` for Unicode-aware text comparison.

```go
package main

import (
"fmt"

"go.osspkg.com/algorithms/comp"
)

func main() {
cmp := comp.NewLevenshtein[rune]()
score := cmp.Similarity([]rune("kitten"), []rune("sitting"))

fmt.Printf("similarity: %.2f\n", score)
}
```

Choose the comparer according to the type of difference you need to model:

- `NewHamming` compares equal-length sequences and counts positional changes.
- `NewLevenshtein` accounts for insertions, deletions, and substitutions.
- `NewDamerauLevenshtein` also accounts for adjacent transpositions.
- `NewLCS` measures the longest common subsequence.
- `NewJaroWinkler` currently uses Jaro-style matching-window similarity and
does not apply a separate Winkler prefix boost.

### Sort a slice

Sorting functions mutate the supplied slice in place. The comparison callback
receives indexes into the slice's current state.

```go
package main

import (
"fmt"

"go.osspkg.com/algorithms/sorts"
)

type job struct {
name string
priority int
}

func main() {
jobs := []job{
{name: "backup", priority: 30},
{name: "deploy", priority: 10},
{name: "test", priority: 20},
}

sorts.Merge(jobs, func(i, j int) bool {
return jobs[i].priority < jobs[j].priority
})

fmt.Println(jobs) // [{deploy 10} {test 20} {backup 30}]
}
```

Available functions are `Bubble`, `Cocktail`, `Heapsort`, `Insertion`, `Merge`,
`Selection`, and `Reverse`. For ordinary application sorting, compare these
algorithms with the Go standard library's `slices.SortFunc` or `sort.Slice`.

### Order a dependency graph

The DFS implementation supports generic comparable keys. Add vertices before
adding edges; an edge `from -> to` means that `from` must come first.

```go
package main

import (
"fmt"
"log"

"go.osspkg.com/algorithms/graph/dfs"
)

func main() {
g := dfs.NewGraph[string]()
for _, node := range []string{"clean", "compile", "test"} {
if err := g.AddNode(node); err != nil {
log.Fatal(err)
}
}
if err := g.AddEdge("clean", "compile"); err != nil {
log.Fatal(err)
}
if err := g.AddEdge("compile", "test"); err != nil {
log.Fatal(err)
}

order, err := g.TopologicalSort()
if err != nil {
log.Fatal(err)
}
fmt.Println(order)
}
```

`graph/kahn` is an alternative for string-keyed graphs. It registers vertices
automatically with `Add` and supports `BreakPoint` when only one target and its
transitive dependencies should be ordered.

### Encode values

```go
package main

import (
"fmt"

"go.osspkg.com/algorithms/encoding/base62"
)

func main() {
codec := base62.New("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
encoded := codec.Encode(123456)
decoded := codec.Decode(encoded)

fmt.Println(encoded, decoded)
}
```

`base62.New` requires an alphabet of exactly 62 unique bytes. `Encode(0)` and
`Decode("")` both produce the zero value. Invalid input to `Decode` also
produces `0`, so validate input or use a round-trip check when zero must be
distinguished from invalid data.

For one-time passwords, use `encoding/otp`:

```go
package main

import (
"fmt"
"log"

"go.osspkg.com/algorithms/encoding/otp"
)

func main() {
generator, err := otp.New(otp.OptHashSHA256(), otp.OptCode8Digits())
if err != nil {
log.Fatal(err)
}

secret, err := generator.NewSecret(20)
if err != nil {
log.Fatal(err)
}
code, err := generator.GenerateTOTP(secret, 0)
if err != nil {
log.Fatal(err)
}
fmt.Println(code)
}
```

The default OTP configuration is SHA-1, a 30-second TOTP period, and 6-digit
codes. Treat secrets and `otpauth` URLs as sensitive credentials.

`encoding/token` provides compact `T64` identifiers:

```go
package main

import (
"fmt"

"go.osspkg.com/algorithms/encoding/token"
)

func main() {
id := token.NewRandom()
wire := id.String()
parsed, ok := token.Parse(wire)
if !ok {
panic("invalid token")
}
fmt.Println(parsed == id)
}
```

`T64` also exposes marshal methods for text, binary, and JSON-oriented
serialization, plus `database/sql` scanner and valuer integration. Its current
`MarshalJSON` method returns the text representation without JSON quotes; wrap
the value as a string when standard JSON encoding is required.

### Use data structures

```go
package main

import (
"fmt"

"go.osspkg.com/algorithms/structs/bitmap"
"go.osspkg.com/algorithms/trees/btree"
)

func main() {
bm := bitmap.New()
bm.Set(42)
fmt.Println(bm.Has(42)) // true

tree := btree.New[int, string](2)
tree.Insert(10, "ten")
value, ok := tree.Find(10)
if ok {
fmt.Println(value) // ten
}
}
```

`structs/bloom` is useful when a fast membership check can tolerate false
positives. It never guarantees that a reported item is present, so keep a
source of truth behind the filter:

```go
package main

import (
"log"

"go.osspkg.com/algorithms/structs/bloom"
)

func main() {
filter, err := bloom.New(bloom.Quantity(100_000, 0.01))
if err != nil {
log.Fatal(err)
}
filter.Add("user:42")
possiblyPresent := filter.Contain("user:42")
log.Println(possiblyPresent)
}
```

`structs/bitmap` and `trees/btree` use synchronization by default. If a bitmap
`Set` may grow its storage, serialize it with concurrent `Has` or `Del` calls.
Disable bitmap locking only when access is strictly single-threaded or
synchronized by the caller.

## Testing

Run the complete test suite with:

```bash
go test ./...
```

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md). Please open an issue for larger
changes and include tests, documentation, and an example when appropriate.

## License

BSD-3-Clause License. See the LICENSE file for details
Algorithms is released under the [BSD 3-Clause License](LICENSE).
41 changes: 41 additions & 0 deletions comp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Package `comp`

## Abstract

`comp` compares sequences of comparable values. Its constructors return a
`Comparer[T]`, whose public interface exposes a normalized `Similarity` score.
Use `[]rune` for Unicode text, `[]byte` for byte sequences, or slices of other
comparable values for tokens and symbols.

## Algorithms

| Constructor | Measures |
| --- | --- |
| `NewHamming[T]` | Positional differences; input lengths must match for a non-zero similarity. |
| `NewLevenshtein[T]` | Insertions, deletions, and substitutions. |
| `NewDamerauLevenshtein[T]` | Levenshtein edits plus adjacent transpositions using the restricted optimal-string-alignment variant. |
| `NewLCS[T]` | Longest common subsequence, not longest common substring. |
| `NewJaroWinkler[T]` | Jaro-style matching-window similarity. The current implementation does not apply a separate Winkler prefix boost. |

`Similarity` returns a score from `0` to `100`, rounded to two decimal
places. Two empty sequences score `100`. Hamming comparison of unequal-length
sequences scores `0`.

```go
package main

import (
"fmt"

"go.osspkg.com/algorithms/comp"
)

func main() {
comparer := comp.NewLevenshtein[rune]()
score := comparer.Similarity([]rune("kitten"), []rune("sitting"))
fmt.Printf("%.2f\n", score)
}
```

The constructors expose `Similarity` through `Comparer[T]`; distance methods
are not part of that interface.
16 changes: 16 additions & 0 deletions comp/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* Copyright (c) 2019-2026 Mikhail Knyazhev <markus621@yandex.com>. All rights reserved.
* Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file.
*/

package comp

import "math"

type Comparer[T comparable] interface {
Similarity(a, b []T) float64
}

func round(x float64) float64 {
return math.Round(x*1_00_00) / 100
}
Loading
Loading