xonecas.io
5119
Lh

lazy-history / commit 3e84cdf

fix: use a matrix instead of recursion for speed

Sean2025-05-11 3e84cdf4eaf1abe861ae40132e9c59f6eb5f8a4a parent e18476b

2 files changed

cmd/main.go+4−2
@@ -6,6 +6,7 @@ import (
66 "os"
77 "os/exec"
88 "path/filepath"
9+ "strings"
910
1011 tea "github.com/charmbracelet/bubbletea"
1112 internal_list "github.com/sacenox/lazy-history/internal/list"
@@ -59,9 +60,10 @@ func main() {
5960 historyFile.Close()
6061 }
6162
62- log.Printf("History: %v", history)
63+ log.Printf("History length: %d", len(history))
6364
64- query := os.Args[1] // args without program name
65+ // Join all args into a single string
66+ query := strings.Join(os.Args[1:], " ")
6567
6668 log.Printf("Searching for %s", query)
6769
internal/search/search.go+23−11
@@ -54,23 +54,35 @@ func search(slice []string, substring string) []SearchResult {
5454 }
5555
5656 func levenshteinDistance(s, t string) int {
57+ // Create matrix of size (lenS+1)*(lenT+1)
5758 lenS := len(s)
5859 lenT := len(t)
5960
60- if lenS == 0 {
61- return lenT
61+ // Initialize the matrix
62+ d := make([][]int, lenS+1)
63+ for i := range d {
64+ d[i] = make([]int, lenT+1)
65+ d[i][0] = i // Fill first column
6266 }
63- if lenT == 0 {
64- return lenS
67+ for j := range d[0] {
68+ d[0][j] = j // Fill first row
6569 }
6670
67- if s[lenS-1] == t[lenT-1] {
68- return levenshteinDistance(s[:lenS-1], t[:lenT-1])
71+ // Fill the matrix
72+ for i := 1; i <= lenS; i++ {
73+ for j := 1; j <= lenT; j++ {
74+ cost := 1
75+ if s[i-1] == t[j-1] {
76+ cost = 0
77+ }
78+
79+ d[i][j] = min(
80+ d[i-1][j]+1, // deletion
81+ d[i][j-1]+1, // insertion
82+ d[i-1][j-1]+cost, // substitution
83+ )
84+ }
6985 }
7086
71- return 1 + min(
72- levenshteinDistance(s[:lenS-1], t),
73- levenshteinDistance(s, t[:lenT-1]),
74- levenshteinDistance(s[:lenS-1], t[:lenT-1]),
75- )
87+ return d[lenS][lenT]
7688 }