python3 实现约瑟夫环

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3 实现约瑟夫环相关的知识,希望对你有一定的参考价值。

参考技术A #coding=GBK

class Node():

    def __init__(self,value,next=None):

        self.value = value

        self.next = next

def createLink(n):

    if n<=0:

        return False

    elif n ==1:

        return Node(1)

    else:

        root = Node(1)

        tmp = root

        for i in range(2,n+1):

            tmp.next = Node(i)

            tmp = tmp.next

        tmp.next = root

        return root

def showLink(root):

    tmp = root

    while True:

        print(tmp.value)

        tmp = tmp.next

        if tmp ==None or tmp == root :

            break

def josephus(n,k):

    if k ==1 :

        print("幸存者:",n)

        return

    root = createLink(n)

    tmp = root

    while True:

        for i in range(k-2):

            tmp = tmp.next

        print("killed:",tmp.next.value)

        tmp.next = tmp.next.next

        tmp = tmp.next

        if tmp.next == tmp:

            break

    print("survive:",tmp.value)

if __name__ =='__main__':

    josephus(10,13)

计算结果:

killed: 3

killed: 7

killed: 2

killed: 10

killed: 1

killed: 6

killed: 8

killed: 9

killed: 4

survive: 5

C#实现约瑟夫环问题

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace orderlyOffarray
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] intPers = Jose(12, 3, 4);
            Console.WriteLine("出列顺序:");
            for (int i = 0; i < intPers.Length; i++)
            {
                Console.WriteLine(intPers[i] + " ");
            }
            Console.ReadLine();
        }

        static int[] Jose(int total, int start, int alter)
        {
            int j, k = 0;
            int[] intCounts = new int[total + 1];
            int[] intPers = new int[total + 1];
            for (int i = 0; i <= total; i++)
            {
                intPers[i] = i;
            }
            for (int i = total; i >= 2; i--)
            {
                start = (start + alter - 1) % i;
                if (start == 0)
                {
                    start = i;
                }
                intCounts[k] = intPers[start];
                k++;
                for (j = start + 1; j <= i; j++)
                {
                    intPers[j - 1] = intPers[j];
                }
            }
            intCounts[k] = intPers[1];
            return intCounts;
        }
    }
}


* 网上有一些实现约瑟夫环代码是有问题的,在给intPers数组赋值时,循环中的条件应该用 i<= total ,否则数组最后一位是0,导致计算结果有误。

以上是关于python3 实现约瑟夫环的主要内容,如果未能解决你的问题,请参考以下文章

python版约瑟夫环

用单向循环链表实现约瑟夫环问题

实现约瑟夫环

Java循环链表实现约瑟夫环(搬运)

约瑟夫环数组简单实现

用循环链表实现约瑟夫环问题