Skip to content

Instantly share code, notes, and snippets.

@sideb0ard
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sideb0ard/5fe81c080ccba3e39ffd to your computer and use it in GitHub Desktop.
Save sideb0ard/5fe81c080ccba3e39ffd to your computer and use it in GitHub Desktop.
markov gold chains
package main
// bits of code gratutiously borrowed from https://golang.org/doc/codewalk/markov/
import (
"bufio"
"fmt"
"io"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
const (
PREFIXLEN = 2
)
//////////////////////////////////////////////////////////////////
func main() {
fmt.Println("DA MARKOV BOOM!")
rand.Seed(time.Now().UnixNano()) // Seed the random number generator.
if len(os.Args) != 3 {
usage()
os.Exit(1)
}
fileContent, err := os.Open(os.Args[1])
if err != nil {
fmt.Println("Err, mate:", err.Error)
os.Exit(1)
}
c := NewChain() // initialize and make map
c.Build(fileContent) // build shizzle
wurdCount, _ := strconv.Atoi(os.Args[2])
text := c.Generate(wurdCount)
fmt.Println(text)
}
/////////////////////////////////
type Chain struct {
chain map[string][]string
}
func NewChain() *Chain {
return &Chain{make(map[string][]string)}
}
func (c *Chain) Build(r io.Reader) {
br := bufio.NewReader(r)
p := make(PrefixScanner, PREFIXLEN)
for {
var s string
if _, err := fmt.Fscan(br, &s); err != nil {
break
}
key := p.String()
c.chain[key] = append(c.chain[key], s)
p.Shift(s)
}
}
func (c *Chain) Generate(n int) string {
p := make(PrefixScanner, PREFIXLEN)
var words []string
for i := 0; i < n; i++ {
choices := c.chain[p.String()]
if len(choices) == 0 {
break
}
next := choices[rand.Intn(len(choices))]
words = append(words, next)
p.Shift(next)
}
return strings.Join(words, " ")
}
//////////////////////////////////////////////////////////////////
type PrefixScanner []string
func (p PrefixScanner) String() string {
return strings.Join(p, " ")
}
func (p PrefixScanner) Shift(word string) {
copy(p, p[1:])
p[len(p)-1] = word
}
///////////////////////////////////////////
func usage() {
fmt.Println("Usage:", os.Args[0], "<filename to read> <num of words returned>")
}
@CoSin3
Copy link

CoSin3 commented Jan 3, 2015

Dude i'm new here I know basics in html css and js but. In this file you posted. does that run the program without domain or what?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment