现在的位置: 首页 > 综合 > 正文

约瑟夫环问题

2018年01月08日 ⁄ 综合 ⁄ 共 768字 ⁄ 字号 评论关闭
/**
*使用数组实现约瑟夫环问题
*由m个人围成一个首尾相连的圈报数。
*从第一个人开始,从1开始报数,报到n的人出圈,
*剩下的人继续从1开始报数,直到所有的人都出圈为止。
*对于给定的m和n,求出所有人的出圈顺序.
*/
以下是解答该问题的objective-c语言写法:

    NSMutableArray *arr1 = [NSMutableArray
array];

   
for (int i=1; i<=100; i++)

    {

        [arr1 addObject:[NSNumber
numberWithInt:i]];

    }

    

   
self._index = 0;

    

    [self
Out:arr1 startIndex:0];

- (void) Out:(NSMutableArray *)arr1 startIndex:(NSInteger)index

{

   
NSInteger nTotalIn = [arr1
count
];

   
if (nTotalIn >= 7)

    {

       
NSNumber *n1;

       
if ((index+6) <= (nTotalIn-1))

        {

            n1 = [arr1
objectAtIndex:index+6];

            index += 6;

        }

       
else

        {

            n1 = [arr1
objectAtIndex:index+6-nTotalIn];

            index = index+6-nTotalIn;

        }

        

       
NSLog(@"%d\n",n1.intValue);

        

        [arr1
removeObjectAtIndex:index];

        [self
Out:arr1 startIndex:index];

    }

   
else

    {

       
NSLog(@"done!\n");

    }

}

抱歉!评论已关闭.