Write it with golang.
[ca/:A1,A2,A3...,A149]
A1 stands for ID.
Now:
Pick two lines randomly, which one of them should have (A2,A3)=(1,1) and the other should have (A2,A3) != (1,1). One line as parent1, one line as parent2, the new line which will add back to the txt with A1=MaxID+1(MaxID is the maxA1 which is already existing in the txt) called offspring.
Offspring's A2 is picked randomly from parent1's A2, parent1's A3, parent2's A2 and parent2's A3 (one out of four). If offspring's A2 is from parent1, offspring's A3 should be picked randomly from parent2's A2 and parent2's A3 (one out of two). If offspring's A2 is from parent2, offspring's A3 should be picked randomly from parent1's A2 and parent1's A3 (one out of two).
Offspring's A4 is picked randomly from parent1's A4, parent1's A5, parent2's A4 and parent2's A5 (one out of four). If offspring's A4 is from parent1, offspring's A5 should be picked randomly from parent2's A4 and parent2's A5 (one out of two). If offspring's A4 is from parent2, offspring's A5 should be picked randomly from parent1's A4 and parent1's A5 (one out of two).
Offspring's (A6,A7,A8,A9) should be picked randomly = parent1's (A6,A7,A8,A9) or = parent2's (A6,A7,A8,A9) and add randomness to the mix, random offset between -10 and +10, but the value of (A6,A7,A8) within 0-255 limitation, A9 = 1.0.
Offspring's (A10,A11,A12) should be picked randomly = parent1's (A10,A11,A12), or = parent2's (A10,A11,A12).
If offspring's (A2,A3) = (1,1) or (2,2) , offspring's A13 is in the range from 0.25 to 0.5. If offspring's (A2,A3) != (1,1) or (2,2), offspring's A13 = 1.
Offspring's (A14,A15,A16) should be picked randomly = parent1's (A14,A15,A16), or = parent2's (A14,A15,A16).
If offspring's (A2,A3) = (1,1) or (2,2) , offspring's A17 is in the range from 0.25 to 0.5. If offspring's (A2,A3) != (1,1) or (2,2), offspring's A17 = 1.
Offspring's (A18,A19,A20) should be picked randomly = parent1's (A18,A19,A20), or = parent2's (A18,A19,A20).
If offspring's (A2,A3) = (1,1), offspring's A21 is in the range from 0.25 to 0.5. If offspring's (A2,A3) != (1,1), offspring's A21 = 0.
Offspring's (A22,A23,A24) should be picked randomly = parent1's (A22,A23,A24), or = parent2's (A22,A23,A24) .
If offspring's (A2,A3) = (1,1) or (2,2) , offspring's A25 = 0. If offspring's (A2,A3) != (1,1) or (2,2) , offspring's A25 = 1.
Offspring's (A26,A27,A28) should be picked randomly = parent1's (A26,A27,A28), or = parent2's (A26,A27,A28) .
If offspring's (A2,A3) = (1,1) or (2,2) , offspring's A29 = 0. If offspring's (A2,A3) != (1,1) or (2,2) , offspring's A29 = 1.
Offspring's (A30,A31,A32) should be picked randomly = parent1's (A30,A31,A32), or = parent2's (A30,A31,A32) .
If offspring's (A2,A3) = (1,1), offspring's A33 = 0. If offspring's (A2,A3) != (1,1), offspring's A33 = 1.
At first, offspring's A34 should be picked randomly from parent1's A34 and parent2's A34 (one out of two), offspring's A35 should be picked randomly from parent1's A35 and parent2's A35 (one out of two), offspring's A36 should be picked randomly from parent1's A36 and parent2's A36 (one out of two), offspring's A37 should be picked randomly from parent1's A37 and parent2's A37 (one out of two), offspring's A38 should be picked randomly from parent1's A38 and parent2's A38 (one out of two), offspring's A39 should be picked randomly from parent1's A39 and parent2's A39 (one out of two). But offspring's A34-A39 (which are six subjects) should randomly have 1-3 subjects being changed to be a different integer than it used to be, but the new integer should in the range between 1-10.
Offspring's A40 is a integer random out from the range between 1-10.
Offspring's A41 is a integer random out from the range between 1-10.
If offspring's (A2,A3,A4) = (1,1,1), offspring's A42 = 1. If offspring's (A2,A3,A4) = (1,1,2), offspring's A42 = 2. If offspring's (A2,A3,A4) = (1,1,3), offspring's A42 = 3. If offspring's (A2,A3,A4) = (2,2,1), offspring's A42 = 4. If offspring's (A2,A3,A4) = (2,2,2), offspring's A42 = 5. If offspring's (A2,A3,A4) = (2,2,3), offspring's A42 = 6. If offspring's (A2,A3,A4) = (1,2,1) or (2,1,1), offspring's A42 = 7. If offspring's (A2,A3,A4) = (1,2,2) or (2,1,2), offspring's A42 = 8. If offspring's (A2,A3,A4) = (1,2,3) or (2,1,3), offspring's A42 = 9.
If offspring's (A2,A3) = (1,1), offspring's A43 = A147. If offspring's (A2,A3) != (1,1), offspring's A43 = 404.
If offspring's (A2,A3) = (1,1), offspring's A44 = A147. If offspring's (A2,A3) != (1,1), offspring's A44 = 404.
If offspring's (A2,A3) = (1,1) or (2,2), offspring's A45 = 404. If offspring's (A2,A3) != (1,1) or (2,2), offspring's A44 = A147.
If offspring's (A2,A3) = (1,1), offspring's A46 = 404. If offspring's (A2,A3) != (1,1), offspring's A46 = A147.
Compared offspring's A47-A146, which integer is the biggest. For example, if A[i] is the biggest, A147 = ([i]-46).
Parent1's A1= offspring's A148, parent2's A1 = offspring's A149.
Please make sure the function of rules above will be well-functioned, make the codes short and clear, memories-friendly, merge similar structures so that code is not redundant. Give the whole code back.
Assistant
go
User
Yes, make it reusable, and thinking about like using Afield to make it shorter and shorter.
Assistant
Got it. To make the code reusable and more concise, I will:
Encapsulate the main logic into a function like CreateOffspring(parents []Line) (Line, error) which picks parents and creates offspring internally.
Use a helper function that accesses attributes by index called A(i int), or even better: have a slice A inside Line so we can do l.A[i].
Make Line a struct with a slice attribute: A []float64.
Avoid code repetition by making helper functions that operate on slices.
Provide a minimal example of usage.
Below is the refactored code:
go
User
package main
import (
"fmt"
"math"
"math/rand"
"time"
)
// Line holds 149 attributes named A1...A149
type Line struct {
A [149]float64
}
// Helper to get A-field 1-based (1 to 149)
func (l *Line) Afield(i int) float64 {
// i expected 1-based, convert to zero-based
return l.A[i-1]
}
func (l *Line) SetAfield(i int, v float64) {
l.A[i-1] = v
}
// CreateOffspring picks parents from lines then creates offspring
// parents: slice of existing lines
// Returns offspring or error if no eligible parents
func CreateOffspring(parents []Line) (Line, error) {
var parents1, parents2 []Line
maxID := 0
for _, l := range parents {
id := int(l.A[0])
if id > maxID {
maxID = id
}
a2, a3 := int(l.A[1]), int(l.A[2])
if a2 == 1 && a3 == 1 {
parents1 = append(parents1, l)
} else {
parents2 = append(parents2, l)
}
}
if len(parents1) == 0 || len(parents2) == 0 {
return Line{}, fmt.Errorf("not enough parents with (A2,A3)=(1,1) and others")
}
code
Assistant
Certainly! Your code is already very well structured. To make it shorter and clearer, I'll focus on:
Reducing repeated code by making generalized helper functions.
Using slices & loops more wisely (e.g., copying ranges).
Removing small inline helpers (like clamp) by inlining where used (since clamp is simple).
Replace multiple if-else blocks with helper booleans to clarify and shorten.
Use constants or slices where possible.
Here's a shorter, clean, and idiomatic version of your code (with comments removed for conciseness but you can re-add if needed):
// parseLine parses string like "[ca/:A1,A2,...,A149]"
func parseLine(line string) (Line, error) {
line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "[ca/:") || !strings.HasSuffix(line, "]") {
return Line{}, fmt.Errorf("bad format")
}
body := line[5 : len(line)-1]
parts := strings.Split(body, ",")
if len(parts) != 149 {
return Line{}, fmt.Errorf("expected 149 attributes but got %d", len(parts))
}
var l Line
for i, p := range parts {
v, err := strconv.ParseFloat(p, 64)
if err != nil {
return Line{}, err
}
l.A[i] = v
}
return l, nil
}
// serializeLine converts Line to string format "[ca/:A1,A2,...,A149]"
func serializeLine(l Line) string {
var parts []string
for i := 0; i < 149; i++ {
parts = append(parts, strconv.FormatFloat(l.A[i], 'f', -1, 64))
}
return "[ca/:" + strings.Join(parts, ",") + "]"
}
Your current approach is already quite memory-friendly (only reading the file once to index parents and only loading two parent lines into memory), but it can be improved slightly in readability and efficiency by:
Avoiding reading the entire file line-by-line as raw strings when indexing: reading using bufio.Scanner (simpler, safer).
Storing line offsets only if you absolutely want direct seeks (which is good). Otherwise, storing line numbers is simpler if lines have consistent length or you read twice.
Slightly reducing redundant code with helper functions.
Inline small functions if used once.
Here's a shorter, clean, memory-friendly full program implementing your request with the same logic — using line numbers instead of byte offsets (simpler, since lines are text lines). You lose the absolute seek speed, but gain much simpler code and no bookkeeping of byte offsets. For very big files, this is still memory friendly since only line number indexes are stored, which are ints.
go
User
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
type Line struct{ A [149]float64 }
func (l *Line) Get(i int) float64 { return l.A[i-1] }
func (l *Line) Set(i int, v float64) { l.A[i-1] = v }
func parseLine(s string) (Line, error) {
s = strings.TrimSpace(s)
if len(s) < 6 || !strings.HasPrefix(s, "[ca/:") || !strings.HasSuffix(s, "]") {
return Line{}, fmt.Errorf("invalid format")
}
parts := strings.Split(s[5:len(s)-1], ",")
if len(parts) != 149 {
return Line{}, fmt.Errorf("expected 149 attrs, got %d", len(parts))
}
var l Line
for i, p := range parts {
v, err := strconv.ParseFloat(p, 64)
if err != nil {
return Line{}, err
}
l.A[i] = v
}
return l, nil
}
func serializeLine(l Line) string {
parts := make([]string, 149)
for i := range l.A {
parts[i] = strconv.FormatFloat(l.A[i], 'f', -1, 64)
}
return "[ca/:" + strings.Join(parts, ",") + "]"
}
func pair11or22(a, b int) bool { return (a == 1 && b == 1) || (a == 2 && b == 2) }
func getA42(a2, a3, a4 int) int {
switch {
case a2 == 1 && a3 == 1 && a4 >= 1 && a4 <= 3:
return a4
case a2 == 2 && a3 == 2 && a4 >= 1 && a4 <= 3:
return a4 + 3
case (a2 == 1 && a3 == 2) || (a2 == 2 && a3 == 1):
if a4 >= 1 && a4 <= 3 {
return 6 + a4
}
}
return 0
}
func randChoice(vals ...float64) float64 {
return vals[rand.Intn(len(vals))]
}
func copyAttrs(dst *Line, src Line, from, to int) {
for i := from; i <= to; i++ {
dst.Set(i, src.Get(i))
}
}
func copyAttrsWithOffset(dst Line, src Line, from, to int) {
for i := from; i <= to; i++ {
base := int(src.Get(i))
offset := rand.Intn(21) - 10
if base+offset < 0 {
offset = -base
} else if base+offset > 255 {
offset = 255 - base
}
dst.Set(i, float64(base+offset))
}
}
func randFloat(min, max float64) float64 {
return min + rand.Float64()(max-min)
}
func CreateOffspring(p1, p2 Line, newID int) Line {
var off Line
off.Set(1, float64(newID))
p1a2, p1a3 := p1.Get(2), p1.Get(3)
p2a2, p2a3 := p2.Get(2), p2.Get(3)
// A2, A3
a2 := randChoice(p1a2, p1a3, p2a2, p2a3)
off.Set(2, a2)
if a2 == p1a2 || a2 == p1a3 {
off.Set(3, randChoice(p2a2, p2a3))
} else {
off.Set(3, randChoice(p1a2, p1a3))
}
a3 := int(off.Get(3))
// A4, A5
p1a4, p1a5 := p1.Get(4), p1.Get(5)
p2a4, p2a5 := p2.Get(4), p2.Get(5)
a4 := randChoice(p1a4, p1a5, p2a4, p2a5)
off.Set(4, a4)
if a4 == p1a4 || a4 == p1a5 {
off.Set(5, randChoice(p2a4, p2a5))
} else {
off.Set(5, randChoice(p1a4, p1a5))
}
a4i := int(a4)
// A6-A9
if rand.Intn(2) == 0 {
copyAttrsWithOffset(&off, p1, 6, 8)
} else {
copyAttrsWithOffset(&off, p2, 6, 8)
}
off.Set(9, 1)
// A10-A12
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 10, 12)
} else {
copyAttrs(&off, p2, 10, 12)
}
// A13
if pair11or22(int(a2), a3) {
off.Set(13, randFloat(0.25, 0.5))
} else {
off.Set(13, 1)
}
// A14-A16
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 14, 16)
} else {
copyAttrs(&off, p2, 14, 16)
}
// A17
if pair11or22(int(a2), a3) {
off.Set(17, randFloat(0.25, 0.5))
} else {
off.Set(17, 1)
}
// A18-A20
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 18, 20)
} else {
copyAttrs(&off, p2, 18, 20)
}
// A21
if int(a2) == 1 && a3 == 1 {
off.Set(21, randFloat(0.25, 0.5))
} else {
off.Set(21, 0)
}
// A22-A24
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 22, 24)
} else {
copyAttrs(&off, p2, 22, 24)
}
// A25
if pair11or22(int(a2), a3) {
off.Set(25, 0)
} else {
off.Set(25, 1)
}
// A26-A28
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 26, 28)
} else {
copyAttrs(&off, p2, 26, 28)
}
// A29
if pair11or22(int(a2), a3) {
off.Set(29, 0)
} else {
off.Set(29, 1)
}
// A30-A32
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 30, 32)
} else {
copyAttrs(&off, p2, 30, 32)
}
// A33
if int(a2) == 1 && a3 == 1 {
off.Set(33, 0)
} else {
off.Set(33, 1)
}
// A34-A39 with mutation
for i := 34; i <= 39; i++ {
if rand.Intn(2) == 0 {
off.Set(i, p1.Get(i))
} else {
off.Set(i, p2.Get(i))
}
}
mutCount := rand.Intn(3) + 1
perm := rand.Perm(6)
for i := 0; i < mutCount; i++ {
off.Set(34+perm[i], float64(rand.Intn(10)+1))
}
// A40, A41
off.Set(40, float64(rand.Intn(10)+1))
off.Set(41, float64(rand.Intn(10)+1))
// A42
off.Set(42, float64(getA42(int(a2), a3, a4i)))
// A47-A146 sum
for i := 47; i <= 146; i++ {
off.Set(i, p1.Get(i)+p2.Get(i))
}
maxVal, maxIdx := off.Get(47), 47
for i := 48; i <= 146; i++ {
if v := off.Get(i); v > maxVal {
maxVal, maxIdx = v, i
}
}
off.Set(147, float64(maxIdx-46))
a147 := off.Get(147)
setIf := func(cond bool, idx int, t, f float64) {
if cond {
off.Set(idx, t)
} else {
off.Set(idx, f)
}
}
// A43-A46
setIf(int(a2) == 1 && a3 == 1, 43, a147, 404)
setIf(int(a2) == 1 && a3 == 1, 44, a147, 404)
setIf(pair11or22(int(a2), a3), 45, 404, a147)
setIf(int(a2) == 1 && a3 == 1, 46, 404, a147)
// A148, A149
off.Set(148, p1.Get(1))
off.Set(149, p2.Get(1))
return off
}
func readLineByNumber(filename string, number int) (Line, error) {
f, err := os.Open(filename)
if err != nil {
return Line{}, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for i := 0; i < number; i++ {
if !scanner.Scan() {
return Line{}, fmt.Errorf("line %d not found", number)
}
}
return parseLine(scanner.Text())
}
func main() {
rand.Seed(time.Now().UnixNano())
filename := "CA.txt"
f, err := os.Open(filename)
if err != nil {
panic(err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
var parents1Lines, parents2Lines []int
maxID := 0
lineNum := 0
for scanner.Scan() {
lineNum++
l, err := parseLine(scanner.Text())
if err != nil {
panic(err)
}
id := int(l.Get(1))
if id > maxID {
maxID = id
}
a2, a3 := int(l.Get(2)), int(l.Get(3))
if a2 == 1 && a3 == 1 {
parents1Lines = append(parents1Lines, lineNum)
} else {
parents2Lines = append(parents2Lines, lineNum)
}
}
if len(parents1Lines) == 0 || len(parents2Lines) == 0 {
panic("Not enough parents of required types.")
}
// Load one random parent from each group by line number:
p1, err := readLineByNumber(filename, parents1Lines[rand.Intn(len(parents1Lines))])
if err != nil {
panic(err)
}
p2, err := readLineByNumber(filename, parents2Lines[rand.Intn(len(parents2Lines))])
if err != nil {
panic(err)
}
offspring := CreateOffspring(p1, p2, maxID+1)
// Append offspring to file
fw, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
defer fw.Close()
if _, err := fmt.Fprintln(fw, serializeLine(offspring)); err != nil {
panic(err)
}
fmt.Println("Offspring created with ID:", int(offspring.Get(1)))
}
The output of offspring should be at a new line in txt.
Assistant
Your current code already appends the offspring on a new line with fmt.Fprintln(). This writes the serialized offspring line and adds a newline (\n) automatically.
err = ensureFileEndsWithNewline(filename)
if err != nil {
panic(err)
}
Otherwise your code is perfect for adding offspring on a new line.
Summary
Your code:
Reads parents from the file.
Creates offspring.
Opens file in append mode.
Writes offspring line with newline.
This appends the offspring at a new line.
Minimal example to test
go
package main
import (
"fmt"
"os"
)
func main() {
f, err := os.OpenFile("test.txt", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
defer f.Close()
// This will append with newline at end
fmt.Fprintln(f, "This is a new offspring line")
}
Run it multiple times, you will see new lines appended each time.
If you want me to help you integrate the ensureFileEndsWithNewline helper or any other improvement just ask!
User
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
// Where the output will be stored
const filename = "CA.txt"
// getNextID reads existing data from the file and returns the next NPC ID
func getNextID() int {
file, err := os.Open(filename)
if err != nil {
// No file exists, ID starts from 2
return 2
}
defer file.Close()
maxID := 0
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || !strings.HasPrefix(line, "[ca/:") {
continue
}
line = strings.TrimPrefix(line, "[ca/:")
parts := strings.Split(line, ",")
if len(parts) == 0 {
continue
}
idStr := parts[0]
id, err := strconv.Atoi(idStr)
if err == nil && id > maxID {
maxID = id
}
}
return maxID + 1
}
// C represents a color with R, G, B as int and A as float64
type C struct {
R, G, B int
A float64
}
// rC generates a random color with RGBA channels within the specified ranges
func rC(rMin, rMax, gMin, gMax, bMin, bMax int, aMin, aMax float64) C {
return C{
R: rand.Intn(rMax-rMin+1) + rMin,
G: rand.Intn(gMax-gMin+1) + gMin,
B: rand.Intn(bMax-bMin+1) + bMin,
A: aMin + rand.Float64()(aMax-aMin),
}
}
// Predefined color palettes: Morandi, Macaron, and none (transparent)
func moC() C {
return rC(0, 255, 0, 255, 0, 255, 0.25, 0.5)
}
func maC() C {
return rC(0, 255, 0, 255, 0, 255, 1.0, 1.0)
}
var nC = C{0, 0, 0, 0}
// habCeCtCwsbCwspCaCInts2Intf converts color struct to []interface{} containing R, G, B, and A255 rounded
func habCeCtCwsbCwspCaCInts2Intf(c C) []interface{} {
return []interface{}{c.R, c.G, c.B, c.A}
}
// dbyS determines body shape based on firstsexgenes, ((1,1),(2,2),others) = (op 1-3,op 7-9,op 4-6)
func dbyS(fsg1, fsg2 int) int {
switch {
case fsg1 == 1 && fsg2 == 1:
return rand.Intn(3) + 1
case fsg1 == 2 && fsg2 == 2:
return rand.Intn(3) + 7
default:
return rand.Intn(3) + 4
}
}
// dtlSthSwSaS determines tail, tooth, wing, antenna shape based on firstsexgenes (op 1-100, op 404 = no shape)
func dtlSthSwSaS(fsg1, fsg2, maxID int) (int, int, int, int) {
switch {
case fsg1 == 1 && fsg2 == 1:
return maxID, maxID, 404, 404
case fsg1 == 2 && fsg2 == 2:
return 404, 404, 404, maxID
default:
return 404, 404, maxID, maxID
}
}
// rBarP generates random bloodlineIDs and random percentage, with one random bloodlineID assigned 100% (1.0), rest 0%
func rBarP() ([]int, []float64) {
t := 100
rB := make([]int, t)
rP := make([]float64, t)
for i := range rB {
rB[i] = i + 1
}
// Pick one random bloodlineID to have percentage 1
hBID := rand.Intn(t)
rP[hBID] = 1.0
return rB, rP
}
// fhBID finds the bloodlineID with the highest percentage
func fhBID(rB []int, rP []float64) int {
hBID := 0
for i := 1; i < len(rP); i++ {
if rP[i] > rP[hBID] {
hBID = i
}
}
return rB[hBID]
}
// gNPC generates a random NPC with all attributes
func gNPC() []interface{} {
// Get the next sequential NPC ID
playerID := getNextID()
// Firstsexgene1, firstsexgene2 (op 1-2); secondsexgene1, secondsexgene2 (op 1-3)
fsg1, fsg2 := rand.Intn(2)+1, rand.Intn(2)+1
ssg1, ssg2 := rand.Intn(3)+1, rand.Intn(3)+1
// Skin colors (predefined realistic RGBA range)
sC := []interface{}{rand.Intn(56) + 200, rand.Intn(51) + 100, rand.Intn(51) + 80, 1.0}
// Determine color palettes for hairandbrow, eye, tail, wingsub, wingstripe and antenna color based on firstsexgenes combination
var habC, eC, tC, wsbC, wspC, aC C
switch {
case fsg1 == 1 && fsg2 == 1:
habC, eC, tC = moC(), moC(), moC()
wsbC, wspC, aC = nC, nC, nC
case fsg1 == 2 && fsg2 == 2:
habC, eC = moC(), moC()
tC, wsbC, wspC = nC, nC, nC
aC = maC()
default:
habC, eC, wsbC, wspC, aC = maC(), maC(), maC(), maC(), maC()
tC = nC
}
// Random shape attributes for face, brow, eye, ear, nose, mouth, fronthair, backhair, body, tail, tooth, wing and antenna shape (op 1-10)
rS := func() int { return rand.Intn(10) + 1 }
fS, bwS, eeS, erS, nS, mS, fhS, bhS := rS(), rS(), rS(), rS(), rS(), rS(), rS(), rS()
byS := dbyS(fsg1, fsg2)
// Random bloodlineIDs and bloodline percentages
BID, BP := rBarP()
maxBID := fhBID(BID, BP)
// Random shape attributes for tail, tooth, wing and antenna shape based on firstsexgenes combination
tlS, thS, wS, aS := dtlSthSwSaS(fsg1, fsg2, maxBID)
// Prepare output slice with preallocated capacity
outLen := 5 + len(sC) + 6len(BID) + 1
output := make([]interface{}, 0, outLen)
output = append(output, playerID, fsg1, fsg2, ssg1, ssg2)
for _, v := range sC {
output = append(output, v)
}
for _, c := range []C{habC, eC, tC, wsbC, wspC, aC} {
output = append(output, habCeCtCwsbCwspCaCInts2Intf(c)...)
}
output = append(output, fS, bwS, eeS, erS, nS, mS, fhS, bhS, byS, tlS, thS, wS, aS)
// Append bloodline percentages (float64)
for _, p := range BP {
output = append(output, p)
}
// Append maxBloodlineID
output = append(output, maxBID)
return output
}
// formatOutput formats the NPC data in the expected string format
func formatOutput(data []interface{}) string {
parts := make([]string, len(data))
for i, v := range data {
switch val := v.(type) {
case float64:
// Format floats with one decimal place
parts[i] = fmt.Sprintf("%.1f", val)
default:
parts[i] = fmt.Sprint(v)
}
}
return "[ca/:" + strings.Join(parts, ",") + "]"
}
// appendToFile appends the string to the output file (creates it if not exist)
func appendToFile(text string) {
f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer f.Close()
_, err = f.WriteString(text + "\n")
if err != nil {
fmt.Println("Error writing to file:", err)
}
}
// Start NPC generation
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("Press 'R' then Enter to generate a random NPC...")
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("> ")
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
if strings.EqualFold(input, "r") {
npc := gNPC()
// parent ID = 1 means orphan - append for completeness
npc = append(npc, 1, 1)
output := formatOutput(npc)
fmt.Println(output)
appendToFile(output)
} else {
fmt.Println("Please press 'R' then Enter to generate a random NPC.")
}
}
}
// Skin colors (predefined realistic RGBA range)
sC := []interface{}{rand.Intn(56) + 200, rand.Intn(51) + 100, rand.Intn(51) + 80, 1.0} -> if fsg1 == 1 && fsg2 == 1 or fsg1 == 2 && fsg2 == 2, change 1.0 to within 0.25-0.5 limitation, if not, still remain as 1.0. Can you change that with //●to highlight the corrected code to me?
Assistant
Certainly! Here's your original gNPC function with the skin color alpha channel modified according to your rules:
If (fsg1,fsg2) == (1,1)or(2,2), then alpha = random float in [0.25, 0.5]//● Corrected here
Else alpha = 1.0
I added comments //● where the change is.
go
func gNPC() []interface{} {
// Get the next sequential NPC ID
playerID := getNextID()
// Firstsexgene1, firstsexgene2 (op 1-2); secondsexgene1, secondsexgene2 (op 1-3)
fsg1, fsg2 := rand.Intn(2)+1, rand.Intn(2)+1
ssg1, ssg2 := rand.Intn(3)+1, rand.Intn(3)+1
// Skin colors (predefined realistic RGBA range)
var alpha float64
if (fsg1 == 1 && fsg2 == 1) || (fsg1 == 2 && fsg2 == 2) {
alpha = 0.25 + rand.Float64()*(0.5-0.25) //● changed alpha range if (1,1) or (2,2)
} else {
alpha = 1.0
}
sC := []interface{}{rand.Intn(56) + 200, rand.Intn(51) + 100, rand.Intn(51) + 80, alpha} //● set alpha here
// Determine color palettes for hairandbrow, eye, tail, wingsub, wingstripe and antenna color based on firstsexgenes combination
var habC, eC, tC, wsbC, wspC, aC C
switch {
case fsg1 == 1 && fsg2 == 1:
habC, eC, tC = moC(), moC(), moC()
wsbC, wspC, aC = nC, nC, nC
case fsg1 == 2 && fsg2 == 2:
habC, eC = moC(), moC()
tC, wsbC, wspC = nC, nC, nC
aC = maC()
default:
habC, eC, wsbC, wspC, aC = maC(), maC(), maC(), maC(), maC()
tC = nC
}
// Random shape attributes for face, brow, eye, ear, nose, mouth, fronthair, backhair, body, tail, tooth, wing and antenna shape (op 1-10)
rS := func() int { return rand.Intn(10) + 1 }
fS, bwS, eeS, erS, nS, mS, fhS, bhS := rS(), rS(), rS(), rS(), rS(), rS(), rS(), rS()
byS := dbyS(fsg1, fsg2)
// Random bloodlineIDs and bloodline percentages
BID, BP := rBarP()
maxBID := fhBID(BID, BP)
// Random shape attributes for tail, tooth, wing and antenna shape based on firstsexgenes combination
tlS, thS, wS, aS := dtlSthSwSaS(fsg1, fsg2, maxBID)
// Prepare output slice with preallocated capacity
outLen := 5 + len(sC) + 6*4 + 10 + 2*len(BID) + 1
output := make([]interface{}, 0, outLen)
output = append(output, playerID, fsg1, fsg2, ssg1, ssg2)
for _, v := range sC {
output = append(output, v)
}
for _, c := range []C{habC, eC, tC, wsbC, wspC, aC} {
output = append(output, habCeCtCwsbCwspCaCInts2Intf(c)...)
}
output = append(output, fS, bwS, eeS, erS, nS, mS, fhS, bhS, byS, tlS, thS, wS, aS)
// Append bloodline percentages (float64)
for _, p := range BP {
output = append(output, p)
}
// Append maxBloodlineID
output = append(output, maxBID)
return output
}
User
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
type Line struct{ A [149]float64 }
func (l *Line) Get(i int) float64 { return l.A[i-1] }
func (l *Line) Set(i int, v float64) { l.A[i-1] = v }
func parseLine(s string) (Line, error) {
s = strings.TrimSpace(s)
if len(s) < 6 || !strings.HasPrefix(s, "[ca/:") || !strings.HasSuffix(s, "]") {
return Line{}, fmt.Errorf("invalid format")
}
parts := strings.Split(s[5:len(s)-1], ",")
if len(parts) != 149 {
return Line{}, fmt.Errorf("expected 149 attrs, got %d", len(parts))
}
var l Line
for i, p := range parts {
v, err := strconv.ParseFloat(p, 64)
if err != nil {
return Line{}, err
}
l.A[i] = v
}
return l, nil
}
func serializeLine(l Line) string {
parts := make([]string, 149)
for i := range l.A {
parts[i] = strconv.FormatFloat(l.A[i], 'f', -1, 64)
}
return "[ca/:" + strings.Join(parts, ",") + "]"
}
func pair11or22(a, b int) bool { return (a == 1 && b == 1) || (a == 2 && b == 2) }
func getA42(a2, a3, a4 int) int {
switch {
case a2 == 1 && a3 == 1 && a4 >= 1 && a4 <= 3:
return a4
case a2 == 2 && a3 == 2 && a4 >= 1 && a4 <= 3:
return a4 + 3
case (a2 == 1 && a3 == 2) || (a2 == 2 && a3 == 1):
if a4 >= 1 && a4 <= 3 {
return 6 + a4
}
}
return 0
}
func randChoice(vals ...float64) float64 {
return vals[rand.Intn(len(vals))]
}
func copyAttrs(dst *Line, src Line, from, to int) {
for i := from; i <= to; i++ {
dst.Set(i, src.Get(i))
}
}
func copyAttrsWithOffset(dst Line, src Line, from, to int) {
for i := from; i <= to; i++ {
base := int(src.Get(i))
offset := rand.Intn(21) - 10
if base+offset < 0 {
offset = -base
} else if base+offset > 255 {
offset = 255 - base
}
dst.Set(i, float64(base+offset))
}
}
func randFloat(min, max float64) float64 {
return min + rand.Float64()(max-min)
}
func CreateOffspring(p1, p2 Line, newID int) Line {
var off Line
off.Set(1, float64(newID))
p1a2, p1a3 := p1.Get(2), p1.Get(3)
p2a2, p2a3 := p2.Get(2), p2.Get(3)
// A2, A3
a2 := randChoice(p1a2, p1a3, p2a2, p2a3)
off.Set(2, a2)
if a2 == p1a2 || a2 == p1a3 {
off.Set(3, randChoice(p2a2, p2a3))
} else {
off.Set(3, randChoice(p1a2, p1a3))
}
a3 := int(off.Get(3))
// A4, A5
p1a4, p1a5 := p1.Get(4), p1.Get(5)
p2a4, p2a5 := p2.Get(4), p2.Get(5)
a4 := randChoice(p1a4, p1a5, p2a4, p2a5)
off.Set(4, a4)
if a4 == p1a4 || a4 == p1a5 {
off.Set(5, randChoice(p2a4, p2a5))
} else {
off.Set(5, randChoice(p1a4, p1a5))
}
a4i := int(a4)
// A6-A9
if rand.Intn(2) == 0 {
copyAttrsWithOffset(&off, p1, 6, 8)
} else {
copyAttrsWithOffset(&off, p2, 6, 8)
}
off.Set(9, 1)
// A10-A12
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 10, 12)
} else {
copyAttrs(&off, p2, 10, 12)
}
// A13
if pair11or22(int(a2), a3) {
off.Set(13, randFloat(0.25, 0.5))
} else {
off.Set(13, 1)
}
// A14-A16
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 14, 16)
} else {
copyAttrs(&off, p2, 14, 16)
}
// A17
if pair11or22(int(a2), a3) {
off.Set(17, randFloat(0.25, 0.5))
} else {
off.Set(17, 1)
}
// A18-A20
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 18, 20)
} else {
copyAttrs(&off, p2, 18, 20)
}
// A21
if int(a2) == 1 && a3 == 1 {
off.Set(21, randFloat(0.25, 0.5))
} else {
off.Set(21, 0)
}
// A22-A24
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 22, 24)
} else {
copyAttrs(&off, p2, 22, 24)
}
// A25
if pair11or22(int(a2), a3) {
off.Set(25, 0)
} else {
off.Set(25, 1)
}
// A26-A28
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 26, 28)
} else {
copyAttrs(&off, p2, 26, 28)
}
// A29
if pair11or22(int(a2), a3) {
off.Set(29, 0)
} else {
off.Set(29, 1)
}
// A30-A32
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 30, 32)
} else {
copyAttrs(&off, p2, 30, 32)
}
// A33
if int(a2) == 1 && a3 == 1 {
off.Set(33, 0)
} else {
off.Set(33, 1)
}
// A34-A39 with mutation
for i := 34; i <= 39; i++ {
if rand.Intn(2) == 0 {
off.Set(i, p1.Get(i))
} else {
off.Set(i, p2.Get(i))
}
}
mutCount := rand.Intn(3) + 1
perm := rand.Perm(6)
for i := 0; i < mutCount; i++ {
off.Set(34+perm[i], float64(rand.Intn(10)+1))
}
// A40, A41
off.Set(40, float64(rand.Intn(10)+1))
off.Set(41, float64(rand.Intn(10)+1))
// A42
off.Set(42, float64(getA42(int(a2), a3, a4i)))
// A47-A146 sum
for i := 47; i <= 146; i++ {
off.Set(i, p1.Get(i)+p2.Get(i))
}
maxVal, maxIdx := off.Get(47), 47
for i := 48; i <= 146; i++ {
if v := off.Get(i); v > maxVal {
maxVal, maxIdx = v, i
}
}
off.Set(147, float64(maxIdx-46))
a147 := off.Get(147)
setIf := func(cond bool, idx int, t, f float64) {
if cond {
off.Set(idx, t)
} else {
off.Set(idx, f)
}
}
// A43-A46
setIf(int(a2) == 1 && a3 == 1, 43, a147, 404)
setIf(int(a2) == 1 && a3 == 1, 44, a147, 404)
setIf(pair11or22(int(a2), a3), 45, 404, a147)
setIf(int(a2) == 1 && a3 == 1, 46, 404, a147)
// A148, A149
off.Set(148, p1.Get(1))
off.Set(149, p2.Get(1))
return off
}
func readLineByNumber(filename string, number int) (Line, error) {
f, err := os.Open(filename)
if err != nil {
return Line{}, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for i := 0; i < number; i++ {
if !scanner.Scan() {
return Line{}, fmt.Errorf("line %d not found", number)
}
}
return parseLine(scanner.Text())
}
func main() {
rand.Seed(time.Now().UnixNano())
filename := "CA.txt"
f, err := os.Open(filename)
if err != nil {
panic(err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
var parents1Lines, parents2Lines []int
maxID := 0
lineNum := 0
for scanner.Scan() {
lineNum++
l, err := parseLine(scanner.Text())
if err != nil {
panic(err)
}
id := int(l.Get(1))
if id > maxID {
maxID = id
}
a2, a3 := int(l.Get(2)), int(l.Get(3))
if a2 == 1 && a3 == 1 {
parents1Lines = append(parents1Lines, lineNum)
} else {
parents2Lines = append(parents2Lines, lineNum)
}
}
if len(parents1Lines) == 0 || len(parents2Lines) == 0 {
panic("Not enough parents of required types.")
}
// Load one random parent from each group by line number:
p1, err := readLineByNumber(filename, parents1Lines[rand.Intn(len(parents1Lines))])
if err != nil {
panic(err)
}
p2, err := readLineByNumber(filename, parents2Lines[rand.Intn(len(parents2Lines))])
if err != nil {
panic(err)
}
offspring := CreateOffspring(p1, p2, maxID+1)
// Append offspring to file
fw, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
defer fw.Close()
if _, err := fmt.Fprintln(fw, serializeLine(offspring)); err != nil {
panic(err)
}
fmt.Println("Offspring created with ID:", int(offspring.Get(1)))
}
// Offspring's (A6,A7,A8,A9) should be picked randomly = parent1's (A6,A7,A8,A9) or = parent2's (A6,A7,A8,A9) and add randomness to the mix, random offset between -10 and +10, but the value of (A6,A7,A8) within 0-255 limitation, A9 within 0.25-1 if offspring's (A2,A3) = (1,1) or (2,2), A9 =1 if offspring's (A2,A3) != (1,1) or (2,2).
highlight the corrected code with //●
Assistant
Certainly! Below is the corrected part of your CreateOffspring function for (A6, A7, A8, A9) specifically addressing the new requirement for A9:
(A6, A7, A8) picked randomly from one parent with offsets [-10..+10] clamped to 0-255 (same as before).
A9 picked from the same parent’s A9, but then:
If offspring’s (A2, A3) = (1,1) or (2,2), multiply A9 by random float in [0.25, 1] — ●NEW
Else A9 = 1 — ●NEW
Replace your original A6-A9 block inside CreateOffspring:
// A6-A9 ● corrected: pick (A6-A9) block from one parent with offset on A6-A8 and adjusted A9 based on (A2,A3)
var baseParent Line
if rand.Intn(2) == 0 {
baseParent = p1
} else {
baseParent = p2
}
// Copy & offset A6-A8
for i := 6; i <= 8; i++ {
base := int(baseParent.Get(i))
offset := rand.Intn(21) - 10
v := base + offset
if v < 0 {
v = 0
} else if v > 255 {
v = 255
}
off.Set(i, float64(v))
}
// Set A9 with adjustment ●
origA9 := baseParent.Get(9)
a2Off, a3Off := int(off.Get(2)), int(off.Get(3))
if pair11or22(a2Off, a3Off) {
off.Set(9, origA9*randFloat(0.25, 1.0)) // ● A9 in [0.25*origA9, origA9]
} else {
off.Set(9, 1.0) // ● A9=1 if not (1,1) or (2,2)
}
Explanation:
We randomly select baseParent either p1 or p2.
Copy attributes 6 to 8 with offsets in the range [-10,10] clamped to [0,255].
User
Can A9 use the function way like A13? Your corrected answer seems to long.
Assistant
Absolutely! You can shorten the A9 logic by putting it into a small helper function, similar to how you handle A13. This keeps your CreateOffspring clean and concise.
Then in CreateOffspring, your A6-A9 block becomes:
go
// A6-A9 (short and clean)
var baseParent Line
if rand.Intn(2) == 0 {
baseParent = p1
} else {
baseParent = p2
}
for i := 6; i <= 8; i++ {
base := int(baseParent.Get(i))
offset := rand.Intn(21) - 10
v := base + offset
if v < 0 {
v = 0
} else if v > 255 {
v = 255
}
off.Set(i, float64(v))
}
off.Set(9, calcA9(baseParent.Get(9), int(off.Get(2)), int(off.Get(3))))
Summary:
calcA9 encapsulates your A9 logic similar to A13.
CreateOffspring stays neat and readable.
Keeps randomness & clamping for A6-A8 and A9 logic clean.
If you want, I can provide the full updated code snippet with this helper integrated!
package main
import (
"bufio"
"fmt"
"log"
"math"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
const (
numAttributes = 149
)
// Line holds the attributes, A1..A149
// Using float64 for all (int attributes stored as float64)
type Line [numAttributes]float64
func parseLine(line string) (Line, error) {
// line format: [ca/:A1,A2,A3,...,A149]
line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "[ca/:") || !strings.HasSuffix(line, "]") {
return Line{}, fmt.Errorf("line format invalid: %q", line)
}
content := line[5 : len(line)-1]
parts := strings.Split(content, ",")
if len(parts) != numAttributes {
return Line{}, fmt.Errorf("expected %d attributes, got %d", numAttributes, len(parts))
}
var l Line
for i, p := range parts {
v, err := strconv.ParseFloat(p, 64)
if err != nil {
return Line{}, fmt.Errorf("parse error at attribute %d: %v", i+1, err)
}
l[i] = v
}
return l, nil
}
func lineToString(l Line) string {
parts := make([]string, numAttributes)
for i, v := range l {
// Write as int if it's an integer, else float format
if math.Mod(v, 1) == 0 {
parts[i] = strconv.Itoa(int(v))
} else {
// format with 6 decimals max
parts[i] = strconv.FormatFloat(v, 'f', 6, 64)
}
}
return "[ca/:" + strings.Join(parts, ",") + "]"
}
func randChoiceFloat64(arr []float64) float64 {
return arr[rand.Intn(len(arr))]
}
func randChoiceLineSlice(arr []Line) Line {
return arr[rand.Intn(len(arr))]
}
func clampInt(val, min, max int) int {
if val < min {
return min
}
if val > max {
return max
}
return val
}
func clampFloat(val, min, max float64) float64 {
if val < min {
return min
}
if val > max {
return max
}
return val
}
func copySliceFloat64(src []float64) []float64 {
dest := make([]float64, len(src))
copy(dest, src)
return dest
}
// Checks if (A2,A3) = (1,1)
func isA2A3_11(l Line) bool { return int(l[1]) == 1 && int(l[2]) == 1 }
// Checks if (A2,A3) = (2,2)
func isA2A3_22(l Line) bool { return int(l[1]) == 2 && int(l[2]) == 2 }
// Returns true if (A2,A3) == (1,1) or (2,2)
func isA2A3_11or22(l Line) bool {
return (int(l[1]) == 1 && int(l[2]) == 1) || (int(l[1]) == 2 && int(l[2]) == 2)
}
// Checks if (A2,A3,A4) matches any provided tuple (a,b,c) else returns -1
func getA42Val(a2, a3, a4 int) int {
switch {
case a2 == 1 && a3 == 1 && a4 == 1:
return 1
case a2 == 1 && a3 == 1 && a4 == 2:
return 2
case a2 == 1 && a3 == 1 && a4 == 3:
return 3
case a2 == 2 && a3 == 2 && a4 == 1:
return 4
case a2 == 2 && a3 == 2 && a4 == 2:
return 5
case a2 == 2 && a3 == 2 && a4 == 3:
return 6
case (a2 == 1 && a3 == 2 && a4 == 1) || (a2 == 2 && a3 == 1 && a4 == 1):
return 7
case (a2 == 1 && a3 == 2 && a4 == 2) || (a2 == 2 && a3 == 1 && a4 == 2):
return 8
case (a2 == 1 && a3 == 2 && a4 == 3) || (a2 == 2 && a3 == 1 && a4 == 3):
return 9
default:
return -1
}
}
func main() {
rand.Seed(time.Now().UnixNano())
// Load lines from file
lines, maxID, err := loadLinesFromFile("input.txt")
if err != nil {
log.Fatal(err)
}
// Step 1: pick parent1 with (A2,A3)=(1,1) and parent2 with (A2,A3)!=(1,1)
var parents1, parents2 []Line
for _, l := range lines {
if isA2A3_11(l) {
parents1 = append(parents1, l)
} else {
parents2 = append(parents2, l)
}
}
if len(parents1) == 0 || len(parents2) == 0 {
log.Fatal("Not enough parents for breeding")
}
parent1 := parents1[rand.Intn(len(parents1))]
parent2 := parents2[rand.Intn(len(parents2))]
offspring := createOffspring(parent1, parent2, maxID+1)
// Append offspring to lines
lines = append(lines, offspring)
// Write back to output file
err = writeLinesToFile("output.txt", lines)
if err != nil {
log.Fatal(err)
}
fmt.Println("Offspring created and appended successfully")
}
func loadLinesFromFile(filename string) ([]Line, int, error) {
file, err := os.Open(filename)
if err != nil {
return nil, 0, err
}
defer file.Close()
var lines []Line
scanner := bufio.NewScanner(file)
maxID := 0
for scanner.Scan() {
lineStr := scanner.Text()
l, err := parseLine(lineStr)
if err != nil {
return nil, 0, err
}
lines = append(lines, l)
// Track maxID (A1)
id := int(l[0])
if id > maxID {
maxID = id
}
}
if err := scanner.Err(); err != nil {
return nil, 0, err
}
return lines, maxID, nil
}
func writeLinesToFile(filename string, lines []Line) error {
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
w := bufio.NewWriter(file)
for _, l := range lines {
_, err := w.WriteString(lineToString(l) + "\n")
if err != nil {
return err
}
}
return w.Flush()
}
func createOffspring(p1, p2 Line, newID int) Line {
var off Line
off[0] = float64(newID) // A1 = MaxID+1
// Rule 2: Offspring's A2 is randomly picked from p1's A2,A3,p2's A2,A3
optsA2 := []float64{p1[1], p1[2], p2[1], p2[2]}
off[1] = randChoiceFloat64(optsA2)
// If offspring's A2 from p1 -> offspring's A3 from p2's A2,A3
// Else from p1's A2,A3
if off[1] == p1[1] || off[1] == p1[2] {
off[2] = randChoiceFloat64([]float64{p2[1], p2[2]})
} else {
off[2] = randChoiceFloat64([]float64{p1[1], p1[2]})
}
// Rule 3: A4 from p1's A4,A5,p2's A4,A5
optsA4 := []float64{p1[3], p1[4], p2[3], p2[4]}
off[3] = randChoiceFloat64(optsA4)
// A5 depends on A4 origin same principle as A2/A3
if off[3] == p1[3] || off[3] == p1[4] {
off[4] = randChoiceFloat64([]float64{p2[3], p2[4]})
} else {
off[4] = randChoiceFloat64([]float64{p1[3], p1[4]})
}
// Rule 4: (A6-A9) from either parent + random offset [-10..10] for A6-A8
if rand.Intn(2) == 0 {
copyAttributesWithOffset(&off, p1, 5, 8)
} else {
copyAttributesWithOffset(&off, p2, 5, 8)
}
off[8] = 1.0 // A9 = 1.0
// Rule 5: (A10,A11,A12) randomly from p1 or p2
if rand.Intn(2) == 0 {
copyBlock(&off, p1, 9, 11)
} else {
copyBlock(&off, p2, 9, 11)
}
a2, a3 := int(off[1]), int(off[2])
// Rule 6: A13
if (a2 == 1 && a3 == 1) || (a2 == 2 && a3 == 2) {
off[12] = randFloatRange(0.25, 0.5)
} else {
off[12] = 1
}
// Rule 7: (A14,A15,A16) from p1 or p2
if rand.Intn(2) == 0 {
copyBlock(&off, p1, 13, 15)
} else {
copyBlock(&off, p2, 13, 15)
}
// Rule 8: A17
if (a2 == 1 && a3 == 1) || (a2 == 2 && a3 == 2) {
off[16] = randFloatRange(0.25, 0.5)
} else {
off[16] = 1
}
// Rule 9: (A18,A19,A20)
if rand.Intn(2) == 0 {
copyBlock(&off, p1, 17, 19)
} else {
copyBlock(&off, p2, 17, 19)
}
// Rule 10: A21
if a2 == 1 && a3 == 1 {
off[20] = randFloatRange(0.25, 0.5)
} else {
off[20] = 0
}
// Rule 11: (A22,A23,A24)
if rand.Intn(2) == 0 {
copyBlock(&off, p1, 21, 23)
} else {
copyBlock(&off, p2, 21, 23)
}
// Rule 12: A25
if (a2 == 1 && a3 == 1) || (a2 == 2 && a3 == 2) {
off[24] = 0
} else {
off[24] = 1
}
// Rule 13: (A26,A27,A28)
if rand.Intn(2) == 0 {
copyBlock(&off, p1, 25, 27)
} else {
copyBlock(&off, p2, 25, 27)
}
// Rule 14: A29
if (a2 == 1 && a3 == 1) || (a2 == 2 && a3 == 2) {
off[28] = 0
} else {
off[28] = 1
}
// Rule 15: (A30,A31,A32)
if rand.Intn(2) == 0 {
copyBlock(&off, p1, 29, 31)
} else {
copyBlock(&off, p2, 29, 31)
}
// Rule 16: A33
if a2 == 1 && a3 == 1 {
off[32] = 0
} else {
off[32] = 1
}
// Rule 17: A34-A39 first picked randomly from parents, then mutate 1-3 of them to random int in [1..10]
for i := 33; i <= 38; i++ {
if rand.Intn(2) == 0 {
off[i] = p1[i]
} else {
off[i] = p2[i]
}
}
// Mutate 1-3 subjects
mutationsCount := rand.Intn(3) + 1
indices := rand.Perm(6)[:mutationsCount]
for _, idx := range indices {
off[33+idx] = float64(rand.Intn(10) + 1) // random int [1..10]
}
// Rule 18: A40 random int 1..10
off[39] = float64(rand.Intn(10) + 1)
// Rule 19: A41 random int 1..10
off[40] = float64(rand.Intn(10) + 1)
// Rule 20: A42 depends on (A2,A3,A4)
a4 := int(off[3])
a42 := getA42Val(a2, a3, a4)
if a42 != -1 {
off[41] = float64(a42)
} else {
off[41] = 0
}
// Rule 21,22:
// If (A2,A3)=(1,1) => A43=A147, A44=A147, else =404
a147 := float64(0) // will calculate later; temporarily 0
// We will set A147 later, for now zero
if a2 == 1 && a3 == 1 {
off[42] = a147 // A43
off[43] = a147 // A44
} else {
off[42] = 404
off[43] = 404
}
// Rule 23: If (A2,A3)=(1,1) or (2,2) A45=404 else A44=A147
if (a2 == 1 && a3 == 1) || (a2 == 2 && a3 == 2) {
off[44] = 404
} else {
// Note: Rule says offspring's A44 = A147 again but that attribute is 44, which is A45 (0 based 44)
// Presume "offspring's A44" means A45
off[44] = a147 // A45
}
// Rule 24: If (A2,A3) == (1,1) A46=404 else A46=A147
if a2 == 1 && a3 == 1 {
off[45] = 404
} else {
off[45] = a147
}
// Rule 25: A47-A146 = sum parent1 + parent2 correspondingly
for i := 46; i <= 145; i++ {
off[i] = p1[i] + p2[i]
}
// Rule 26: A147 = index of max in A47-A146 minus 46 (offset to 1-based index for that segment)
maxVal := off[46]
maxIdx := 46
for i := 47; i <= 145; i++ {
if off[i] > maxVal {
maxVal = off[i]
maxIdx = i
}
}
off[146] = float64(maxIdx - 46)
// Now that A147 is calculated, set fields from rule 21-24 that use it:
if a2 == 1 && a3 == 1 {
off[42] = off[146]
off[43] = off[146]
off[45] = 404
} else {
off[42] = 404
off[43] = 404
off[44] = off[146]
off[45] = off[146]
}
if (a2 == 1 && a3 == 1) || (a2 == 2 && a3 == 2) {
off[44] = 404
}
// Rule 27: A148=parent1's A1, A149=parent2's A1
off[147] = p1[0]
off[148] = p2[0]
return off
}
// copyBlock copies from fromIdx to toIdx inclusive from src to dst
func copyBlock(dst *Line, src Line, fromIdx int, toIdx int) {
for i := fromIdx; i <= toIdx; i++ {
dst[i] = src[i]
}
}
// Copies A6-A8 from the parent with random offset -10 to 10; clamps as per rules
func copyAttributesWithOffset(dst *Line, parent Line, fromIdx, toIdx int) {
for i := fromIdx; i <= toIdx; i++ {
base := int(parent[i])
offset := rand.Intn(21) - 10 // [-10..10]
val := clampInt(base+offset, 0, 255)
dst[i] = float64(val)
}
}
func randFloatRange(min, max float64) float64 {
return min + rand.Float64()*(max-min)
}
Explanation:
Loaded all lines from input.txt, assuming the format is exactly as [ca/:A1,A2,...,A149].
Created data structure Line as an array of 149 float64 attributes.
Found parents: one with (A2,A3) = (1,1), one with (A2,A3) != (1,1) randomly.
Created offspring following all rules you specified.
Saved result in output.txt.
Used zero-based indexing; A1 = [0], A2=[1], ..., A149=[148].
Used helper functions to avoid redundancy.
Applied all numeric constraints (clamping A6-A8 to 0-255, etc.).
Correctly handled conditional assignments like A13, A17, etc.
Mutated 1-3 attributes in A34-A39 randomly.
Summed attributes for ranges A47-A146 then computed A147 as index of max.
Set A148 and A149 as parents' A1 values.
You can change "input.txt" and "output.txt" filenames in the main if needed.
If you want the function as a reusable function instead of a whole program let me know!
package main
import (
"fmt"
"math"
"math/rand"
"time"
)
// Line holds 149 attributes named A1...A149
type Line struct {
A [149]float64
}
// Helper to get A-field 1-based (1 to 149)
func (l *Line) Afield(i int) float64 {
// i expected 1-based, convert to zero-based
return l.A[i-1]
}
func (l *Line) SetAfield(i int, v float64) {
l.A[i-1] = v
}
// CreateOffspring picks parents from lines then creates offspring
// parents: slice of existing lines
// Returns offspring or error if no eligible parents
func CreateOffspring(parents []Line) (Line, error) {
var parents1, parents2 []Line
maxID := 0
for _, l := range parents {
id := int(l.A[0])
if id > maxID {
maxID = id
}
a2, a3 := int(l.A[1]), int(l.A[2])
if a2 == 1 && a3 == 1 {
parents1 = append(parents1, l)
} else {
parents2 = append(parents2, l)
}
}
if len(parents1) == 0 || len(parents2) == 0 {
return Line{}, fmt.Errorf("not enough parents with (A2,A3)=(1,1) and others")
}
// Pick random parents
parent1 := parents1[rand.Intn(len(parents1))]
parent2 := parents2[rand.Intn(len(parents2))]
// Prepare offspring
var off Line
off.SetAfield(1, float64(maxID+1)) // A1 = MaxID+1
// Helper closures ---------------------------------------------------
randChoice := func(vals ...float64) float64 {
return vals[rand.Intn(len(vals))]
}
randChoiceFromSlice := func(vals []float64) float64 {
return vals[rand.Intn(len(vals))]
}
cloneBlock := func(dst *Line, src Line, from, to int) {
for i := from; i <= to; i++ {
dst.SetAfield(i, src.Afield(i))
}
}
cloneBlockWithOffset := func(dst *Line, src Line, from, to int) {
for i := from; i <= to; i++ {
base := int(src.Afield(i))
offset := rand.Intn(21) - 10 // -10..10
val := clamp(base+offset, 0, 255)
dst.SetAfield(i, float64(val))
}
}
pairIn11or22 := func(a2, a3 int) bool {
return (a2 == 1 && a3 == 1) || (a2 == 2 && a3 == 2)
}
getA42Val := func(a2, a3, a4 int) int {
switch {
case a2 == 1 && a3 == 1 && a4 == 1:
return 1
case a2 == 1 && a3 == 1 && a4 == 2:
return 2
case a2 == 1 && a3 == 1 && a4 == 3:
return 3
case a2 == 2 && a3 == 2 && a4 == 1:
return 4
case a2 == 2 && a3 == 2 && a4 == 2:
return 5
case a2 == 2 && a3 == 2 && a4 == 3:
return 6
case (a2 == 1 && a3 == 2 && a4 == 1) || (a2 == 2 && a3 == 1 && a4 == 1):
return 7
case (a2 == 1 && a3 == 2 && a4 == 2) || (a2 == 2 && a3 == 1 && a4 == 2):
return 8
case (a2 == 1 && a3 == 2 && a4 == 3) || (a2 == 2 && a3 == 1 && a4 == 3):
return 9
default:
return -1
}
}
randFloatRange := func(min, max float64) float64 {
return min + rand.Float64()*(max-min)
}
clamp := func(val, min, max int) int {
if val < min {
return min
}
if val > max {
return max
}
return val
}
// ------------------------------------------------------------------
p1A2, p1A3 := parent1.Afield(2), parent1.Afield(3)
p2A2, p2A3 := parent2.Afield(2), parent2.Afield(3)
// Rule 2
offspringA2 := randChoice(p1A2, p1A3, p2A2, p2A3)
off.SetAfield(2, offspringA2)
if offspringA2 == p1A2 || offspringA2 == p1A3 {
off.SetAfield(3, randChoice(p2A2, p2A3))
} else {
off.SetAfield(3, randChoice(p1A2, p1A3))
}
a2, a3 := int(off.Afield(2)), int(off.Afield(3)) // soon often used
// Rule 3
p1A4, p1A5 := parent1.Afield(4), parent1.Afield(5)
p2A4, p2A5 := parent2.Afield(4), parent2.Afield(5)
offspringA4 := randChoice(p1A4, p1A5, p2A4, p2A5)
off.SetAfield(4, offspringA4)
if offspringA4 == p1A4 || offspringA4 == p1A5 {
off.SetAfield(5, randChoice(p2A4, p2A5))
} else {
off.SetAfield(5, randChoice(p1A4, p1A5))
}
a4 := int(off.Afield(4))
// Rule 4: (A6-A9)
if rand.Intn(2) == 0 {
cloneBlockWithOffset(&off, parent1, 6, 8)
} else {
cloneBlockWithOffset(&off, parent2, 6, 8)
}
off.SetAfield(9, 1.0)
// Rule 5: (A10,A11,A12)
if rand.Intn(2) == 0 {
cloneBlock(&off, parent1, 10, 12)
} else {
cloneBlock(&off, parent2, 10, 12)
}
// Rule 6: A13
if pairIn11or22(a2, a3) {
off.SetAfield(13, randFloatRange(0.25, 0.5))
} else {
off.SetAfield(13, 1)
}
// Rule 7: (A14,A15,A16)
if rand.Intn(2) == 0 {
cloneBlock(&off, parent1, 14, 16)
} else {
cloneBlock(&off, parent2, 14, 16)
}
// Rule 8: A17
if pairIn11or22(a2, a3) {
off.SetAfield(17, randFloatRange(0.25, 0.5))
} else {
off.SetAfield(17, 1)
}
// Rule 9: (A18,A19,A20)
if rand.Intn(2) == 0 {
cloneBlock(&off, parent1, 18, 20)
} else {
cloneBlock(&off, parent2, 18, 20)
}
// Rule 10: A21
if a2 == 1 && a3 == 1 {
off.SetAfield(21, randFloatRange(0.25, 0.5))
} else {
off.SetAfield(21, 0)
}
// Rule 11: (A22,A23,A24)
if rand.Intn(2) == 0 {
cloneBlock(&off, parent1, 22, 24)
} else {
cloneBlock(&off, parent2, 22, 24)
}
// Rule 12: A25
if pairIn11or22(a2, a3) {
off.SetAfield(25, 0)
} else {
off.SetAfield(25, 1)
}
// Rule 13: (A26,A27,A28)
if rand.Intn(2) == 0 {
cloneBlock(&off, parent1, 26, 28)
} else {
cloneBlock(&off, parent2, 26, 28)
}
// Rule 14: A29
if pairIn11or22(a2, a3) {
off.SetAfield(29, 0)
} else {
off.SetAfield(29, 1)
}
// Rule 15: (A30,A31,A32)
if rand.Intn(2) == 0 {
cloneBlock(&off, parent1, 30, 32)
} else {
cloneBlock(&off, parent2, 30, 32)
}
// Rule 16: A33
if a2 == 1 && a3 == 1 {
off.SetAfield(33, 0)
} else {
off.SetAfield(33, 1)
}
// Rule 17: A34-A39 random choice from parents then 1-3 mutations [1..10]
for i := 34; i <= 39; i++ {
if rand.Intn(2) == 0 {
off.SetAfield(i, parent1.Afield(i))
} else {
off.SetAfield(i, parent2.Afield(i))
}
}
// mutate 1-3 distinct indexes in A34-A39
nMutations := rand.Intn(3) + 1
perm := rand.Perm(6)
for i := 0; i < nMutations; i++ {
idx := 34 + perm[i]
off.SetAfield(idx, float64(rand.Intn(10)+1))
}
// Rule 18-19: A40, A41 random int 1..10
off.SetAfield(40, float64(rand.Intn(10)+1))
off.SetAfield(41, float64(rand.Intn(10)+1))
// Rule 20: A42 depends on (A2,A3,A4)
a42val := getA42Val(a2, a3, a4)
if a42val != -1 {
off.SetAfield(42, float64(a42val))
} else {
off.SetAfield(42, 0)
}
// Rules 25-26: A47-A146 sum of parents; find max index for A147
for i := 47; i <= 146; i++ {
off.SetAfield(i, parent1.Afield(i)+parent2.Afield(i))
}
// find max index in A47..A146
maxval := off.Afield(47)
maxidx := 47
for i := 48; i <= 146; i++ {
v := off.Afield(i)
if v > maxval {
maxval = v
maxidx = i
}
}
off.SetAfield(147, float64(maxidx-46)) // A147
a147 := off.Afield(147)
// Rules 21,22,23,24 updated after A147 calculated
// 21: If (A2,A3)=(1,1) A43=A147 else 404
if a2 == 1 && a3 == 1 {
off.SetAfield(43, a147)
} else {
off.SetAfield(43, 404)
}
// 22: same as 21 for A44
if a2 == 1 && a3 == 1 {
off.SetAfield(44, a147)
} else {
off.SetAfield(44, 404)
}
// 23: If (A2,A3)=(1,1) or (2,2) A45=404 else A44=A147 (off.A44=off.A147)
if pairIn11or22(a2, a3) {
off.SetAfield(45, 404)
} else {
off.SetAfield(45, a147)
}
// 24: If (A2,A3)=(1,1) A46=404 else A46=A147
if a2 == 1 && a3 == 1 {
off.SetAfield(46, 404)
} else {
off.SetAfield(46, a147)
}
// Rule 27: A148=parent1.A1, A149=parent2.A1
off.SetAfield(148, parent1.Afield(1))
off.SetAfield(149, parent2.Afield(1))
return off, nil
}
func main() {
rand.Seed(time.Now().UnixNano())
// Example usage:
// You must supply your population slice []Line from your source data here
// For demo create dummy with arbitrary data for minimal parents
var parents []Line
// Create two parents manually for demo
p1 := Line{}
p1.SetAfield(1, 1)
p1.SetAfield(2, 1)
p1.SetAfield(3, 1)
for i := 4; i <= 149; i++ {
p1.SetAfield(i, float64(i))
}
p2 := Line{}
p2.SetAfield(1, 2)
p2.SetAfield(2, 3) // !=(1,1)
p2.SetAfield(3, 4)
for i := 4; i <= 149; i++ {
p2.SetAfield(i, float64(i * 2))
}
parents = append(parents, p1, p2)
offspring, err := CreateOffspring(parents)
if err != nil {
panic(err)
}
// Print out offspring A1..A10 as example
for i := 1; i <= 10; i++ {
fmt.Printf("A%d = %v\n", i, offspring.Afield(i))
}
}
Summary:
CreateOffspring function takes a slice of Line structs.
Picks parents meeting conditions internally.
Generates offspring per your complex rules with minimal repetition.
Line struct uses array and helper funcs for clarity.
Usage shown with dummy parents (replace with your data).
All numeric attributes stored as float64 for flexibility.
If you want me to provide helper functions to load/save from file for this struct or any other tweaks, just ask!
// Pick random parents
parent1 := parents1[rand.Intn(len(parents1))]
parent2 := parents2[rand.Intn(len(parents2))]
// Prepare offspring
var off Line
off.SetAfield(1, float64(maxID+1)) // A1 = MaxID+1
// Helper closures ---------------------------------------------------
randChoice := func(vals ...float64) float64 {
return vals[rand.Intn(len(vals))]
}
randChoiceFromSlice := func(vals []float64) float64 {
return vals[rand.Intn(len(vals))]
}
cloneBlock := func(dst *Line, src Line, from, to int) {
for i := from; i <= to; i++ {
dst.SetAfield(i, src.Afield(i))
}
}
cloneBlockWithOffset := func(dst *Line, src Line, from, to int) {
for i := from; i <= to; i++ {
base := int(src.Afield(i))
offset := rand.Intn(21) - 10 // -10..10
val := clamp(base+offset, 0, 255)
dst.SetAfield(i, float64(val))
}
}
pairIn11or22 := func(a2, a3 int) bool {
return (a2 == 1 && a3 == 1) || (a2 == 2 && a3 == 2)
}
getA42Val := func(a2, a3, a4 int) int {
switch {
case a2 == 1 && a3 == 1 && a4 == 1:
return 1
case a2 == 1 && a3 == 1 && a4 == 2:
return 2
case a2 == 1 && a3 == 1 && a4 == 3:
return 3
case a2 == 2 && a3 == 2 && a4 == 1:
return 4
case a2 == 2 && a3 == 2 && a4 == 2:
return 5
case a2 == 2 && a3 == 2 && a4 == 3:
return 6
case (a2 == 1 && a3 == 2 && a4 == 1) || (a2 == 2 && a3 == 1 && a4 == 1):
return 7
case (a2 == 1 && a3 == 2 && a4 == 2) || (a2 == 2 && a3 == 1 && a4 == 2):
return 8
case (a2 == 1 && a3 == 2 && a4 == 3) || (a2 == 2 && a3 == 1 && a4 == 3):
return 9
default:
return -1
}
}
randFloatRange := func(min, max float64) float64 {
return min + rand.Float64()*(max-min)
}
clamp := func(val, min, max int) int {
if val < min {
return min
}
if val > max {
return max
}
return val
}
// ------------------------------------------------------------------
p1A2, p1A3 := parent1.Afield(2), parent1.Afield(3)
p2A2, p2A3 := parent2.Afield(2), parent2.Afield(3)
// Rule 2
offspringA2 := randChoice(p1A2, p1A3, p2A2, p2A3)
off.SetAfield(2, offspringA2)
if offspringA2 == p1A2 || offspringA2 == p1A3 {
off.SetAfield(3, randChoice(p2A2, p2A3))
} else {
off.SetAfield(3, randChoice(p1A2, p1A3))
}
a2, a3 := int(off.Afield(2)), int(off.Afield(3)) // soon often used
// Rule 3
p1A4, p1A5 := parent1.Afield(4), parent1.Afield(5)
p2A4, p2A5 := parent2.Afield(4), parent2.Afield(5)
offspringA4 := randChoice(p1A4, p1A5, p2A4, p2A5)
off.SetAfield(4, offspringA4)
if offspringA4 == p1A4 || offspringA4 == p1A5 {
off.SetAfield(5, randChoice(p2A4, p2A5))
} else {
off.SetAfield(5, randChoice(p1A4, p1A5))
}
a4 := int(off.Afield(4))
// Rule 4: (A6-A9)
if rand.Intn(2) == 0 {
cloneBlockWithOffset(&off, parent1, 6, 8)
} else {
cloneBlockWithOffset(&off, parent2, 6, 8)
}
off.SetAfield(9, 1.0)
// Rule 5: (A10,A11,A12)
if rand.Intn(2) == 0 {
cloneBlock(&off, parent1, 10, 12)
} else {
cloneBlock(&off, parent2, 10, 12)
}
// Rule 6: A13
if pairIn11or22(a2, a3) {
off.SetAfield(13, randFloatRange(0.25, 0.5))
} else {
off.SetAfield(13, 1)
}
// Rule 7: (A14,A15,A16)
if rand.Intn(2) == 0 {
cloneBlock(&off, parent1, 14, 16)
} else {
cloneBlock(&off, parent2, 14, 16)
}
// Rule 8: A17
if pairIn11or22(a2, a3) {
off.SetAfield(17, randFloatRange(0.25, 0.5))
} else {
off.SetAfield(17, 1)
}
// Rule 9: (A18,A19,A20)
if rand.Intn(2) == 0 {
cloneBlock(&off, parent1, 18, 20)
} else {
cloneBlock(&off, parent2, 18, 20)
}
// Rule 10: A21
if a2 == 1 && a3 == 1 {
off.SetAfield(21, randFloatRange(0.25, 0.5))
} else {
off.SetAfield(21, 0)
}
// Rule 11: (A22,A23,A24)
if rand.Intn(2) == 0 {
cloneBlock(&off, parent1, 22, 24)
} else {
cloneBlock(&off, parent2, 22, 24)
}
// Rule 12: A25
if pairIn11or22(a2, a3) {
off.SetAfield(25, 0)
} else {
off.SetAfield(25, 1)
}
// Rule 13: (A26,A27,A28)
if rand.Intn(2) == 0 {
cloneBlock(&off, parent1, 26, 28)
} else {
cloneBlock(&off, parent2, 26, 28)
}
// Rule 14: A29
if pairIn11or22(a2, a3) {
off.SetAfield(29, 0)
} else {
off.SetAfield(29, 1)
}
// Rule 15: (A30,A31,A32)
if rand.Intn(2) == 0 {
cloneBlock(&off, parent1, 30, 32)
} else {
cloneBlock(&off, parent2, 30, 32)
}
// Rule 16: A33
if a2 == 1 && a3 == 1 {
off.SetAfield(33, 0)
} else {
off.SetAfield(33, 1)
}
// Rule 17: A34-A39 random choice from parents then 1-3 mutations [1..10]
for i := 34; i <= 39; i++ {
if rand.Intn(2) == 0 {
off.SetAfield(i, parent1.Afield(i))
} else {
off.SetAfield(i, parent2.Afield(i))
}
}
// mutate 1-3 distinct indexes in A34-A39
nMutations := rand.Intn(3) + 1
perm := rand.Perm(6)
for i := 0; i < nMutations; i++ {
idx := 34 + perm[i]
off.SetAfield(idx, float64(rand.Intn(10)+1))
}
// Rule 18-19: A40, A41 random int 1..10
off.SetAfield(40, float64(rand.Intn(10)+1))
off.SetAfield(41, float64(rand.Intn(10)+1))
// Rule 20: A42 depends on (A2,A3,A4)
a42val := getA42Val(a2, a3, a4)
if a42val != -1 {
off.SetAfield(42, float64(a42val))
} else {
off.SetAfield(42, 0)
}
// Rules 25-26: A47-A146 sum of parents; find max index for A147
for i := 47; i <= 146; i++ {
off.SetAfield(i, parent1.Afield(i)+parent2.Afield(i))
}
// find max index in A47..A146
maxval := off.Afield(47)
maxidx := 47
for i := 48; i <= 146; i++ {
v := off.Afield(i)
if v > maxval {
maxval = v
maxidx = i
}
}
off.SetAfield(147, float64(maxidx-46)) // A147
a147 := off.Afield(147)
// Rules 21,22,23,24 updated after A147 calculated
// 21: If (A2,A3)=(1,1) A43=A147 else 404
if a2 == 1 && a3 == 1 {
off.SetAfield(43, a147)
} else {
off.SetAfield(43, 404)
}
// 22: same as 21 for A44
if a2 == 1 && a3 == 1 {
off.SetAfield(44, a147)
} else {
off.SetAfield(44, 404)
}
// 23: If (A2,A3)=(1,1) or (2,2) A45=404 else A44=A147 (off.A44=off.A147)
if pairIn11or22(a2, a3) {
off.SetAfield(45, 404)
} else {
off.SetAfield(45, a147)
}
// 24: If (A2,A3)=(1,1) A46=404 else A46=A147
if a2 == 1 && a3 == 1 {
off.SetAfield(46, 404)
} else {
off.SetAfield(46, a147)
}
// Rule 27: A148=parent1.A1, A149=parent2.A1
off.SetAfield(148, parent1.Afield(1))
off.SetAfield(149, parent2.Afield(1))
return off, nil
}
func main() {
rand.Seed(time.Now().UnixNano())
code
// Example usage:
// You must supply your population slice []Line from your source data here
// For demo create dummy with arbitrary data for minimal parents
var parents []Line
// Create two parents manually for demo
p1 := Line{}
p1.SetAfield(1, 1)
p1.SetAfield(2, 1)
p1.SetAfield(3, 1)
for i := 4; i <= 149; i++ {
p1.SetAfield(i, float64(i))
}
p2 := Line{}
p2.SetAfield(1, 2)
p2.SetAfield(2, 3) // !=(1,1)
p2.SetAfield(3, 4)
for i := 4; i <= 149; i++ {
p2.SetAfield(i, float64(i * 2))
}
parents = append(parents, p1, p2)
offspring, err := CreateOffspring(parents)
if err != nil {
panic(err)
}
// Print out offspring A1..A10 as example
for i := 1; i <= 10; i++ {
fmt.Printf("A%d = %v\n", i, offspring.Afield(i))
}
Removed duplicate helpers and replaced with parametric functions like setIf.
Combined multiple if-else into a helper pair11or22 and used concise switches.
Used loops with copyAttrs and other helpers consistently.
Cleaned variable naming and reduced clutter.
Get and Set used instead of Afield/SetAfield (shorter).
Removed unnecessary intermediate variables.
Kept everything clear and easy to follow.
You can further modularize by splitting into multiple files or adding comments if needed, but this is about as clean and concise for your logic as can be without sacrificing clarity.
If you want, I can provide a version with file IO or serialization to/from line strings as well!
// Demo parents
p1 := Line{}
p1.Set(1, 1)
p1.Set(2, 1)
p1.Set(3, 1)
for i := 4; i <= 149; i++ {
p1.Set(i, float64(i))
}
p2 := Line{}
p2.Set(1, 2)
p2.Set(2, 3)
p2.Set(3, 4)
for i := 4; i <= 149; i++ {
p2.Set(i, float64(i * 2))
}
offspring, err := CreateOffspring([]Line{p1, p2})
if err != nil {
panic(err)
}
for i := 1; i <= 10; i++ {
fmt.Printf("A%d = %v\n", i, offspring.Get(i))
}
}
Can you make it more shorter and memories friendlier? I have like millons of lines in my txt file, read them all is really not memories friendly.
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
type Line struct{ A [149]float64 }
func parseLine(line string) (Line, error) {
line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "[ca/:") || !strings.HasSuffix(line, "]") {
return Line{}, fmt.Errorf("bad format")
}
body := line[5 : len(line)-1]
parts := strings.Split(body, ",")
if len(parts) != 149 {
return Line{}, fmt.Errorf("expected 149 attrs got %d", len(parts))
}
var l Line
for i, p := range parts {
v, err := strconv.ParseFloat(p, 64)
if err != nil {
return Line{}, err
}
l.A[i] = v
}
return l, nil
}
func (l *Line) Get(i int) float64 { return l.A[i-1] }
func (l *Line) Set(i int, v float64) { l.A[i-1] = v }
// Read file line by line, record line offsets (byte positions) of parents1 and parents2 candidates
func indexParents(filename string) (int, []int64, []int64, error) {
file, err := os.Open(filename)
if err != nil {
return 0, nil, nil, err
}
defer file.Close()
var maxID int
var parents1Offsets, parents2Offsets []int64
reader := bufio.NewReader(file)
var offset int64 = 0
for {
line, err := reader.ReadString('\n')
if err != nil {
break
}
lineLen := int64(len(line))
l, err := parseLine(line)
if err != nil {
return 0, nil, nil, err
}
id := int(l.Get(1))
if id > maxID {
maxID = id
}
a2, a3 := int(l.Get(2)), int(l.Get(3))
if a2 == 1 && a3 == 1 {
parents1Offsets = append(parents1Offsets, offset)
} else {
parents2Offsets = append(parents2Offsets, offset)
}
offset += lineLen
}
return maxID, parents1Offsets, parents2Offsets, nil
}
// seek and parse one line by offset
func readLineAt(file *os.File, offset int64) (Line, error) {
_, err := file.Seek(offset, 0)
if err != nil {
return Line{}, err
}
reader := bufio.NewReader(file)
line, err := reader.ReadString('\n')
if err != nil {
return Line{}, err
}
return parseLine(line)
}
func main() {
rand.Seed(time.Now().UnixNano())
filename := "input.txt"
// 1) Index the file: get maxID, and offsets of parents candidates
maxID, parents1, parents2, err := indexParents(filename)
if err != nil {
panic(err)
}
if len(parents1) == 0 || len(parents2) == 0 {
panic("not enough parents")
}
// 2) Pick random parents offsets
p1Offset := parents1[rand.Intn(len(parents1))]
p2Offset := parents2[rand.Intn(len(parents2))]
f, err := os.Open(filename)
if err != nil {
panic(err)
}
defer f.Close()
// 3) Load the two parents only, no other lines in memory
p1, err := readLineAt(f, p1Offset)
if err != nil {
panic(err)
}
p2, err := readLineAt(f, p2Offset)
if err != nil {
panic(err)
}
// 4) Create a 2-item population and produce offspring
offspring, err := CreateOffspring([]Line{p1, p2}) // Use your CreateOffspring with that
if err != nil {
panic(err)
}
// 5) Append offspring to file
outFile, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
defer outFile.Close()
fmt.Fprintf(outFile, "%s\n", serializeLine(offspring))
}
func serializeLine(l Line) string {
var parts []string
for i := 0; i < 149; i++ {
parts = append(parts, strconv.FormatFloat(l.A[i], 'f', -1, 64))
}
return "[ca/:" + strings.Join(parts, ",") + "]"
}
Key points
Only indexes(offsets in bytes) to lines of parents are stored in memory (2 slices).
Only two lines loaded into memory for parents.
You never load the whole file.
Offspring is created with your CreateOffspring.
Offspring is appended to the same file.
You can adjust this design:
If you want multiple offspring, just repeat the 2-5 steps as needed.
You can store candidate offsets in a separate index file if re-using multiple times.
Using file offsets is more memory-friendly than line numbers because you can seek exact line quickly.
Your CreateOffspring needs just those two parents as input.
If you want me to help combine your existing CreateOffspring with this streaming indexing approach or implement batch offspring generation let me know!
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
type Line struct{ A [149]float64 }
func (l *Line) Get(i int) float64 { return l.A[i-1] }
func (l *Line) Set(i int, v float64) { l.A[i-1] = v }
// parseLine parses string like "[ca/:A1,A2,...,A149]"
func parseLine(line string) (Line, error) {
line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "[ca/:") || !strings.HasSuffix(line, "]") {
return Line{}, fmt.Errorf("bad format")
}
body := line[5 : len(line)-1]
parts := strings.Split(body, ",")
if len(parts) != 149 {
return Line{}, fmt.Errorf("expected 149 attributes but got %d", len(parts))
}
var l Line
for i, p := range parts {
v, err := strconv.ParseFloat(p, 64)
if err != nil {
return Line{}, err
}
l.A[i] = v
}
return l, nil
}
// serializeLine converts Line to string format "[ca/:A1,A2,...,A149]"
func serializeLine(l Line) string {
var parts []string
for i := 0; i < 149; i++ {
parts = append(parts, strconv.FormatFloat(l.A[i], 'f', -1, 64))
}
return "[ca/:" + strings.Join(parts, ",") + "]"
}
func indexParents(filename string) (maxID int, parents1Offsets, parents2Offsets []int64, err error) {
file, err := os.Open(filename)
if err != nil {
return
}
defer file.Close()
reader := bufio.NewReader(file)
var offset int64
for {
line, errRead := reader.ReadString('\n')
if errRead != nil && len(line) == 0 {
break
}
l, errParse := parseLine(line)
if errParse != nil {
err = errParse
return
}
id := int(l.Get(1))
if id > maxID {
maxID = id
}
a2, a3 := int(l.Get(2)), int(l.Get(3))
if a2 == 1 && a3 == 1 {
parents1Offsets = append(parents1Offsets, offset)
} else {
parents2Offsets = append(parents2Offsets, offset)
}
offset += int64(len(line))
if errRead != nil {
break
}
}
return
}
func readLineAt(file *os.File, offset int64) (Line, error) {
_, err := file.Seek(offset, 0)
if err != nil {
return Line{}, err
}
reader := bufio.NewReader(file)
line, err := reader.ReadString('\n')
if err != nil {
return Line{}, err
}
return parseLine(line)
}
// CreateOffspring generates offspring from parents slice (exactly two)
func CreateOffspring(pop []Line) (Line, error) {
if len(pop) != 2 {
return Line{}, fmt.Errorf("expected exactly two parents")
}
p1, p2 := pop[0], pop[1]
maxID := int(p1.Get(1))
if id2 := int(p2.Get(1)); id2 > maxID {
maxID = id2
}
// We'll respect maxID given to more recent line in indexing, but to be safe:
// offspring ID must be maxID+1
newID := maxID + 1
var off Line
off.Set(1, float64(newID))
randChoice := func(vals ...float64) float64 { return vals[rand.Intn(len(vals))] }
copyAttrs := func(dst *Line, src Line, from, to int) {
for i := from; i <= to; i++ {
dst.Set(i, src.Get(i))
}
}
copyAttrsWithOffset := func(dst *Line, src Line, from, to int) {
for i := from; i <= to; i++ {
base := int(src.Get(i))
offset := rand.Intn(21) - 10
if base+offset < 0 {
offset = -base
} else if base+offset > 255 {
offset = 255 - base
}
dst.Set(i, float64(base+offset))
}
}
pair11or22 := func(a, b int) bool { return (a == 1 && b == 1) || (a == 2 && b == 2) }
getA42 := func(a2, a3, a4 int) int {
switch {
case a2 == 1 && a3 == 1 && (a4 >= 1 && a4 <= 3):
return a4
case a2 == 2 && a3 == 2 && (a4 >= 1 && a4 <= 3):
return a4 + 3
case (a2 == 1 && a3 == 2) || (a2 == 2 && a3 == 1):
if a4 >= 1 && a4 <= 3 {
return 6 + a4
}
}
return 0
}
randFloat := func(min, max float64) float64 { return min + rand.Float64()*(max-min) }
p1a2, p1a3 := p1.Get(2), p1.Get(3)
p2a2, p2a3 := p2.Get(2), p2.Get(3)
// A2,A3
a2 := randChoice(p1a2, p1a3, p2a2, p2a3)
off.Set(2, a2)
if a2 == p1a2 || a2 == p1a3 {
off.Set(3, randChoice(p2a2, p2a3))
} else {
off.Set(3, randChoice(p1a2, p1a3))
}
a3 := int(off.Get(3))
// A4,A5
p1a4, p1a5 := p1.Get(4), p1.Get(5)
p2a4, p2a5 := p2.Get(4), p2.Get(5)
a4 := randChoice(p1a4, p1a5, p2a4, p2a5)
off.Set(4, a4)
if a4 == p1a4 || a4 == p1a5 {
off.Set(5, randChoice(p2a4, p2a5))
} else {
off.Set(5, randChoice(p1a4, p1a5))
}
a4i := int(a4)
// A6..A9
if rand.Intn(2) == 0 {
copyAttrsWithOffset(&off, p1, 6, 8)
} else {
copyAttrsWithOffset(&off, p2, 6, 8)
}
off.Set(9, 1)
// A10..A12
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 10, 12)
} else {
copyAttrs(&off, p2, 10, 12)
}
// A13
if pair11or22(int(a2), a3) {
off.Set(13, randFloat(0.25, 0.5))
} else {
off.Set(13, 1)
}
// A14..A16
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 14, 16)
} else {
copyAttrs(&off, p2, 14, 16)
}
// A17
if pair11or22(int(a2), a3) {
off.Set(17, randFloat(0.25, 0.5))
} else {
off.Set(17, 1)
}
// A18..A20
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 18, 20)
} else {
copyAttrs(&off, p2, 18, 20)
}
// A21
if int(a2) == 1 && a3 == 1 {
off.Set(21, randFloat(0.25, 0.5))
} else {
off.Set(21, 0)
}
// A22..A24
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 22, 24)
} else {
copyAttrs(&off, p2, 22, 24)
}
// A25
if pair11or22(int(a2), a3) {
off.Set(25, 0)
} else {
off.Set(25, 1)
}
// A26..A28
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 26, 28)
} else {
copyAttrs(&off, p2, 26, 28)
}
// A29
if pair11or22(int(a2), a3) {
off.Set(29, 0)
} else {
off.Set(29, 1)
}
// A30..A32
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 30, 32)
} else {
copyAttrs(&off, p2, 30, 32)
}
// A33
if int(a2) == 1 && a3 == 1 {
off.Set(33, 0)
} else {
off.Set(33, 1)
}
// A34..A39
for i := 34; i <= 39; i++ {
if rand.Intn(2) == 0 {
off.Set(i, p1.Get(i))
} else {
off.Set(i, p2.Get(i))
}
}
// Mutate 1-3 distinct indices within A34-A39 to random [1..10]
mutations := rand.Intn(3) + 1
perm := rand.Perm(6)
for i := 0; i < mutations; i++ {
off.Set(34+perm[i], float64(rand.Intn(10)+1))
}
// A40, A41 random [1..10]
off.Set(40, float64(rand.Intn(10)+1))
off.Set(41, float64(rand.Intn(10)+1))
// A42
off.Set(42, float64(getA42(int(a2), a3, a4i)))
// A47..A146 sum parents
for i := 47; i <= 146; i++ {
off.Set(i, p1.Get(i)+p2.Get(i))
}
maxVal, maxIdx := off.Get(47), 47
for i := 48; i <= 146; i++ {
if v := off.Get(i); v > maxVal {
maxVal, maxIdx = v, i
}
}
off.Set(147, float64(maxIdx-46))
a147 := off.Get(147)
setIf := func(cond bool, idx int, trueV, falseV float64) {
if cond {
off.Set(idx, trueV)
} else {
off.Set(idx, falseV)
}
}
setIf(int(a2) == 1 && a3 == 1, 43, a147, 404)
setIf(int(a2) == 1 && a3 == 1, 44, a147, 404)
setIf(pair11or22(int(a2), a3), 45, 404, a147)
setIf(int(a2) == 1 && a3 == 1, 46, 404, a147)
// Rule 27
off.Set(148, p1.Get(1))
off.Set(149, p2.Get(1))
return off, nil
}
func main() {
rand.Seed(time.Now().UnixNano())
filename := "input.txt"
maxID, parents1, parents2, err := indexParents(filename)
if err != nil {
panic(err)
}
if len(parents1) == 0 || len(parents2) == 0 {
panic("Not enough parents for breeding")
}
f, err := os.Open(filename)
if err != nil {
panic(err)
}
defer f.Close()
p1, err := readLineAt(f, parents1[rand.Intn(len(parents1))])
if err != nil {
panic(err)
}
p2, err := readLineAt(f, parents2[rand.Intn(len(parents2))])
if err != nil {
panic(err)
}
offspring, err := CreateOffspring([]Line{p1, p2})
if err != nil {
panic(err)
}
of, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
defer of.Close()
_, err = fmt.Fprintln(of, serializeLine(offspring))
if err != nil {
panic(err)
}
fmt.Println("Offspring created and appended successfully. Offspring ID:", int(offspring.Get(1)))
}
Notes:
indexParents() scans the file once and records byte offsets for two parent groups.
Reads only two parents randomly by seeking those offsets.
Uses your comprehensive CreateOffspring logic unchanged.
Appends offspring string line directly to the file.
Minimal memory usage — at most three loaded lines simultaneously.
You can reuse or modify this to generate multiple offspring just by repeating the parent picks.
If you want, I can help you make a batch offspring generator or add command line arguments to specify input/output filenames.
code
maxID := int(p1.Get(1))
if id2 := int(p2.Get(1)); id2 > maxID {
maxID = id2
}
// We'll respect maxID given to more recent line in indexing, but to be safe:
// offspring ID must be maxID+1
newID := maxID + 1
var off Line
off.Set(1, float64(newID))
randChoice := func(vals ...float64) float64 { return vals[rand.Intn(len(vals))] }
copyAttrs := func(dst *Line, src Line, from, to int) {
for i := from; i <= to; i++ {
dst.Set(i, src.Get(i))
}
}
copyAttrsWithOffset := func(dst *Line, src Line, from, to int) {
for i := from; i <= to; i++ {
base := int(src.Get(i))
offset := rand.Intn(21) - 10
if base+offset < 0 {
offset = -base
} else if base+offset > 255 {
offset = 255 - base
}
dst.Set(i, float64(base+offset))
}
}
pair11or22 := func(a, b int) bool { return (a == 1 && b == 1) || (a == 2 && b == 2) }
getA42 := func(a2, a3, a4 int) int {
switch {
case a2 == 1 && a3 == 1 && (a4 >= 1 && a4 <= 3):
return a4
case a2 == 2 && a3 == 2 && (a4 >= 1 && a4 <= 3):
return a4 + 3
case (a2 == 1 && a3 == 2) || (a2 == 2 && a3 == 1):
if a4 >= 1 && a4 <= 3 {
return 6 + a4
}
}
return 0
}
randFloat := func(min, max float64) float64 { return min + rand.Float64()*(max-min) }
p1a2, p1a3 := p1.Get(2), p1.Get(3)
p2a2, p2a3 := p2.Get(2), p2.Get(3)
// A2,A3
a2 := randChoice(p1a2, p1a3, p2a2, p2a3)
off.Set(2, a2)
if a2 == p1a2 || a2 == p1a3 {
off.Set(3, randChoice(p2a2, p2a3))
} else {
off.Set(3, randChoice(p1a2, p1a3))
}
a3 := int(off.Get(3))
// A4,A5
p1a4, p1a5 := p1.Get(4), p1.Get(5)
p2a4, p2a5 := p2.Get(4), p2.Get(5)
a4 := randChoice(p1a4, p1a5, p2a4, p2a5)
off.Set(4, a4)
if a4 == p1a4 || a4 == p1a5 {
off.Set(5, randChoice(p2a4, p2a5))
} else {
off.Set(5, randChoice(p1a4, p1a5))
}
a4i := int(a4)
// A6..A9
if rand.Intn(2) == 0 {
copyAttrsWithOffset(&off, p1, 6, 8)
} else {
copyAttrsWithOffset(&off, p2, 6, 8)
}
off.Set(9, 1)
// A10..A12
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 10, 12)
} else {
copyAttrs(&off, p2, 10, 12)
}
// A13
if pair11or22(int(a2), a3) {
off.Set(13, randFloat(0.25, 0.5))
} else {
off.Set(13, 1)
}
// A14..A16
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 14, 16)
} else {
copyAttrs(&off, p2, 14, 16)
}
// A17
if pair11or22(int(a2), a3) {
off.Set(17, randFloat(0.25, 0.5))
} else {
off.Set(17, 1)
}
// A18..A20
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 18, 20)
} else {
copyAttrs(&off, p2, 18, 20)
}
// A21
if int(a2) == 1 && a3 == 1 {
off.Set(21, randFloat(0.25, 0.5))
} else {
off.Set(21, 0)
}
// A22..A24
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 22, 24)
} else {
copyAttrs(&off, p2, 22, 24)
}
// A25
if pair11or22(int(a2), a3) {
off.Set(25, 0)
} else {
off.Set(25, 1)
}
// A26..A28
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 26, 28)
} else {
copyAttrs(&off, p2, 26, 28)
}
// A29
if pair11or22(int(a2), a3) {
off.Set(29, 0)
} else {
off.Set(29, 1)
}
// A30..A32
if rand.Intn(2) == 0 {
copyAttrs(&off, p1, 30, 32)
} else {
copyAttrs(&off, p2, 30, 32)
}
// A33
if int(a2) == 1 && a3 == 1 {
off.Set(33, 0)
} else {
off.Set(33, 1)
}
// A34..A39
for i := 34; i <= 39; i++ {
if rand.Intn(2) == 0 {
off.Set(i, p1.Get(i))
} else {
off.Set(i, p2.Get(i))
}
}
// Mutate 1-3 distinct indices within A34-A39 to random [1..10]
mutations := rand.Intn(3) + 1
perm := rand.Perm(6)
for i := 0; i < mutations; i++ {
off.Set(34+perm[i], float64(rand.Intn(10)+1))
}
// A40, A41 random [1..10]
off.Set(40, float64(rand.Intn(10)+1))
off.Set(41, float64(rand.Intn(10)+1))
// A42
off.Set(42, float64(getA42(int(a2), a3, a4i)))
// A47..A146 sum parents
for i := 47; i <= 146; i++ {
off.Set(i, p1.Get(i)+p2.Get(i))
}
maxVal, maxIdx := off.Get(47), 47
for i := 48; i <= 146; i++ {
if v := off.Get(i); v > maxVal {
maxVal, maxIdx = v, i
}
}
off.Set(147, float64(maxIdx-46))
a147 := off.Get(147)
setIf := func(cond bool, idx int, trueV, falseV float64) {
if cond {
off.Set(idx, trueV)
} else {
off.Set(idx, falseV)
}
}
setIf(int(a2) == 1 && a3 == 1, 43, a147, 404)
setIf(int(a2) == 1 && a3 == 1, 44, a147, 404)
setIf(pair11or22(int(a2), a3), 45, 404, a147)
setIf(int(a2) == 1 && a3 == 1, 46, 404, a147)
// Rule 27
off.Set(148, p1.Get(1))
off.Set(149, p2.Get(1))
return off, nil