Source

euler / go / src / euler / euler.go

Full commit
package main

import (
	"flag"
	"fmt"
	"os"
	"sort"
	"strconv"
)

type Solution struct {
	name string
	fn   func()
}

type Solutions []*Solution
func (s Solutions) Len() int { return len(s) }
func (s Solutions) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s Solutions) Less(i, j int) bool {
	ielem, _ := strconv.Atoi(s[i].name)
	jelem, _ := strconv.Atoi(s[j].name)
	return ielem < jelem
}


var solutions = Solutions{}

func register(name string, fn func()) {
	solutions = append(solutions, &Solution{name, fn})
	sort.Sort(&solutions)
}

func run(name string) error {
	for _, sol := range solutions {
		if sol.name == name {
			sol.fn()
			return nil
		}
	}

	return fmt.Errorf("%s not found", name)
}


func main() {
	list := flag.Bool("list", false, "list solutions")
	flag.Parse()

	if *list {
		for _, sol := range solutions {
			fmt.Println(sol.name)
		}
	}

	for _, name := range flag.Args() {
		err := run(name)
		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %s\n", err)
			os.Exit(1)
		}
	}
}