// Rule 6 A13 a2a311 := floatEquals(offspring[AField(2)], 1) &&…
- User
// Rule 6 A13 a2a311 := floatEquals(offspring[AField(2)], 1) && floatEquals(offspring[AField(3)], 1) a2a322 := floatEquals(offspring[AField(2)], 2) && floatEquals(offspring[AField(3)], 2) if a2a311 || a2a322 { // 0.25 to 0.5 offspring[AField(13)] = float64(rand.Intn(26)+25) / 100 } else { offspring[AField(13)] = 1 } But the output isn't following this: 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.
- Assistant
Your code logic looks almost correct for implementing the described rule, but the issue might be with how you're generating the range from 0.25 to 0.5. Let's break down the code:
a2a311 := floatEquals(offspring[AField(2)], 1) && floatEquals(offspring[AField(3)], 1) a2a322 := floatEquals(offspring[AField(2)], 2) && floatEquals(offspring[AField(3)], 2) if a2a311 || a2a322 { // 0.25 to 0.5 offspring[AField(13)] = float64(rand.Intn(26)+25) / 100 } else { offspring[AField(13)] = 1 }Key points:
rand.Intn(26)generates a random integer from 0 to 25.- Adding 25 makes it from 25 to 50.
- Dividing by 100 makes it 0.25 to 0.5.
- So that part is correct.
If your output deviates from this, several possible reasons:
Potential issues and fixes:
-
Verification of
floatEqualsfunction:How is
floatEqualsimplemented? Floating-point comparison is tricky, and iffloatEqualsis not implemented properly (i.e., not considering a tolerance), it might return false when it should be true.A typical float equals function with tolerance might be:
func floatEquals(a, b float64) bool { const epsilon = 0.0001 return math.Abs(a - b) < epsilon }Please verify that the
floatEqualsfunction is working correctly. If you are comparing exact integers but stored as floats (like 1.0 or 2.0), and offspring values are exactly those float values, you might just compare with == safely. -
Check
offspring[AField(n)]values:Ensure that values in
offspring[AField(2)]andoffspring[AField(3)]are exactly 1 or 2 for the expected cases. Any difference (such as 1.000001) can causefloatEqualsto be false. -
Random seed:
Make sure that you have seeded your random number generator using
rand.Seed()somewhere once in your program, or elserand.Intn()will give the same results every time you run the program. For example:rand.Seed(time.Now().UnixNano()) -
Alternative simpler code for clarity:
If you are sure offspring[AField(2)] and offspring[AField(3)] are exactly integers in float64 form (1.0 or 2.0), you can simplify:
if (offspring[AField(2)] == 1 && offspring[AField(3)] == 1) || (offspring[AField(2)] == 2 && offspring[AField(3)] == 2) { offspring[AField(13)] = float64(rand.Intn(26)+25) / 100 } else { offspring[AField(13)] = 1 } -
Debug print statements
Insert debug print statements just before the
ifcondition to check the actual values:fmt.Println("A2:", offspring[AField(2)], "A3:", offspring[AField(3)])
Summary:
- Double check your
floatEqualsimplementation or use direct comparison if possible. - Confirm values in
offspringare exactly what you expect. - Confirm random number generator is properly seeded.
- Add debug prints to confirm logic.
- Using direct equality checks if values are exactly integers but stored as floats.
If you want me to review your
floatEqualsimplementation or the data feeding into this code, please provide it. - User
package main
import ( "bufio" "fmt" "log" "math" "math/rand" "os" "strconv" "strings" "time" ) const FieldsCount = 149 // AField returns zero-based index for field A func AField(n int) int { return n - 1 } // Helper: floating-point equality tolerance func floatEquals(a, b float64) bool { const epsilon = 0.0001 return math.Abs(a-b) < 1e-9 } // Parses one line from [ca/:A1,A2,...] into a float64 slice func parseLine(line string) ([]float64, error) { if !strings.HasPrefix(line, "[ca/:") || !strings.HasSuffix(line, "]") { return nil, fmt.Errorf("Invalid line format") } content := line[5 : len(line)-1] parts := strings.Split(content, ",") if len(parts) < FieldsCount { return nil, fmt.Errorf("Not enough fields: %d", len(parts)) } fields := make([]float64, FieldsCount) for i, p := range parts[:FieldsCount] { v, err := strconv.ParseFloat(p, 64) if err != nil { return nil, fmt.Errorf("Parse float error at field %d: %v", i+1, err) } fields[i] = v } return fields, nil } // Formats fields slice back to line string func formatLine(fields []float64) string { parts := make([]string, len(fields)) for i, v := range fields { if floatEquals(v, float64(int64(v))) { parts[i] = strconv.FormatInt(int64(v), 10) } else { parts[i] = fmt.Sprintf("%.5g", v) } } return "[ca/:" + strings.Join(parts, ",") + "]" } // Reads file, returns slice of line offsets and (A2,A3) values and maxID // It store offsets so it can seek and read lines on demand, not full contents func scanFileForParents(path string) (parent1Offsets []int64, parent2Offsets []int64, maxID int64, err error) { f, err := os.Open(path) if err != nil { return nil, nil, 0, err } defer f.Close() scanner := bufio.NewScanner(f) offset := int64(0) for scanner.Scan() { line := scanner.Text() fields, err := parseLine(line) if err != nil { return nil, nil, 0, err } id := int64(fields[AField(1)]) if id > maxID { maxID = id } a2 := fields[AField(2)] a3 := fields[AField(3)] if floatEquals(a2, 1) && floatEquals(a3, 1) { parent1Offsets = append(parent1Offsets, offset) } else { parent2Offsets = append(parent2Offsets, offset) } // +1 for newline offset += int64(len(line)) + 1 } if err := scanner.Err(); err != nil { return nil, nil, 0, err } return parent1Offsets, parent2Offsets, maxID, nil } // Reads one line at offset (assumes lines end with \n) func readLineAtOffset(f *os.File, offset int64) ([]float64, error) { _, err := f.Seek(offset, 0) if err != nil { return nil, err } reader := bufio.NewReader(f) line, err := reader.ReadString('\n') if err != nil { return nil, err } return parseLine(strings.TrimRight(line, "\r\n")) } // Helper for random choose 1 element from slices of float64 func choice(s []float64) float64 { return s[rand.Intn(len(s))] } // Helper clamp to 0-255 ints func clampInt(i int) int { if i < 0 { return 0 } else if i > 255 { return 255 } return i } // Copy or set fields conditionally helper // If condition==true, set all fields [from:to] to trueVal // Else if trueVal==falseVal==0, randomly copy from p1 or p2 for all these fields // Else set all fields [from:to] to falseVal func copyOrSetConditional(offspring, p1, p2 []float64, from, to int, condition bool, trueVal, falseVal float64) { if condition { for i := from; i <= to; i++ { offspring[i] = trueVal } } else if trueVal == 0 && falseVal == 0 { if rand.Intn(2) == 0 { copy(offspring[from:to+1], p1[from:to+1]) } else { copy(offspring[from:to+1], p2[from:to+1]) } } else { for i := from; i <= to; i++ { offspring[i] = falseVal } } } // Create offspring fields per rules, given parents p1 and p2 fields, new ID func createOffspring(p1, p2 []float64, newID int64) []float64 { offspring := make([]float64, FieldsCount) offspring[AField(1)] = float64(newID) // Rule 2 a2Candidates := []float64{p1[AField(2)], p1[AField(3)], p2[AField(2)], p2[AField(3)]} a2 := choice(a2Candidates) offspring[AField(2)] = a2 if a2 == p1[AField(2)] || a2 == p1[AField(3)] { offspring[AField(3)] = choice([]float64{p2[AField(2)], p2[AField(3)]}) } else { offspring[AField(3)] = choice([]float64{p1[AField(2)], p1[AField(3)]}) } // Rule 3 a4Candidates := []float64{p1[AField(4)], p1[AField(5)], p2[AField(4)], p2[AField(5)]} a4 := choice(a4Candidates) offspring[AField(4)] = a4 if a4 == p1[AField(4)] || a4 == p1[AField(5)] { offspring[AField(5)] = choice([]float64{p2[AField(4)], p2[AField(5)]}) } else { offspring[AField(5)] = choice([]float64{p1[AField(4)], p1[AField(5)]}) } // Rule 4: A6...A9 from p1 or p2 + random offset source := p1 if rand.Intn(2) == 1 { source = p2 } for i := AField(6); i <= AField(9); i++ { base := int(source[i]) offset := rand.Intn(21) - 10 offspring[i] = float64(clampInt(base + offset)) } // Rule 5: A10...A12 pick all from p1 or p2 randomly if rand.Intn(2) == 0 { copy(offspring[AField(10):AField(13)], p1[AField(10):AField(13)]) } else { copy(offspring[AField(10):AField(13)], p2[AField(10):AField(13)]) } // Rule 6 A13 a2a311 := floatEquals(offspring[AField(2)], 1) && floatEquals(offspring[AField(3)], 1) a2a322 := floatEquals(offspring[AField(2)], 2) && floatEquals(offspring[AField(3)], 2) if a2a311 || a2a322 { // 0.25 to 0.5 offspring[AField(13)] = float64(rand.Intn(26)+25) / 100 } else { offspring[AField(13)] = 1 } // Rule 7: A14...A16 pick from one parent randomly if rand.Intn(2) == 0 { copy(offspring[AField(14):AField(17)], p1[AField(14):AField(17)]) } else { copy(offspring[AField(14):AField(17)], p2[AField(14):AField(17)]) } // Rule 8: A17 same pattern as A13 if a2a311 || a2a322 { offspring[AField(17)] = float64(rand.Intn(26)+25) / 100 } else { offspring[AField(17)] = 1 } // Rule 9: A18...A20 pick from one parent randomly if rand.Intn(2) == 0 { copy(offspring[AField(18):AField(21)], p1[AField(18):AField(21)]) } else { copy(offspring[AField(18):AField(21)], p2[AField(18):AField(21)]) } // Rule 10: A21 conditional if a2a311 { offspring[AField(21)] = float64(rand.Intn(26)+25) / 100 } else { offspring[AField(21)] = 0 } // Rules 11-16 combined using helper: type condRule struct { from, to int condition bool trueVal, falseVal float64 } rules := []condRule{ // Rule 11: A22-A24 choose parent {AField(22), AField(24), false, 0, 0}, // Rule 12: A25 conditional value {AField(25), AField(25), a2a311 || a2a322, 0, 1}, // Rule 13: A26-A28 choose parent {AField(26), AField(28), false, 0, 0}, // Rule 14: A29 conditional value {AField(29), AField(29), a2a311 || a2a322, 0, 1}, // Rule 15: A30-A32 choose parent {AField(30), AField(32), false, 0, 0}, // Rule 16: A33 conditional value {AField(33), AField(33), a2a311, 0, 1}, } for _, r := range rules { copyOrSetConditional(offspring, p1, p2, r.from, r.to, r.condition, r.trueVal, r.falseVal) } // Rule 17: A34-A39 pick parent independently, then randomly mutate 1-3 times for i := AField(34); i <= AField(39); i++ { if rand.Intn(2) == 0 { offspring[i] = p1[i] } else { offspring[i] = p2[i] } } toChangeCount := rand.Intn(3) + 1 indices := rand.Perm(6)[:toChangeCount] for _, idx := range indices { pos := AField(34) + idx old := offspring[pos] newVal := float64(rand.Intn(10) + 1) for floatEquals(newVal, old) { newVal = float64(rand.Intn(10) + 1) } offspring[pos] = newVal } // Rule 18-19: A40, A41 random 1-10 offspring[AField(40)] = float64(rand.Intn(10) + 1) offspring[AField(41)] = float64(rand.Intn(10) + 1) // Rule 20: A42 complex mapping a2v := int(offspring[AField(2)]) a3v := int(offspring[AField(3)]) a4v := int(offspring[AField(4)]) var a42 float64 switch { case a2v == 1 && a3v == 1 && a4v == 1: a42 = 1 case a2v == 1 && a3v == 1 && a4v == 2: a42 = 2 case a2v == 1 && a3v == 1 && a4v == 3: a42 = 3 case a2v == 2 && a3v == 2 && a4v == 1: a42 = 4 case a2v == 2 && a3v == 2 && a4v == 2: a42 = 5 case a2v == 2 && a3v == 2 && a4v == 3: a42 = 6 case (a2v == 1 && a3v == 2 && a4v == 1) || (a2v == 2 && a3v == 1 && a4v == 1): a42 = 7 case (a2v == 1 && a3v == 2 && a4v == 2) || (a2v == 2 && a3v == 1 && a4v == 2): a42 = 8 case (a2v == 1 && a3v == 2 && a4v == 3) || (a2v == 2 && a3v == 1 && a4v == 3): a42 = 9 default: a42 = 0 } offspring[AField(42)] = a42 // Rule 21-22: A43, A44 A147 := p1[AField(147)] if a2a311 { offspring[AField(43)] = A147 offspring[AField(44)] = A147 } else { offspring[AField(43)] = 404 offspring[AField(44)] = 404 } // Rule 23: A45 if a2a311 || a2a322 { offspring[AField(45)] = 404 } else { offspring[AField(45)] = A147 } // Rule 24: A46 if a2a311 { offspring[AField(46)] = 404 } else { offspring[AField(46)] = A147 } // Rule 25: Sum A47...A146 = p1 + p2 for i := AField(47); i <= AField(146); i++ { offspring[i] = p1[i] + p2[i] } // Rule 26: Find max in A47...A146, set A147 = max index-46 maxIdx := AField(47) maxVal := offspring[AField(47)] for i := AField(48); i <= AField(146); i++ { if offspring[i] > maxVal { maxVal = offspring[i] maxIdx = i } } offspring[AField(147)] = float64(maxIdx - AField(46)) // Rule 27: Set offspring's A148 = p1's A1, A149 = p2's A1 (parents' IDs) offspring[AField(148)] = p1[AField(1)] offspring[AField(149)] = p2[AField(1)] return offspring } func main() { rand.Seed(time.Now().UnixNano()) file := "CA.txt" // Step 1: Scan file offsets of parents (store minimal info to be memory-friendly) parent1Offsets, parent2Offsets, maxID, err := scanFileForParents(file) if err != nil { log.Fatalf("Failed scanning file: %v", err) } if len(parent1Offsets) == 0 || len(parent2Offsets) == 0 { log.Fatal("No suitable parents found") } // Pick random offsets: offset1 := parent1Offsets[rand.Intn(len(parent1Offsets))] offset2 := parent2Offsets[rand.Intn(len(parent2Offsets))] // Open file for reading parents f, err := os.Open(file) if err != nil { log.Fatalf("Failed to open file: %v", err) } defer f.Close() p1, err := readLineAtOffset(f, offset1) if err != nil { log.Fatalf("Failed to read parent1 at offset %d: %v", offset1, err) } p2, err := readLineAtOffset(f, offset2) if err != nil { log.Fatalf("Failed to read parent2 at offset %d: %v", offset2, err) } offspring := createOffspring(p1, p2, maxID+1) // Append offspring to file outf, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY, 0644) if err != nil { log.Fatalf("Failed opening file to append: %v", err) } defer outf.Close() line := formatLine(offspring) _, err = outf.WriteString(line + "\n") if err != nil { log.Fatalf("Failed to write offspring: %v", err) } fmt.Println("Offspring created and appended:") fmt.Println(line) } But the output isn't following this: 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.
- Assistant
Thank you for the detailed code! After checking your full implementation, the logic for Rule 6 (setting
A13) appears correct and should work as intended. However, you still experience cases where the output violates the rule:If offspring's (A2, A3) = (1, 1) or (2, 2), offspring's A13 is in [0.25,0.5]. Otherwise, offspring's A13 = 1.
What to check next
Let's systematically identify potential reasons for the issue:
1.
floatEqualsimplementation mistakeYour
floatEqualsis:func floatEquals(a, b float64) bool { const epsilon = 0.0001 return math.Abs(a-b) < 1e-9 }You define
epsilonbut do not use it, instead hardcode1e-9as tolerance, which is extremely strict.Considering you parse values from strings, sometimes these may have tiny representation errors, so
1e-9might be too small and cause comparisons likefloatEquals(1.0000000001, 1.0)to befalse.Suggestion: Use the defined epsilon constant for better tolerance, e.g.,
func floatEquals(a, b float64) bool { const epsilon = 0.0001 // or 1e-6 if you want looser tolerance return math.Abs(a-b) < epsilon }This loosens the tolerance enough to avoid floating-point precision issues affecting your equality comparisons.
2. Output verification and debugging helpers
Insert debugging before the
ifblock increateOffspringto print values and confirm the condition:fmt.Printf("Debug A2=%.6f, A3=%.6f\n", offspring[AField(2)], offspring[AField(3)]) a2a311 := floatEquals(offspring[AField(2)], 1) && floatEquals(offspring[AField(3)], 1) a2a322 := floatEquals(offspring[AField(2)], 2) && floatEquals(offspring[AField(3)], 2) fmt.Printf("Condition a2a311=%v, a2a322=%v\n", a2a311, a2a322) if a2a311 || a2a322 { rv := float64(rand.Intn(26)+25) / 100 fmt.Printf("Setting A13 to %.3f\n", rv) offspring[AField(13)] = rv } else { fmt.Println("Setting A13 to 1") offspring[AField(13)] = 1 }Run your program several times and verify:
- Are
(A2, A3)what you expect? - Is the condition evaluating as expected?
- Is
A13set properly?
This helps isolate where the behavior diverges.
3. Verify that
(A2,A3)themselves are set consistentlyYour code for
A2andA3selection increateOffspring:a2Candidates := []float64{p1[AField(2)], p1[AField(3)], p2[AField(2)], p2[AField(3)]} a2 := choice(a2Candidates) offspring[AField(2)] = a2 if a2 == p1[AField(2)] || a2 == p1[AField(3)] { offspring[AField(3)] = choice([]float64{p2[AField(2)], p2[AField(3)]}) } else { offspring[AField(3)] = choice([]float64{p1[AField(2)], p1[AField(3)]}) }This mixes candidate values from both parents and might produce
(A2, A3)which don't have the (1,1) or (2,2) pattern very often.Suggestion: Print
(A2, A3)before Rule 6 to confirm their actual values.
4. Check random seed initialization
In your
main(), you correctly call:rand.Seed(time.Now().UnixNano())So randomness should be fine.
5. Ensure no other code overwrites A13 after rule 6
After Rule 6 code, you do not overwrite
A13. So no conflicts.
6. Floating-point printing and formatting
When you print or output values, remember:
- Your
formatLinerounds or formats roughly via%.5g. - If you want to debug strictly, maybe print raw float64 with more decimals to verify that
A13values are actually inside[0.25, 0.5].
Summary
Most likely cause: Your
floatEqualstolerance is too tight (1e-9), causing false equality failures, so the conditiona2a311ora2a322becomes false even when values are very close to 1 or 2.To fix:
Modify
floatEqualsto:func floatEquals(a, b float64) bool { const epsilon = 0.0001 return math.Abs(a-b) < epsilon }Additional debugging prints will help verify behavior.
Optional: Quick Test for floatEquals
You can add a quick test snippet in
main:fmt.Println("floatEquals(1.0, 1.0):", floatEquals(1.0, 1.0)) // expect true fmt.Println("floatEquals(1.000000001, 1.0):", floatEquals(1.000000001, 1.0)) // depends on epsilon fmt.Println("floatEquals(1.0001, 1.0):", floatEquals(1.0001, 1.0)) // expect false if epsilon is 0.0001This will ensure your
floatEqualsbehaves as expected.
If after this diagnosis your problem persists, please share some concrete input lines and output examples to inspect actual numbers.
- Are
- User
package main
import ( "bufio" "fmt" "log" "math" "math/rand" "os" "strconv" "strings" "time" ) const FieldsCount = 149 // AField returns zero-based index for field A func AField(n int) int { return n - 1 } // Helper: floating-point equality tolerance func floatEquals(a, b float64) bool { const epsilon = 0.0001 return math.Abs(a-b) < epsilon } // Parses one line from [ca/:A1,A2,...] into a float64 slice func parseLine(line string) ([]float64, error) { if !strings.HasPrefix(line, "[ca/:") || !strings.HasSuffix(line, "]") { return nil, fmt.Errorf("Invalid line format") } content := line[5 : len(line)-1] parts := strings.Split(content, ",") if len(parts) < FieldsCount { return nil, fmt.Errorf("Not enough fields: %d", len(parts)) } fields := make([]float64, FieldsCount) for i, p := range parts[:FieldsCount] { v, err := strconv.ParseFloat(p, 64) if err != nil { return nil, fmt.Errorf("Parse float error at field %d: %v", i+1, err) } fields[i] = v } return fields, nil } // Formats fields slice back to line string func formatLine(fields []float64) string { parts := make([]string, len(fields)) for i, v := range fields { if floatEquals(v, float64(int64(v))) { parts[i] = strconv.FormatInt(int64(v), 10) } else { parts[i] = fmt.Sprintf("%.5g", v) } } return "[ca/:" + strings.Join(parts, ",") + "]" } // Reads file, returns slice of line offsets and (A2,A3) values and maxID // It store offsets so it can seek and read lines on demand, not full contents func scanFileForParents(path string) (parent1Offsets []int64, parent2Offsets []int64, maxID int64, err error) { f, err := os.Open(path) if err != nil { return nil, nil, 0, err } defer f.Close() scanner := bufio.NewScanner(f) offset := int64(0) for scanner.Scan() { line := scanner.Text() fields, err := parseLine(line) if err != nil { return nil, nil, 0, err } id := int64(fields[AField(1)]) if id > maxID { maxID = id } a2 := fields[AField(2)] a3 := fields[AField(3)] if floatEquals(a2, 1) && floatEquals(a3, 1) { parent1Offsets = append(parent1Offsets, offset) } else { parent2Offsets = append(parent2Offsets, offset) } // +1 for newline offset += int64(len(line)) + 1 } if err := scanner.Err(); err != nil { return nil, nil, 0, err } return parent1Offsets, parent2Offsets, maxID, nil } // Reads one line at offset (assumes lines end with \n) func readLineAtOffset(f *os.File, offset int64) ([]float64, error) { _, err := f.Seek(offset, 0) if err != nil { return nil, err } reader := bufio.NewReader(f) line, err := reader.ReadString('\n') if err != nil { return nil, err } return parseLine(strings.TrimRight(line, "\r\n")) } // Helper for random choose 1 element from slices of float64 func choice(s []float64) float64 { return s[rand.Intn(len(s))] } // Helper clamp to 0-255 ints func clampInt(i int) int { if i < 0 { return 0 } else if i > 255 { return 255 } return i } // Copy or set fields conditionally helper // If condition==true, set all fields [from:to] to trueVal // Else if trueVal==falseVal==0, randomly copy from p1 or p2 for all these fields // Else set all fields [from:to] to falseVal func copyOrSetConditional(offspring, p1, p2 []float64, from, to int, condition bool, trueVal, falseVal float64) { if condition { for i := from; i <= to; i++ { offspring[i] = trueVal } } else if trueVal == 0 && falseVal == 0 { if rand.Intn(2) == 0 { copy(offspring[from:to+1], p1[from:to+1]) } else { copy(offspring[from:to+1], p2[from:to+1]) } } else { for i := from; i <= to; i++ { offspring[i] = falseVal } } } // Create offspring fields per rules, given parents p1 and p2 fields, new ID func createOffspring(p1, p2 []float64, newID int64) []float64 { offspring := make([]float64, FieldsCount) offspring[AField(1)] = float64(newID) // Rule 2 a2Candidates := []float64{p1[AField(2)], p1[AField(3)], p2[AField(2)], p2[AField(3)]} a2 := choice(a2Candidates) offspring[AField(2)] = a2 if a2 == p1[AField(2)] || a2 == p1[AField(3)] { offspring[AField(3)] = choice([]float64{p2[AField(2)], p2[AField(3)]}) } else { offspring[AField(3)] = choice([]float64{p1[AField(2)], p1[AField(3)]}) } // Rule 3 a4Candidates := []float64{p1[AField(4)], p1[AField(5)], p2[AField(4)], p2[AField(5)]} a4 := choice(a4Candidates) offspring[AField(4)] = a4 if a4 == p1[AField(4)] || a4 == p1[AField(5)] { offspring[AField(5)] = choice([]float64{p2[AField(4)], p2[AField(5)]}) } else { offspring[AField(5)] = choice([]float64{p1[AField(4)], p1[AField(5)]}) } // Rule 4: A6...A9 from p1 or p2 + random offset source := p1 if rand.Intn(2) == 1 { source = p2 } for i := AField(6); i <= AField(9); i++ { base := int(source[i]) offset := rand.Intn(21) - 10 offspring[i] = float64(clampInt(base + offset)) } // Rule 5: A10...A12 pick all from p1 or p2 randomly if rand.Intn(2) == 0 { copy(offspring[AField(10):AField(13)], p1[AField(10):AField(13)]) } else { copy(offspring[AField(10):AField(13)], p2[AField(10):AField(13)]) } // Rule 6 A13 fmt.Printf("Debug A2=%.6f, A3=%.6f\n", offspring[AField(2)], offspring[AField(3)]) a2a311 := floatEquals(offspring[AField(2)], 1) && floatEquals(offspring[AField(3)], 1) a2a322 := floatEquals(offspring[AField(2)], 2) && floatEquals(offspring[AField(3)], 2) fmt.Printf("Condition a2a311=%v, a2a322=%v\n", a2a311, a2a322) if a2a311 || a2a322 { // 0.25 to 0.5 rv := float64(rand.Intn(26)+25) / 100 fmt.Printf("Setting A13 to %.3f\n", rv) offspring[AField(13)] = rv } else { fmt.Println("Setting A13 to 1") offspring[AField(13)] = 1 } // Rule 7: A14...A16 pick from one parent randomly if rand.Intn(2) == 0 { copy(offspring[AField(14):AField(17)], p1[AField(14):AField(17)]) } else { copy(offspring[AField(14):AField(17)], p2[AField(14):AField(17)]) } // Rule 8: A17 same pattern as A13 if a2a311 || a2a322 { offspring[AField(17)] = float64(rand.Intn(26)+25) / 100 } else { offspring[AField(17)] = 1 } // Rule 9: A18...A20 pick from one parent randomly if rand.Intn(2) == 0 { copy(offspring[AField(18):AField(21)], p1[AField(18):AField(21)]) } else { copy(offspring[AField(18):AField(21)], p2[AField(18):AField(21)]) } // Rule 10: A21 conditional if a2a311 { offspring[AField(21)] = float64(rand.Intn(26)+25) / 100 } else { offspring[AField(21)] = 0 } // Rules 11-16 combined using helper: type condRule struct { from, to int condition bool trueVal, falseVal float64 } rules := []condRule{ // Rule 11: A22-A24 choose parent {AField(22), AField(24), false, 0, 0}, // Rule 12: A25 conditional value {AField(25), AField(25), a2a311 || a2a322, 0, 1}, // Rule 13: A26-A28 choose parent {AField(26), AField(28), false, 0, 0}, // Rule 14: A29 conditional value {AField(29), AField(29), a2a311 || a2a322, 0, 1}, // Rule 15: A30-A32 choose parent {AField(30), AField(32), false, 0, 0}, // Rule 16: A33 conditional value {AField(33), AField(33), a2a311, 0, 1}, } for _, r := range rules { copyOrSetConditional(offspring, p1, p2, r.from, r.to, r.condition, r.trueVal, r.falseVal) } // Rule 17: A34-A39 pick parent independently, then randomly mutate 1-3 times for i := AField(34); i <= AField(39); i++ { if rand.Intn(2) == 0 { offspring[i] = p1[i] } else { offspring[i] = p2[i] } } toChangeCount := rand.Intn(3) + 1 indices := rand.Perm(6)[:toChangeCount] for _, idx := range indices { pos := AField(34) + idx old := offspring[pos] newVal := float64(rand.Intn(10) + 1) for floatEquals(newVal, old) { newVal = float64(rand.Intn(10) + 1) } offspring[pos] = newVal } // Rule 18-19: A40, A41 random 1-10 offspring[AField(40)] = float64(rand.Intn(10) + 1) offspring[AField(41)] = float64(rand.Intn(10) + 1) // Rule 20: A42 complex mapping a2v := int(offspring[AField(2)]) a3v := int(offspring[AField(3)]) a4v := int(offspring[AField(4)]) var a42 float64 switch { case a2v == 1 && a3v == 1 && a4v == 1: a42 = 1 case a2v == 1 && a3v == 1 && a4v == 2: a42 = 2 case a2v == 1 && a3v == 1 && a4v == 3: a42 = 3 case a2v == 2 && a3v == 2 && a4v == 1: a42 = 4 case a2v == 2 && a3v == 2 && a4v == 2: a42 = 5 case a2v == 2 && a3v == 2 && a4v == 3: a42 = 6 case (a2v == 1 && a3v == 2 && a4v == 1) || (a2v == 2 && a3v == 1 && a4v == 1): a42 = 7 case (a2v == 1 && a3v == 2 && a4v == 2) || (a2v == 2 && a3v == 1 && a4v == 2): a42 = 8 case (a2v == 1 && a3v == 2 && a4v == 3) || (a2v == 2 && a3v == 1 && a4v == 3): a42 = 9 default: a42 = 0 } offspring[AField(42)] = a42 // Rule 21-22: A43, A44 A147 := p1[AField(147)] if a2a311 { offspring[AField(43)] = A147 offspring[AField(44)] = A147 } else { offspring[AField(43)] = 404 offspring[AField(44)] = 404 } // Rule 23: A45 if a2a311 || a2a322 { offspring[AField(45)] = 404 } else { offspring[AField(45)] = A147 } // Rule 24: A46 if a2a311 { offspring[AField(46)] = 404 } else { offspring[AField(46)] = A147 } // Rule 25: Sum A47...A146 = p1 + p2 for i := AField(47); i <= AField(146); i++ { offspring[i] = p1[i] + p2[i] } // Rule 26: Find max in A47...A146, set A147 = max index-46 maxIdx := AField(47) maxVal := offspring[AField(47)] for i := AField(48); i <= AField(146); i++ { if offspring[i] > maxVal { maxVal = offspring[i] maxIdx = i } } offspring[AField(147)] = float64(maxIdx - AField(46)) // Rule 27: Set offspring's A148 = p1's A1, A149 = p2's A1 (parents' IDs) offspring[AField(148)] = p1[AField(1)] offspring[AField(149)] = p2[AField(1)] return offspring } func main() { rand.Seed(time.Now().UnixNano()) file := "CA.txt" // Step 1: Scan file offsets of parents (store minimal info to be memory-friendly) parent1Offsets, parent2Offsets, maxID, err := scanFileForParents(file) if err != nil { log.Fatalf("Failed scanning file: %v", err) } if len(parent1Offsets) == 0 || len(parent2Offsets) == 0 { log.Fatal("No suitable parents found") } // Pick random offsets: offset1 := parent1Offsets[rand.Intn(len(parent1Offsets))] offset2 := parent2Offsets[rand.Intn(len(parent2Offsets))] // Open file for reading parents f, err := os.Open(file) if err != nil { log.Fatalf("Failed to open file: %v", err) } defer f.Close() p1, err := readLineAtOffset(f, offset1) if err != nil { log.Fatalf("Failed to read parent1 at offset %d: %v", offset1, err) } p2, err := readLineAtOffset(f, offset2) if err != nil { log.Fatalf("Failed to read parent2 at offset %d: %v", offset2, err) } offspring := createOffspring(p1, p2, maxID+1) // Append offspring to file outf, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY, 0644) if err != nil { log.Fatalf("Failed opening file to append: %v", err) } defer outf.Close() line := formatLine(offspring) _, err = outf.WriteString(line + "\n") if err != nil { log.Fatalf("Failed to write offspring: %v", err) } fmt.Println("Offspring created and appended:") fmt.Println(line) } Failed scanning file: Parse float error at field 149: strconv.ParseFloat: parsing "1][ca/:21": invalid syntax
- Assistant
The error message is:
Failed scanning file: Parse float error at field 149: strconv.ParseFloat: parsing "1][ca/:21": invalid syntaxThis means when you try to parse field 149 (the last field), the string you get is
"1][ca/:21"which is invalid as a float.
What this tells us
- Your input file line format should be like:
[ca/:A1,A2,...,A149]- Your
parseLine(line string)extracts the content between prefix[ca/:and suffix]
content := line[5 : len(line)-1]-
Then splits by
, -
The last field, field 149, is getting a value like
"1][ca/:21" -
That suggests that your input file contains concatenated lines or missing line breaks so that when you read a line, you're not reading a single complete line, but accidentally a chunk containing the end of one line and the start of the next
Cause and fix
Likely cause
The input file probably uses Windows-style line endings (
\r\n) but you are only trimming\r\non read line.In particular, your
scanner.Text()reads lines separated by\n, but if the file uses\r\n, this is okay becausescanner.Text()strips\n, but the leftover\rremains in the line.Your
parseLinetries to parse the line including any extra trailing\rif not trimmed properly.Or the file might be malformed with no real line breaks, or double lines concatenated in one physical line due to earlier writes failing with no line breaks.
How to fix this:
- In your
parseLineyou canTrimSpacefirst before processing (removes\rand whitespace):
func parseLine(line string) ([]float64, error) { line = strings.TrimSpace(line) // <- trim whitespace including \r and \n if !strings.HasPrefix(line, "[ca/:") || !strings.HasSuffix(line, "]") { return nil, fmt.Errorf("Invalid line format") } content := line[5 : len(line)-1] parts := strings.Split(content, ",") ...- Also in
readLineAtOffset, you're doing:
return parseLine(strings.TrimRight(line, "\r\n"))TrimRight(line, "\r\n")removes all trailing\rand\nchars, so this should be fine as is.- To be safe, add debug prints to ascertain file lines:
line, err := reader.ReadString('\n') if err != nil { return nil, err } fmt.Printf("Read line: '%s'\n", line) // Debug line content return parseLine(strings.TrimSpace(line))And check if lines contain unexpected embedded lines.
- Alternatively, it may be an issue with your input file formatting or how you appended lines.
Important: Are you appending lines correctly?
In your
mainafter creating offspring, you do:line := formatLine(offspring) _, err = outf.WriteString(line + "\n")Make sure this actually writes the newline (
\n) after each offspring line.If the file ends with no newline, the next read might combine two logical lines into one physical line, causing parse errors on the next read.
You can verify your file manually in an editor or by adding a newline after every line.
Summary and checklist:
-
Add
strings.TrimSpacecall inparseLineon input line. -
Add debug print in
readLineAtOffsetto view actual line being read. -
Verify your input file really has one well-formed
[ca/: ... ]entry per line. -
Verify your code appends new lines with trailing newline (\n).
-
If the file is corrupted or lines are concatenated without newlines, fix that.
Adjusted parseLine example:
func parseLine(line string) ([]float64, error) { line = strings.TrimSpace(line) if !strings.HasPrefix(line, "[ca/:") || !strings.HasSuffix(line, "]") { return nil, fmt.Errorf("Invalid line format") } content := line[5 : len(line)-1] parts := strings.Split(content, ",") if len(parts) < FieldsCount { return nil, fmt.Errorf("Not enough fields: %d", len(parts)) } fields := make([]float64, FieldsCount) for i, p := range parts[:FieldsCount] { v, err := strconv.ParseFloat(p, 64) if err != nil { return nil, fmt.Errorf("Parse float error at field %d: %v", i+1, err) } fields[i] = v } return fields, nil }
If you still get errors, please provide a sample of 2-3 input lines (with exact format) from your file to help diagnose.
- User
package main
import ( "bufio" "fmt" "log" "math" "math/rand" "os" "strconv" "strings" "time" ) const FieldsCount = 149 // AField returns zero-based index for field A func AField(n int) int { return n - 1 } // Helper: floating-point equality tolerance func floatEquals(a, b float64) bool { const epsilon = 0.0001 return math.Abs(a-b) < epsilon } // Parses one line from [ca/:A1,A2,...] into a float64 slice func parseLine(line string) ([]float64, error) { line = strings.TrimSpace(line) if !strings.HasPrefix(line, "[ca/:") || !strings.HasSuffix(line, "]") { return nil, fmt.Errorf("Invalid line format") } content := line[5 : len(line)-1] parts := strings.Split(content, ",") if len(parts) < FieldsCount { return nil, fmt.Errorf("Not enough fields: %d", len(parts)) } fields := make([]float64, FieldsCount) for i, p := range parts[:FieldsCount] { v, err := strconv.ParseFloat(p, 64) if err != nil { return nil, fmt.Errorf("Parse float error at field %d: %v", i+1, err) } fields[i] = v } return fields, nil } // Formats fields slice back to line string func formatLine(fields []float64) string { parts := make([]string, len(fields)) for i, v := range fields { if floatEquals(v, float64(int64(v))) { parts[i] = strconv.FormatInt(int64(v), 10) } else { parts[i] = fmt.Sprintf("%.5g", v) } } return "[ca/:" + strings.Join(parts, ",") + "]" } // Reads file, returns slice of line offsets and (A2,A3) values and maxID // It store offsets so it can seek and read lines on demand, not full contents func scanFileForParents(path string) (parent1Offsets []int64, parent2Offsets []int64, maxID int64, err error) { f, err := os.Open(path) if err != nil { return nil, nil, 0, err } defer f.Close() scanner := bufio.NewScanner(f) offset := int64(0) for scanner.Scan() { line := scanner.Text() fields, err := parseLine(line) if err != nil { return nil, nil, 0, err } id := int64(fields[AField(1)]) if id > maxID { maxID = id } a2 := fields[AField(2)] a3 := fields[AField(3)] if floatEquals(a2, 1) && floatEquals(a3, 1) { parent1Offsets = append(parent1Offsets, offset) } else { parent2Offsets = append(parent2Offsets, offset) } // +1 for newline offset += int64(len(line)) + 1 } if err := scanner.Err(); err != nil { return nil, nil, 0, err } return parent1Offsets, parent2Offsets, maxID, nil } // Reads one line at offset (assumes lines end with \n) func readLineAtOffset(f *os.File, offset int64) ([]float64, error) { _, err := f.Seek(offset, 0) if err != nil { return nil, err } reader := bufio.NewReader(f) line, err := reader.ReadString('\n') if err != nil { return nil, err } fmt.Printf("Read line: '%s'\n", line) return parseLine(strings.TrimRight(line)) } // Helper for random choose 1 element from slices of float64 func choice(s []float64) float64 { return s[rand.Intn(len(s))] } // Helper clamp to 0-255 ints func clampInt(i int) int { if i < 0 { return 0 } else if i > 255 { return 255 } return i } // Copy or set fields conditionally helper // If condition==true, set all fields [from:to] to trueVal // Else if trueVal==falseVal==0, randomly copy from p1 or p2 for all these fields // Else set all fields [from:to] to falseVal func copyOrSetConditional(offspring, p1, p2 []float64, from, to int, condition bool, trueVal, falseVal float64) { if condition { for i := from; i <= to; i++ { offspring[i] = trueVal } } else if trueVal == 0 && falseVal == 0 { if rand.Intn(2) == 0 { copy(offspring[from:to+1], p1[from:to+1]) } else { copy(offspring[from:to+1], p2[from:to+1]) } } else { for i := from; i <= to; i++ { offspring[i] = falseVal } } } // Create offspring fields per rules, given parents p1 and p2 fields, new ID func createOffspring(p1, p2 []float64, newID int64) []float64 { offspring := make([]float64, FieldsCount) offspring[AField(1)] = float64(newID) // Rule 2 a2Candidates := []float64{p1[AField(2)], p1[AField(3)], p2[AField(2)], p2[AField(3)]} a2 := choice(a2Candidates) offspring[AField(2)] = a2 if a2 == p1[AField(2)] || a2 == p1[AField(3)] { offspring[AField(3)] = choice([]float64{p2[AField(2)], p2[AField(3)]}) } else { offspring[AField(3)] = choice([]float64{p1[AField(2)], p1[AField(3)]}) } // Rule 3 a4Candidates := []float64{p1[AField(4)], p1[AField(5)], p2[AField(4)], p2[AField(5)]} a4 := choice(a4Candidates) offspring[AField(4)] = a4 if a4 == p1[AField(4)] || a4 == p1[AField(5)] { offspring[AField(5)] = choice([]float64{p2[AField(4)], p2[AField(5)]}) } else { offspring[AField(5)] = choice([]float64{p1[AField(4)], p1[AField(5)]}) } // Rule 4: A6...A9 from p1 or p2 + random offset source := p1 if rand.Intn(2) == 1 { source = p2 } for i := AField(6); i <= AField(9); i++ { base := int(source[i]) offset := rand.Intn(21) - 10 offspring[i] = float64(clampInt(base + offset)) } // Rule 5: A10...A12 pick all from p1 or p2 randomly if rand.Intn(2) == 0 { copy(offspring[AField(10):AField(13)], p1[AField(10):AField(13)]) } else { copy(offspring[AField(10):AField(13)], p2[AField(10):AField(13)]) } // Rule 6 A13 fmt.Printf("Debug A2=%.6f, A3=%.6f\n", offspring[AField(2)], offspring[AField(3)]) a2a311 := floatEquals(offspring[AField(2)], 1) && floatEquals(offspring[AField(3)], 1) a2a322 := floatEquals(offspring[AField(2)], 2) && floatEquals(offspring[AField(3)], 2) fmt.Printf("Condition a2a311=%v, a2a322=%v\n", a2a311, a2a322) if a2a311 || a2a322 { // 0.25 to 0.5 rv := float64(rand.Intn(26)+25) / 100 fmt.Printf("Setting A13 to %.3f\n", rv) offspring[AField(13)] = rv } else { fmt.Println("Setting A13 to 1") offspring[AField(13)] = 1 } // Rule 7: A14...A16 pick from one parent randomly if rand.Intn(2) == 0 { copy(offspring[AField(14):AField(17)], p1[AField(14):AField(17)]) } else { copy(offspring[AField(14):AField(17)], p2[AField(14):AField(17)]) } // Rule 8: A17 same pattern as A13 if a2a311 || a2a322 { offspring[AField(17)] = float64(rand.Intn(26)+25) / 100 } else { offspring[AField(17)] = 1 } // Rule 9: A18...A20 pick from one parent randomly if rand.Intn(2) == 0 { copy(offspring[AField(18):AField(21)], p1[AField(18):AField(21)]) } else { copy(offspring[AField(18):AField(21)], p2[AField(18):AField(21)]) } // Rule 10: A21 conditional if a2a311 { offspring[AField(21)] = float64(rand.Intn(26)+25) / 100 } else { offspring[AField(21)] = 0 } // Rules 11-16 combined using helper: type condRule struct { from, to int condition bool trueVal, falseVal float64 } rules := []condRule{ // Rule 11: A22-A24 choose parent {AField(22), AField(24), false, 0, 0}, // Rule 12: A25 conditional value {AField(25), AField(25), a2a311 || a2a322, 0, 1}, // Rule 13: A26-A28 choose parent {AField(26), AField(28), false, 0, 0}, // Rule 14: A29 conditional value {AField(29), AField(29), a2a311 || a2a322, 0, 1}, // Rule 15: A30-A32 choose parent {AField(30), AField(32), false, 0, 0}, // Rule 16: A33 conditional value {AField(33), AField(33), a2a311, 0, 1}, } for _, r := range rules { copyOrSetConditional(offspring, p1, p2, r.from, r.to, r.condition, r.trueVal, r.falseVal) } // Rule 17: A34-A39 pick parent independently, then randomly mutate 1-3 times for i := AField(34); i <= AField(39); i++ { if rand.Intn(2) == 0 { offspring[i] = p1[i] } else { offspring[i] = p2[i] } } toChangeCount := rand.Intn(3) + 1 indices := rand.Perm(6)[:toChangeCount] for _, idx := range indices { pos := AField(34) + idx old := offspring[pos] newVal := float64(rand.Intn(10) + 1) for floatEquals(newVal, old) { newVal = float64(rand.Intn(10) + 1) } offspring[pos] = newVal } // Rule 18-19: A40, A41 random 1-10 offspring[AField(40)] = float64(rand.Intn(10) + 1) offspring[AField(41)] = float64(rand.Intn(10) + 1) // Rule 20: A42 complex mapping a2v := int(offspring[AField(2)]) a3v := int(offspring[AField(3)]) a4v := int(offspring[AField(4)]) var a42 float64 switch { case a2v == 1 && a3v == 1 && a4v == 1: a42 = 1 case a2v == 1 && a3v == 1 && a4v == 2: a42 = 2 case a2v == 1 && a3v == 1 && a4v == 3: a42 = 3 case a2v == 2 && a3v == 2 && a4v == 1: a42 = 4 case a2v == 2 && a3v == 2 && a4v == 2: a42 = 5 case a2v == 2 && a3v == 2 && a4v == 3: a42 = 6 case (a2v == 1 && a3v == 2 && a4v == 1) || (a2v == 2 && a3v == 1 && a4v == 1): a42 = 7 case (a2v == 1 && a3v == 2 && a4v == 2) || (a2v == 2 && a3v == 1 && a4v == 2): a42 = 8 case (a2v == 1 && a3v == 2 && a4v == 3) || (a2v == 2 && a3v == 1 && a4v == 3): a42 = 9 default: a42 = 0 } offspring[AField(42)] = a42 // Rule 21-22: A43, A44 A147 := p1[AField(147)] if a2a311 { offspring[AField(43)] = A147 offspring[AField(44)] = A147 } else { offspring[AField(43)] = 404 offspring[AField(44)] = 404 } // Rule 23: A45 if a2a311 || a2a322 { offspring[AField(45)] = 404 } else { offspring[AField(45)] = A147 } // Rule 24: A46 if a2a311 { offspring[AField(46)] = 404 } else { offspring[AField(46)] = A147 } // Rule 25: Sum A47...A146 = p1 + p2 for i := AField(47); i <= AField(146); i++ { offspring[i] = p1[i] + p2[i] } // Rule 26: Find max in A47...A146, set A147 = max index-46 maxIdx := AField(47) maxVal := offspring[AField(47)] for i := AField(48); i <= AField(146); i++ { if offspring[i] > maxVal { maxVal = offspring[i] maxIdx = i } } offspring[AField(147)] = float64(maxIdx - AField(46)) // Rule 27: Set offspring's A148 = p1's A1, A149 = p2's A1 (parents' IDs) offspring[AField(148)] = p1[AField(1)] offspring[AField(149)] = p2[AField(1)] return offspring } func main() { rand.Seed(time.Now().UnixNano()) file := "CA.txt" // Step 1: Scan file offsets of parents (store minimal info to be memory-friendly) parent1Offsets, parent2Offsets, maxID, err := scanFileForParents(file) if err != nil { log.Fatalf("Failed scanning file: %v", err) } if len(parent1Offsets) == 0 || len(parent2Offsets) == 0 { log.Fatal("No suitable parents found") } // Pick random offsets: offset1 := parent1Offsets[rand.Intn(len(parent1Offsets))] offset2 := parent2Offsets[rand.Intn(len(parent2Offsets))] // Open file for reading parents f, err := os.Open(file) if err != nil { log.Fatalf("Failed to open file: %v", err) } defer f.Close() p1, err := readLineAtOffset(f, offset1) if err != nil { log.Fatalf("Failed to read parent1 at offset %d: %v", offset1, err) } p2, err := readLineAtOffset(f, offset2) if err != nil { log.Fatalf("Failed to read parent2 at offset %d: %v", offset2, err) } offspring := createOffspring(p1, p2, maxID+1) // Append offspring to file outf, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY, 0644) if err != nil { log.Fatalf("Failed opening file to append: %v", err) } defer outf.Close() line := formatLine(offspring) _, err = outf.WriteString(line + "\n") if err != nil { log.Fatalf("Failed to write offspring: %v", err) } fmt.Println("Offspring created and appended:") fmt.Println(line) }
command-line-arguments
.\CF.go:102:37: not enough arguments in call to strings.TrimRight have (string) want (string, string)
- Assistant
The error message
.\CF.go:102:37: not enough arguments in call to strings.TrimRight have (string) want (string, string)is because you called
strings.TrimRightwith only one argument:return parseLine(strings.TrimRight(line))but
strings.TrimRightrequires two arguments: the string to trim and the cutset specifying which characters to remove, e.g.:strings.TrimRight(s, cutset string) string
How to fix
Replace:
return parseLine(strings.TrimRight(line))with either:
return parseLine(strings.TrimRight(line, "\r\n"))or more commonly:
return parseLine(strings.TrimSpace(line))TrimSpaceremoves all leading and trailing whitespace including\rand\n, so it's usually better for trimming line breaks.
Corrected
readLineAtOffsetfunction snippet:func readLineAtOffset(f *os.File, offset int64) ([]float64, error) { _, err := f.Seek(offset, 0) if err != nil { return nil, err } reader := bufio.NewReader(f) line, err := reader.ReadString('\n') if err != nil { return nil, err } fmt.Printf("Read line: '%s'\n", line) return parseLine(strings.TrimSpace(line)) }
This should fix the compile error.
If you still face parsing errors, check the trimmed line string using the debug print and verify the input file's format is correct (one
[ca/: ... ]record per line, properly newline separated). - User
package main
import ( "bufio" "fmt" "log" "math" "math/rand" "os" "strconv" "strings" "time" ) const FieldsCount = 149 // AField returns zero-based index for field A func AField(n int) int { return n - 1 } // Helper: floating-point equality tolerance func floatEquals(a, b float64) bool { const epsilon = 0.0001 return math.Abs(a-b) < epsilon } // Parses one line from [ca/:A1,A2,...] into a float64 slice func parseLine(line string) ([]float64, error) { line = strings.TrimSpace(line) if !strings.HasPrefix(line, "[ca/:") || !strings.HasSuffix(line, "]") { return nil, fmt.Errorf("Invalid line format") } content := line[5 : len(line)-1] parts := strings.Split(content, ",") if len(parts) < FieldsCount { return nil, fmt.Errorf("Not enough fields: %d", len(parts)) } fields := make([]float64, FieldsCount) for i, p := range parts[:FieldsCount] { v, err := strconv.ParseFloat(p, 64) if err != nil { return nil, fmt.Errorf("Parse float error at field %d: %v", i+1, err) } fields[i] = v } return fields, nil } // Formats fields slice back to line string func formatLine(fields []float64) string { parts := make([]string, len(fields)) for i, v := range fields { if floatEquals(v, float64(int64(v))) { parts[i] = strconv.FormatInt(int64(v), 10) } else { parts[i] = fmt.Sprintf("%.5g", v) } } return "[ca/:" + strings.Join(parts, ",") + "]" } // Reads file, returns slice of line offsets and (A2,A3) values and maxID // It store offsets so it can seek and read lines on demand, not full contents func scanFileForParents(path string) (parent1Offsets []int64, parent2Offsets []int64, maxID int64, err error) { f, err := os.Open(path) if err != nil { return nil, nil, 0, err } defer f.Close() scanner := bufio.NewScanner(f) offset := int64(0) for scanner.Scan() { line := scanner.Text() fields, err := parseLine(line) if err != nil { return nil, nil, 0, err } id := int64(fields[AField(1)]) if id > maxID { maxID = id } a2 := fields[AField(2)] a3 := fields[AField(3)] if floatEquals(a2, 1) && floatEquals(a3, 1) { parent1Offsets = append(parent1Offsets, offset) } else { parent2Offsets = append(parent2Offsets, offset) } // +1 for newline offset += int64(len(line)) + 1 } if err := scanner.Err(); err != nil { return nil, nil, 0, err } return parent1Offsets, parent2Offsets, maxID, nil } // Reads one line at offset (assumes lines end with \n) func readLineAtOffset(f *os.File, offset int64) ([]float64, error) { _, err := f.Seek(offset, 0) if err != nil { return nil, err } reader := bufio.NewReader(f) line, err := reader.ReadString('\n') if err != nil { return nil, err } fmt.Printf("Read line: '%s'\n", line) return parseLine(strings.TrimSpace(line)) } // Helper for random choose 1 element from slices of float64 func choice(s []float64) float64 { return s[rand.Intn(len(s))] } // Helper clamp to 0-255 ints func clampInt(i int) int { if i < 0 { return 0 } else if i > 255 { return 255 } return i } // Copy or set fields conditionally helper // If condition==true, set all fields [from:to] to trueVal // Else if trueVal==falseVal==0, randomly copy from p1 or p2 for all these fields // Else set all fields [from:to] to falseVal func copyOrSetConditional(offspring, p1, p2 []float64, from, to int, condition bool, trueVal, falseVal float64) { if condition { for i := from; i <= to; i++ { offspring[i] = trueVal } } else if trueVal == 0 && falseVal == 0 { if rand.Intn(2) == 0 { copy(offspring[from:to+1], p1[from:to+1]) } else { copy(offspring[from:to+1], p2[from:to+1]) } } else { for i := from; i <= to; i++ { offspring[i] = falseVal } } } // Create offspring fields per rules, given parents p1 and p2 fields, new ID func createOffspring(p1, p2 []float64, newID int64) []float64 { offspring := make([]float64, FieldsCount) offspring[AField(1)] = float64(newID) // Rule 2 a2Candidates := []float64{p1[AField(2)], p1[AField(3)], p2[AField(2)], p2[AField(3)]} a2 := choice(a2Candidates) offspring[AField(2)] = a2 if a2 == p1[AField(2)] || a2 == p1[AField(3)] { offspring[AField(3)] = choice([]float64{p2[AField(2)], p2[AField(3)]}) } else { offspring[AField(3)] = choice([]float64{p1[AField(2)], p1[AField(3)]}) } // Rule 3 a4Candidates := []float64{p1[AField(4)], p1[AField(5)], p2[AField(4)], p2[AField(5)]} a4 := choice(a4Candidates) offspring[AField(4)] = a4 if a4 == p1[AField(4)] || a4 == p1[AField(5)] { offspring[AField(5)] = choice([]float64{p2[AField(4)], p2[AField(5)]}) } else { offspring[AField(5)] = choice([]float64{p1[AField(4)], p1[AField(5)]}) } // Rule 4: A6...A9 from p1 or p2 + random offset source := p1 if rand.Intn(2) == 1 { source = p2 } for i := AField(6); i <= AField(9); i++ { base := int(source[i]) offset := rand.Intn(21) - 10 offspring[i] = float64(clampInt(base + offset)) } // Rule 5: A10...A12 pick all from p1 or p2 randomly if rand.Intn(2) == 0 { copy(offspring[AField(10):AField(13)], p1[AField(10):AField(13)]) } else { copy(offspring[AField(10):AField(13)], p2[AField(10):AField(13)]) } // Rule 6 A13 fmt.Printf("Debug A2=%.6f, A3=%.6f\n", offspring[AField(2)], offspring[AField(3)]) a2a311 := floatEquals(offspring[AField(2)], 1) && floatEquals(offspring[AField(3)], 1) a2a322 := floatEquals(offspring[AField(2)], 2) && floatEquals(offspring[AField(3)], 2) fmt.Printf("Condition a2a311=%v, a2a322=%v\n", a2a311, a2a322) if a2a311 || a2a322 { // 0.25 to 0.5 rv := float64(rand.Intn(26)+25) / 100 fmt.Printf("Setting A13 to %.3f\n", rv) offspring[AField(13)] = rv } else { fmt.Println("Setting A13 to 1") offspring[AField(13)] = 1 } // Rule 7: A14...A16 pick from one parent randomly if rand.Intn(2) == 0 { copy(offspring[AField(14):AField(17)], p1[AField(14):AField(17)]) } else { copy(offspring[AField(14):AField(17)], p2[AField(14):AField(17)]) } // Rule 8: A17 same pattern as A13 if a2a311 || a2a322 { offspring[AField(17)] = float64(rand.Intn(26)+25) / 100 } else { offspring[AField(17)] = 1 } // Rule 9: A18...A20 pick from one parent randomly if rand.Intn(2) == 0 { copy(offspring[AField(18):AField(21)], p1[AField(18):AField(21)]) } else { copy(offspring[AField(18):AField(21)], p2[AField(18):AField(21)]) } // Rule 10: A21 conditional if a2a311 { offspring[AField(21)] = float64(rand.Intn(26)+25) / 100 } else { offspring[AField(21)] = 0 } // Rules 11-16 combined using helper: type condRule struct { from, to int condition bool trueVal, falseVal float64 } rules := []condRule{ // Rule 11: A22-A24 choose parent {AField(22), AField(24), false, 0, 0}, // Rule 12: A25 conditional value {AField(25), AField(25), a2a311 || a2a322, 0, 1}, // Rule 13: A26-A28 choose parent {AField(26), AField(28), false, 0, 0}, // Rule 14: A29 conditional value {AField(29), AField(29), a2a311 || a2a322, 0, 1}, // Rule 15: A30-A32 choose parent {AField(30), AField(32), false, 0, 0}, // Rule 16: A33 conditional value {AField(33), AField(33), a2a311, 0, 1}, } for _, r := range rules { copyOrSetConditional(offspring, p1, p2, r.from, r.to, r.condition, r.trueVal, r.falseVal) } // Rule 17: A34-A39 pick parent independently, then randomly mutate 1-3 times for i := AField(34); i <= AField(39); i++ { if rand.Intn(2) == 0 { offspring[i] = p1[i] } else { offspring[i] = p2[i] } } toChangeCount := rand.Intn(3) + 1 indices := rand.Perm(6)[:toChangeCount] for _, idx := range indices { pos := AField(34) + idx old := offspring[pos] newVal := float64(rand.Intn(10) + 1) for floatEquals(newVal, old) { newVal = float64(rand.Intn(10) + 1) } offspring[pos] = newVal } // Rule 18-19: A40, A41 random 1-10 offspring[AField(40)] = float64(rand.Intn(10) + 1) offspring[AField(41)] = float64(rand.Intn(10) + 1) // Rule 20: A42 complex mapping a2v := int(offspring[AField(2)]) a3v := int(offspring[AField(3)]) a4v := int(offspring[AField(4)]) var a42 float64 switch { case a2v == 1 && a3v == 1 && a4v == 1: a42 = 1 case a2v == 1 && a3v == 1 && a4v == 2: a42 = 2 case a2v == 1 && a3v == 1 && a4v == 3: a42 = 3 case a2v == 2 && a3v == 2 && a4v == 1: a42 = 4 case a2v == 2 && a3v == 2 && a4v == 2: a42 = 5 case a2v == 2 && a3v == 2 && a4v == 3: a42 = 6 case (a2v == 1 && a3v == 2 && a4v == 1) || (a2v == 2 && a3v == 1 && a4v == 1): a42 = 7 case (a2v == 1 && a3v == 2 && a4v == 2) || (a2v == 2 && a3v == 1 && a4v == 2): a42 = 8 case (a2v == 1 && a3v == 2 && a4v == 3) || (a2v == 2 && a3v == 1 && a4v == 3): a42 = 9 default: a42 = 0 } offspring[AField(42)] = a42 // Rule 21-22: A43, A44 A147 := p1[AField(147)] if a2a311 { offspring[AField(43)] = A147 offspring[AField(44)] = A147 } else { offspring[AField(43)] = 404 offspring[AField(44)] = 404 } // Rule 23: A45 if a2a311 || a2a322 { offspring[AField(45)] = 404 } else { offspring[AField(45)] = A147 } // Rule 24: A46 if a2a311 { offspring[AField(46)] = 404 } else { offspring[AField(46)] = A147 } // Rule 25: Sum A47...A146 = p1 + p2 for i := AField(47); i <= AField(146); i++ { offspring[i] = p1[i] + p2[i] } // Rule 26: Find max in A47...A146, set A147 = max index-46 maxIdx := AField(47) maxVal := offspring[AField(47)] for i := AField(48); i <= AField(146); i++ { if offspring[i] > maxVal { maxVal = offspring[i] maxIdx = i } } offspring[AField(147)] = float64(maxIdx - AField(46)) // Rule 27: Set offspring's A148 = p1's A1, A149 = p2's A1 (parents' IDs) offspring[AField(148)] = p1[AField(1)] offspring[AField(149)] = p2[AField(1)] return offspring } func main() { rand.Seed(time.Now().UnixNano()) file := "CA.txt" // Step 1: Scan file offsets of parents (store minimal info to be memory-friendly) parent1Offsets, parent2Offsets, maxID, err := scanFileForParents(file) if err != nil { log.Fatalf("Failed scanning file: %v", err) } if len(parent1Offsets) == 0 || len(parent2Offsets) == 0 { log.Fatal("No suitable parents found") } // Pick random offsets: offset1 := parent1Offsets[rand.Intn(len(parent1Offsets))] offset2 := parent2Offsets[rand.Intn(len(parent2Offsets))] // Open file for reading parents f, err := os.Open(file) if err != nil { log.Fatalf("Failed to open file: %v", err) } defer f.Close() p1, err := readLineAtOffset(f, offset1) if err != nil { log.Fatalf("Failed to read parent1 at offset %d: %v", offset1, err) } p2, err := readLineAtOffset(f, offset2) if err != nil { log.Fatalf("Failed to read parent2 at offset %d: %v", offset2, err) } offspring := createOffspring(p1, p2, maxID+1) // Append offspring to file outf, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY, 0644) if err != nil { log.Fatalf("Failed opening file to append: %v", err) } defer outf.Close() line := formatLine(offspring) _, err = outf.WriteString(line + "\n") if err != nil { log.Fatalf("Failed to write offspring: %v", err) } fmt.Println("Offspring created and appended:") fmt.Println(line) } Failed scanning file: Parse float error at field 149: strconv.ParseFloat: parsing "1][ca/:21": invalid syntax
- Assistant
The error
Parse float error at field 149: strconv.ParseFloat: parsing "1][ca/:21": invalid syntaxclearly shows that during parsing the 149th field as float your program is getting a string value"1][ca/:21". This means that instead of just a number, the string includes something like][ca/:21appended to it, which suggests your input file has concatenated (or malformed) lines.
What is going wrong?
Your
scanFileForParentsreads the file line-by-line usingbufio.Scanner. Eachlineshould correspond to exactly one record like:[ca/:1,1,1,2,2,..., ... ,value_for_A149]However, the fact that during parsing you see tail of next line appended to last field of previous line means the file lines are not properly separated or you are miscalculating offsets — reading partial data.
Why does this happen?
You compute the offsets while scanning like:
offset := int64(0) ... offset += int64(len(line)) + 1You assume each line ends with a single byte for newline (
\n) — adding 1 for each line read.But your input file might use Windows-style line endings (
\r\n), which take two bytes.So the offsets become incorrect by one byte per line.
When you later seek by these offsets and read lines, you may end up starting in the middle of a line or concatenated lines, causing parse failures.
How to fix offset calculation properly?
Instead of manually summing the lengths of the lines + 1, you need to track the actual bytes read including the full line ending.
bufio.Scannerdoes not expose byte offset directly, but you can do this:- Since you need offsets, read file line by line with
bufio.Readeryourself and keep track of bytes.
Or
- Use
bufio.Reader.ReadSlice('\n')or similar and add length of line + length of delimiter (\nvs\r\n).
Alternatively, if input file uses consistent newlines, you can write a helper to detect newline length.
Simple approach: Use
\r\naware offset accountingChange:
offset += int64(len(line)) + 1To:
offset += int64(len(line)) + int64(len(getLineEnding(line)))where
getLineEndingexamines the actual bytes following the line and returns 1 or 2 depending on if\nor\r\nnewline.But since you don't have direct byte slice here, better approach is:
Recommended fix (read the file for offsets using os.File and bufio.Reader)
Create a custom function like:
func scanFileForParents(path string) ([]int64, []int64, int64, error) { f, err := os.Open(path) if err != nil { return nil, nil, 0, err } defer f.Close() parent1Offsets := []int64{} parent2Offsets := []int64{} maxID := int64(0) offset := int64(0) reader := bufio.NewReader(f) for { line, err := reader.ReadString('\n') if err != nil { if err == io.EOF { if len(line) == 0 { break } } else { return nil, nil, 0, err } } lineLen := int64(len(line)) fields, err := parseLine(line) if err != nil { return nil, nil, 0, err } id := int64(fields[AField(1)]) if id > maxID { maxID = id } a2 := fields[AField(2)] a3 := fields[AField(3)] if floatEquals(a2, 1) && floatEquals(a3, 1) { parent1Offsets = append(parent1Offsets, offset) } else { parent2Offsets = append(parent2Offsets, offset) } offset += lineLen if err == io.EOF { break } } return parent1Offsets, parent2Offsets, maxID, nil }Key points:
-
Using
bufio.Reader.ReadString('\n')includes\r\nor\nendings inlineso your offset accounts exactly for file bytes read. -
The offset increases by full
len(line)bytes including any newline chars.
Now your offsets correctly point to the beginning of each logical line.
Why this matters?
Your later code:
_, err := f.Seek(offset, 0) // ... line, err := reader.ReadString('\n')Reads one full logical line from the exact start of a line, so parsing works correctly.
Summary checklist:
-
Change scanOffset function to use
bufio.Readerand accumulate offsets withlen(line). -
Make sure
readLineAtOffsetreads one full line as before. -
Ensure input file lines end with proper newline characters (
\nor\r\n).
Additional note: Debugging
Add a test that loads first 2-3 lines from file with your
scanFileForParentsand prints offsets and extracted(id, A2, A3)values to confirm correctness.
If you want, I can help write a full corrected version of the
scanFileForParentsto reflect this fix. Just ask! - Since you need offsets, read file line by line with