Exemple #1
0
func main() {
	flag.Parse()
	if flag.NArg() != 1 {
		fmt.Println("Usage: go run samples/tsp.go ROUTEFILEPATH")
		return
	}
	var routeFileName = flag.Arg(0)
	if !File.Exists(routeFileName) {
		fmt.Println("file " + routeFileName + " does not exist.")
		return
	}
	fmt.Println("using route file: " + routeFileName)

	idToPointLookup := readPoints(routeFileName)
	fmt.Println("read " + strconv.Itoa(len(idToPointLookup)) + " points...")

	calc := func(candidate string) int {
		return getFitness(candidate, idToPointLookup)
	}

	if File.Exists(routeFileName + ".opt.tour") {
		fmt.Println("found optimal solution file: " + routeFileName + ".opt")
		optimalRoute := readOptimalRoute(routeFileName+".opt.tour", len(idToPointLookup))
		fmt.Println("read " + strconv.Itoa(len(optimalRoute)) + " segments in the optimal route")
		points := getPointsInOptimalOrder(idToPointLookup, optimalRoute)
		genes := genericGeneSet[0:len(idToPointLookup)]
		idToPointLookup = make(map[string]Point, len(idToPointLookup))
		for i, v := range points {
			idToPointLookup[genericGeneSet[i:i+1]] = v
		}
		fmt.Print("optimal route: " + genes)
		fmt.Print("\t")
		fmt.Println(getFitness(genes, idToPointLookup))
	}

	geneSet := genericGeneSet[0:len(idToPointLookup)]

	start := time.Now()

	disp := func(candidate string) {
		fmt.Print(candidate)
		fmt.Print("\t")
		fmt.Print(getFitness(candidate, idToPointLookup))
		fmt.Print("\t")
		fmt.Println(time.Since(start))
	}

	var solver = new(genetic.Solver)
	solver.MaxSecondsToRunWithoutImprovement = 20
	solver.LowerFitnessesAreBetter = true

	var best = solver.GetBest(calc, disp, geneSet, len(idToPointLookup), 1)
	fmt.Println()
	fmt.Println(best, "\t", getFitness(best, idToPointLookup))
	fmt.Print("Total time: ")
	fmt.Println(time.Since(start))
}