Skip to content

Instantly share code, notes, and snippets.

@alixander
Created May 25, 2015 06:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alixander/2ab6b75c835b00c674be to your computer and use it in GitHub Desktop.
Save alixander/2ab6b75c835b00c674be to your computer and use it in GitHub Desktop.
package main
import (
"github.com/fighterlyt/permutation"
)
func formSolution(arr []int) []Solution {
solution := []Solution{}
for i := 0; i < len(arr); i += 2 {
solution = append(solution, Solution{arr[i], arr[i+1]})
}
return solution
}
func naive(rules []Rule) []Solution {
perm, _ := NewPerm(options, nil)
nextPerm, _ := perm.Next()
currentSolution := formSolution(nextPerm.([]int))
for !isCorrect(currentSolution) && perm.Left() > 0 {
nextPerm, _ = perm.Next()
currentSolution = formSolution(nextPerm.([]int))
}
return currentSolution
}
package main
import (
"fmt"
)
type Rule struct {
op string
result int
}
type Solution struct {
left int
right int
}
var (
rules []Rule
options []int
)
func contains(s []int, e int) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func isSolution(sol Solution, rule Rule) bool {
if applyOp(rule.op, sol) == rule.result {
return true
}
return false
}
func applyOp(op string, sol Solution) int {
switch op {
case "+":
return sol.left + sol.right
case "-":
return sol.left - sol.right
}
return 0
}
func isCorrect(solution []Solution) bool {
index := 0
for index < len(rules) {
if index > 2 {
fmt.Println(solution)
}
if !isSolution(solution[index], rules[index]) {
return false
}
index += 1
}
return true
}
func initVars() {
rules = []Rule{
{"-", 1},
{"+", 9},
{"-", 2},
{"+", 7},
}
options = []int{1, 2, 3, 4, 5, 6, 7, 8}
}
func main() {
initVars()
var naiveSolution []Solution = naive(rules)
fmt.Println("The rules are: ", rules)
fmt.Println("The naive method returns: ", naiveSolution)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment