Markov chain implementation for Go
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
cmd
internal/disk
LICENSE.txt
README.md
benchmark_test.go
builder.go
builder_test.go
copy.go
copy_test.go
disk_chain.go
disk_chain_test.go
disk_chain_writer.go
doc.go
example_test.go
go.mod
markov.go
markov_test.go
memory_chain.go
memory_chain_test.go
random.go
random_test.go
value.go
value_test.go
walker.go
walker_iterative.go
walker_iterative_test.go
walker_random.go
walker_random_test.go

README.md

Markov GoDoc

markov is a Markov chain for Go. The package contains a in-memory chain and a slower disk-based version, and functions to move between the memory and disk versions.

Example

This example generates a nonsense sentence from sample text.

package main

import (
	"fmt"

	"github.com/pboyd/markov"
)

const text = `Listen, strange women lying in ponds distributing swords is no basis for a system of government. Supreme executive power derives from a mandate from the masses, not from some farcical aquatic ceremony.`

func main() {
	chain := markov.NewMemoryChain(0)

	// Feed each rune into the chain
	markov.Feed(chain, split(text))

	// Walk the chain with randomly but with weighted probabilities.
	walker := markov.RandomWalker(chain, 0)
	for {
		r, _ := walker.Next()
		fmt.Printf(string(r.(rune)))

		// Stop after the first period.
		if r == '.' {
			break
		}
	}

        fmt.Print("\n")
}

func split(text string) chan interface{} {
	runes := make(chan interface{})
	go func() {
		defer close(runes)

		// Start at the beginning of a word
		runes <- ' '

		for _, r := range text {
			runes <- r
		}
	}()
	return runes
}

For more in-depth examples see the cmd/markov-ngram and cmd/markov-walk programs.

License

This package is released under the terms of the Apache 2.0 license. See LICENSE.TXT.