Skip to content

Instantly share code, notes, and snippets.

@vaughany
Created December 16, 2020 13:37
Show Gist options
  • Save vaughany/0e8644ee9890a225d14a17bdac203887 to your computer and use it in GitHub Desktop.
Save vaughany/0e8644ee9890a225d14a17bdac203887 to your computer and use it in GitHub Desktop.
Van Eck Sequence in Go.
// Van Eck Sequence
// Run with: `go run van-eck-sequence.go`
package main
import (
"flag"
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
var delay int = 100
var perline int = 50
var separator string = ", "
var runs int = 0
var sequence = []int{0}
func init() {
flag.IntVar(&delay, "d", delay, "Delay between numbers in ms. Can be 0.")
flag.IntVar(&perline, "p", perline, "Wrap at this amount of numbers output.")
flag.StringVar(&separator, "s", separator, "Something to delineate the different numbers. Or not.")
flag.IntVar(&runs, "r", runs, "Maximum amount of numbers output. 0 means infinite, or thereabouts.")
flag.Parse()
if delay < 0 {
panic("Invalid delay: that would involve time travel.")
}
if perline < 1 {
panic("Invalid numbers-per-line setting. Don't be an idiot.")
}
if len(separator) > 5 {
panic("You're using more than 5 characters to delineate numbers? Are you okay?")
}
if runs < 0 {
panic("Well, that's a bit pointless.")
}
}
func main () {
seen := map[int]int{}
closeHandler()
for i, s := range sequence {
seen[s] = i + 1
}
for {
key := sequence[len(sequence)-1]
value := len(sequence)-1
if seen[key] == 0 {
seen[key] = value + 1
sequence = append(sequence, 0)
} else {
sequence = append(sequence, value + 1 - seen[key])
seen[key] = value + 1
}
fmt.Printf("%d%s", key, separator)
if (len(sequence)-1) % perline == 0 {
fmt.Println()
}
if runs > 0 && len(sequence) == runs {
fmt.Printf("\nCompleted %d runs.\n", runs)
doOutput()
createGraph()
break
}
time.Sleep(time.Duration(int(delay)) * time.Millisecond)
}
}
func closeHandler() {
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
fmt.Println("\nCtrl+C pressed, quitting...")
doOutput()
createGraph()
os.Exit(0)
}()
}
func doOutput() {
fmt.Println(sequence)
}
func createGraph() {
fmt.Println("Creating image, will just be a sec...")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment