Skip to content

Instantly share code, notes, and snippets.

@chaos95
Created October 23, 2012 01:59
Show Gist options
  • Save chaos95/3936240 to your computer and use it in GitHub Desktop.
Save chaos95/3936240 to your computer and use it in GitHub Desktop.
L-systems in Go
package lsystems
import (
"bytes"
)
func lsystem_buffer(s *bytes.Buffer, rules []string) {
tmpbuf := bytes.NewBuffer(make([]byte, 0, 1e6))
for _, b := range s.Bytes() {
if rule := rules[b]; rule != "" {
tmpbuf.WriteString(rule)
} else {
tmpbuf.WriteByte(b)
}
}
*s = *tmpbuf
}
func lsystem_append(s *[]byte, rules []string) {
tmpbuf := make([]byte, 0, 1e6)
for _, b := range *s {
if rule := rules[b]; rule != "" {
tmpbuf = append(tmpbuf, rule...)
} else {
tmpbuf = append(tmpbuf, b)
}
}
*s = tmpbuf
}
package lsystems
import (
"bytes"
"encoding/json"
"fmt"
"testing"
)
type rule struct {
key []byte
value []byte
}
func BenchmarkBuffer(b *testing.B) {
b.StopTimer()
rules_in := []byte("{\"X\": \"F-[[X]+X]+F[+FX]-X\", \"F\": \"FF\"}")
rules_tmp := make(map[string]string)
json.Unmarshal(rules_in, &rules_tmp)
rules := make([]string, 256)
for key, value := range rules_tmp {
rules[byte(key[0])] = value
}
out := bytes.NewBuffer(make([]byte, 0, 1e8))
b.StartTimer()
for i := 0; i < b.N; i++ {
out.Reset()
out.WriteString("X")
for x := 0; x < 9; x++ {
lsystem_buffer(out, rules)
}
}
fmt.Println(out.String())
}
func BenchmarkAppend(b *testing.B) {
b.StopTimer()
rules_in := []byte("{\"X\": \"F-[[X]+X]+F[+FX]-X\", \"F\": \"FF\"}")
rules_tmp := make(map[string]string)
json.Unmarshal(rules_in, &rules_tmp)
rules := make([]string, 256)
for key, value := range rules_tmp {
rules[byte(key[0])] = value
}
out := make([]byte, 0, 1e8)
b.StartTimer()
for i := 0; i < b.N; i++ {
out = []byte("X")
for x := 0; x < 9; x++ {
lsystem_append(&out, rules)
}
}
fmt.Println(string(out))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment