Files
subcoding/grow/grow.go

63 lines
1.1 KiB
Go
Raw Normal View History

2021-11-20 19:38:31 -10:00
package grow
import "github.com/firestuff/subcoding/gen"
import "github.com/firestuff/subcoding/vm"
2021-11-20 20:02:16 -10:00
func (def *Definition) Grow(statusChan chan<- Status) (*vm.Program, error) {
status := Status{
TargetScore: uint64(len(def.Samples)),
}
2021-11-20 20:02:16 -10:00
if statusChan != nil {
statusChan <- status
}
// TODO: Score should be number of output criteria, not number of Samples
2021-11-20 20:02:16 -10:00
for {
status.Attempts++
2021-11-20 19:25:16 -10:00
prog := gen.RandProgram(def.GlobalMemorySize, def.FunctionMemorySize, def.InstructionLimit)
score, err := def.Score(prog)
if err != nil {
2021-11-20 20:02:16 -10:00
close(statusChan)
2021-11-20 19:38:31 -10:00
return nil, err
}
2021-11-20 20:02:16 -10:00
if score > status.BestScore {
status.BestScore = score
status.BestProgram = prog
2021-11-20 20:02:16 -10:00
if statusChan != nil {
statusChan <- status
}
2021-11-20 20:02:16 -10:00
if status.BestScore == status.TargetScore {
close(statusChan)
2021-11-20 19:38:31 -10:00
return prog, nil
}
}
}
}
2021-11-20 20:02:16 -10:00
func (def *Definition) Score(prog *vm.Program) (uint64, error) {
score := uint64(0)
for _, sample := range def.Samples {
state, err := vm.NewState(prog)
if err != nil {
return 0, err
}
sample.SetInputs(state)
state.Execute() // ignore error
if sample.OutputsMatch(state) {
score += 1
}
}
return score, nil
}