completed save rect to RLE file feature

This commit is contained in:
2024-05-26 20:26:13 +02:00
parent cb3e8b3c4c
commit 4b38bea5db
7 changed files with 160 additions and 5 deletions

View File

@@ -1,8 +1,9 @@
// source: https://github.com/nhoffmann/life by N.Hoffmann 2020.
// original source: https://github.com/nhoffmann/life by N.Hoffmann 2020.
package rle
import (
"fmt"
"os"
"regexp"
"strconv"
"strings"
@@ -52,7 +53,7 @@ func (rle *RLE) partitionFile() error {
}
}
return fmt.Errorf("Invlaid input: Header is missing")
return fmt.Errorf("invalid input: Header is missing")
}
func (rle *RLE) parseComments() error {
@@ -98,3 +99,78 @@ func removeWhitespace(input string) string {
re := regexp.MustCompile(` *\t*\r*\n*`)
return re.ReplaceAllString(input, "")
}
// Store a grid to an RLE file
func StoreGridToRLE(grid [][]int64, filename, rule string, width, height int) error {
fd, err := os.Create(filename)
if err != nil {
return err
}
var pattern string
for y := 0; y < height; y++ {
line := ""
for x := 0; x < width; x++ {
switch grid[y][x] {
case 0:
line += "b"
case 1:
line += "o"
}
}
// if first row is: 001011110, then line is now:
// bboboooob
encoded := RunLengthEncode(line)
// and now its: 2bob4ob
pattern += encoded
if y != height-1 {
pattern += "$"
}
}
pattern += "!"
wrapped := ""
for idx, char := range pattern {
if idx%70 == 0 && idx != 0 {
wrapped += "\n"
}
wrapped += string(char)
}
_, err = fmt.Fprintf(fd, "#N %s\nx = %d, y = %d, rule = %s\n%s\n",
filename, width, height, rule, wrapped)
if err != nil {
return err
}
return nil
}
// by peterSO on
// https://codereview.stackexchange.com/questions/238893/run-length-encoding-in-golang
func RunLengthEncode(s string) string {
e := make([]byte, 0, len(s))
for i := 0; i < len(s); i++ {
c := s[i]
j := i + 1
for ; j <= len(s); j++ {
if j < len(s) && s[j] == c {
continue
}
if j-i > 1 {
e = strconv.AppendInt(e, int64(j-i), 10)
}
e = append(e, c)
break
}
i = j - 1
}
return string(e)
}