golang實現商人渡河問題(暴力解法)

學習須要,結合模型實現了商人過河問題。golang

包括:算法

  1. N商人N隨從 M小船問題
  2. 人,貓,雞,米過河問題

目前使用暴力算法,後期打算寫下Dijstra算法求解(畢竟暴力算法沒法證實無解性)ide

模型

S容許狀態集合學習

D容許決策集合spa

代碼

N對商人隨從過河

const N = 3

// 遍歷算法
// 輸入 商人 隨從人數 n = 3,4,5...
// 輸出 每一步的 決策
func nextStep(x, y, stepCount int, printContent string) {
    // 設置遞歸層數,防止無限遞歸。
	if stepCount > 30 {
		return
	}
	// 決策集合
	for _, decision := range [][2]int{{0, 1}, {0, 2}, {1, 0}, {1, 1}, {2, 0}} {  // 能夠改變容許決策集合D
		nextX, nextY := decide(x, y, decision[0], decision[1], stepCount)
		if checkInS(nextX, nextY) {
			nextPrintContent := printContent + fmt.Sprintf("第%d步:%d,%d.", stepCount, decision[0], decision[1])
			//fmt.Println(nextPrintContent)
			if nextX == 0 && nextY == 0 {
				fmt.Println(nextPrintContent, nextX, nextY)
				return
			}
			nextStep(nextX, nextY, stepCount+1, nextPrintContent)
		}
	}

}

// 作決策
func decide(x, y, decisionOne, decisionTwo, stepCount int) (int, int) {
	if stepCount%2 != 0 {
		return x - decisionOne, y - decisionTwo
	} else {
		return x + decisionOne, y + decisionTwo
	}
}

// 查看如今的狀態是否符合 S 容許狀態集合
func checkInS(x, y int) bool {
	if N <= 0 {
		return false
	}
	if x == y {
		return true
	}

	for j := 0; j <= N; j++ {
		if x == 0 && y == j {
			return true
		}
	}

	for j := 0; j <= N; j++ {
		if x == N && y == j {
			return true
		}
	}

	return false
}

複製代碼

人貓雞米過河

同上面算法相似,只是增長了變元code

func nextStep(a, b, c, d, stepCount int, printContent string) {
	if stepCount > 7 {
		return
	}
	for _, decision := range [][4]int{{1, 0, 0, 0}, {1, 0, 0, 1}, {1, 0, 1, 0}, {1, 1, 0, 0}} {
		nextA, nextB, nextC, nextD := decide(a, b, c, d, decision[0], decision[1], decision[2], decision[3], stepCount)
		if checkInS(nextA, nextB, nextC, nextD) {
			nextPrintContent := printContent + fmt.Sprintf("第%d步:%d,%d,%d,%d.", stepCount, decision[0], decision[1], decision[2], decision[3])
			//fmt.Println(nextPrintContent)
			if nextA == 0 && nextB == 0 && nextC == 0 && nextD == 0 {
				fmt.Println(nextPrintContent, nextA, nextB, nextC, nextD)
				return
			}
			nextStep(nextA, nextB, nextC, nextD, stepCount+1, nextPrintContent)
		}
	}
}

func decide(a, b, c, d, decideOne, decideTwo, decideThree, decideFour, stepCount int) (int, int, int, int) {
	if stepCount%2 != 0 {
		// 是奇數 ,減
		return a - decideOne, b - decideTwo, c - decideThree, d - decideFour
	}
	return a + decideOne, b + decideTwo, c + decideThree, d + decideFour
}

func checkInS(a, b, c, d int) bool {
	if 0 <= a && a <= 1 && 0 <= b && b <= 1 && 0 <= c && c <= 1 && 0 <= d && d <= 1 {
		if a == 0 {
			if b+c == 2 || c+d == 2 {
				return false
			}
			return true
		}
		if a == 1 {
			if b+c == 0 || c+d == 0 {
				return false
			}
			return true
		}
		return true
	}
	return false
}

複製代碼
相關文章
相關標籤/搜索