常用算法(C#): 约瑟夫环问题
2008-09-10 09:27
337 查看
约瑟夫环问题: 设有n个人围坐在圆桌周围,现从某个位置m(1≤m≤n)上的人开始报数,报数到k的人就站出来。
继续下一个人,即原来的第k+1个位置上的人,又从1开始报数,再报数到k的人站出来。依此重复下去,直到全部的人都站出来为止
using System;
using System.Collections.Generic;
using System.Text;
namespace ExJose
{
class ClassJose {
//从第start人开始计数,以alter为单位循环记数出列,总人数为total
public int[] Jose(int total, int start,int alter)
{
int j, k = 0;
//count数组存储按出列顺序的数据,以当结果返回
int[] count = new int[total + 1];
//s数组存储初始数据
int[] s = new int[total + 1];
//对数组s赋初值,第一个人序号为0,第二人为1,依此下去
for (int i = 0; i < total; i++)
{
s[i] = i;
}
//按出列次序依次存于数组count中
for (int i = total; i >= 2; i--)
{
start = (start + alter - 1) % i;
if (start == 0)
start = i;
count[k] = s[start];
k++;
for (j = start + 1; j <= i; j++)
s[j - 1] = s[j];
}
count[k] = s[1];
//结果返回
return count;
}
static void Main(string[] args)
{
ClassJose e=new ClassJose ();
int[] a = e.Jose(10,3,4);
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i].ToString ());
}
}
}
}
继续下一个人,即原来的第k+1个位置上的人,又从1开始报数,再报数到k的人站出来。依此重复下去,直到全部的人都站出来为止
using System;
using System.Collections.Generic;
using System.Text;
namespace ExJose
{
class ClassJose {
//从第start人开始计数,以alter为单位循环记数出列,总人数为total
public int[] Jose(int total, int start,int alter)
{
int j, k = 0;
//count数组存储按出列顺序的数据,以当结果返回
int[] count = new int[total + 1];
//s数组存储初始数据
int[] s = new int[total + 1];
//对数组s赋初值,第一个人序号为0,第二人为1,依此下去
for (int i = 0; i < total; i++)
{
s[i] = i;
}
//按出列次序依次存于数组count中
for (int i = total; i >= 2; i--)
{
start = (start + alter - 1) % i;
if (start == 0)
start = i;
count[k] = s[start];
k++;
for (j = start + 1; j <= i; j++)
s[j - 1] = s[j];
}
count[k] = s[1];
//结果返回
return count;
}
static void Main(string[] args)
{
ClassJose e=new ClassJose ();
int[] a = e.Jose(10,3,4);
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i].ToString ());
}
}
}
}
相关文章推荐
- c# 算法-------约瑟夫环问题
- 常用算法C#实现:字符串包含问题
- [c#算法和数据结构]约瑟夫环问题
- 常用算法(C#): 猴子选大王问题
- 小小c#算法题 - 12 - Joseph Circle(约瑟夫环)
- 赌博算法之约瑟夫环问题(JAVA)
- C#常用的几种算法
- 每天一道算法题(23)——约瑟夫环问题
- 【C#代码实战】群蚁算法理论与实践全攻略——旅行商等路径优化问题的新方法
- C#常用数据结构和算法总结
- 算法----约瑟夫环问题
- C#基础系列问题四数据结构常用术语总结
- 常用算法(C#): 求一个数的最大公约数
- C# 常用算法&Int32转3字节数组
- 群蚁算法理论与实践全攻略——旅行商等路径优化问题的新方法【附C#群蚁算法完整项目代码】
- C#一些常用机密算法DES
- SQL的各种常用算法问题
- [算法]数据结构中关于货郎担路径问题的常用解法,边界路径问题
- 常用数据结构及算法C#/Java实现
- 国际象棋“皇后”问题的回溯算法[C#源码分析]