You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
lavos/cap3/ex17.go

53 lines
1.1 KiB

package cap3
// _node 链表节点,单向循环链表
type _node struct {
Value int
Next *_node
}
// 初始化长度为n的环
func _initCircle(n int) *_node {
head := &_node{0, nil}
current := head
for i := 1; i < n; i++ {
newNode := &_node{i, nil}
current.Next = newNode
current = newNode
}
// 头尾相连成环
current.Next = head
return head
}
// Ex17Normal 小朋友游戏(约瑟夫问题),一般解法(非数学解法),n: 总人数(节点数),k:出队报数
func Ex17Normal(n, k int) int {
circle := _initCircle(n)
current := circle
for current.Next != current {
for i := 1; i < k-1; i++ {
current = current.Next
}
// 报到k-1时移除下一个节点
next := current.Next
current.Next = next.Next
current = current.Next
// 避免内存泄露
next.Next = nil
}
return current.Value
}
// Ex17Math 小朋友游戏(约瑟夫问题),公式递推解法,n: 总人数(节点数),k:出队报数
func Ex17Math(n, k int) int {
idx := 0
for i := 2; i <= n; i++ {
idx = (idx + k) % i
}
return idx
}