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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值