Go语言实现Josephus Permutation

描述

This problem takes its name by arguably the most important event in the life of the ancient historian Josephus: according to his tale, he and his 40 soldiers were trapped in a cave by the Romans during a siege.
Refusing to surrender to the enemy, they instead opted for mass suicide, with a twist: they formed a circle and proceeded to kill one man every three, until one last man was left (and that it was supposed to kill himself to end the act).
Well, Josephus and another man were the last two and, as we now know every detail of the story, you may have correctly guessed that they didn’t exactly follow through the original idea.
You are now to create a function that returns a Josephus permutation, taking as parameters the initial array/list of items to be permuted as if they were in a circle and counted out every k places until none remained.
Tips and notes: it helps to start counting from 1 up to n, instead of the usual range 0…n-1; k will always be >=1.

分析

方法1:
循环遍历数组,到数组尾则返回数组头。计数器达到指定值,则把当前元素从数组中删除,并放入结果数组。计数器清零后,如果当前元素是数组尾,则跳到数组头,否则从下一个元素(由于当前元素已删除,故原数组下一个元素索引就是删除后新数组的当前元素索引)继续遍历。
方法2:
最省事儿的办法是类似C语言的循环链表,只要链表不空,持续遍历计数删除即可。Go语言可以通过Channel实现。从Channel中取出并立刻放回channel,即模拟了循环链表的行为,妙!

实现

方法1:

func Josephus(items []interface{}, k int) (res []interface{}) {
  res = []interface{}{}
  for i, c := 0, 0; i < len(items); {
    if c < k - 1 {
      i, c = (i + 1) % len(items), c + 1
      continue
    }
    res = append(res, items[i])
    if i == len(items) - 1 {
      items = append(items[:i])
      i = 0
    } else {
      items = append(items[:i], items[i+1:]...)
    }
    c = 0
  }
  return
}

方法2:

func Josephus(items []interface{}, k int) []interface{} {
  ch := make(chan interface{}, len(items))
  res := []interface{}{}
  for _, v := range items {
    ch <- v
  }
  for i := 1; len(ch) > 0; i++ {
    if i % k == 0 {
      res = append(res, <- ch)
    } else {
      ch <- <- ch
    }
  }
  return res
}

你可能感兴趣的:(Go语言习题集)