标签:
很久以前学C时, 就弄过出局游戏(约瑟夫环), 当时很感兴趣不过没有做出来
今天看到了一个java也里有类似的题, 觉得用面向对象来做更合适……
题目:30个人站成一个圆圈, 从第一个人开始, 每数9个人则出局一人,一共需要出局15人,求哪些编号的人是应该出局的
下面是C#版解法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
//共30个人
int count = 30;
//需要排除的有15个人
int remainingCount = 15;
//每数9个人出局1个人
int position = 9;
//构建环形链
List<Person> list = new List<Person>();
for (int i = 1; i <= count; i++)
{
Person p = new Person()
{
Id = i,
PrevId = i == 1 ? count : i - 1,
NextId = i == count ? 1 : i + 1,
Out = false
};
list.Add(p);
}
//循环直到找出全部需要排除的人为止
for (int j = 0, currId = 1; j < remainingCount;j++)
{
Person currPerson = list.Find(p => p.Id == currId);
int theNextId = 0;
for (int k = 0; k < position; k++)
{
theNextId = currPerson.NextId;
currPerson = list.Find(p => p.Id == theNextId);
}
currPerson.Out = true;
Person prev = list.Find(p => p.Id == currPerson.PrevId);
prev.NextId = currPerson.NextId;
Person next = list.Find(p => p.Id == currPerson.NextId);
next.PrevId = currPerson.PrevId;
currId = currPerson.Id;
}
//输出所有人的编号及是否出局
foreach (Person p in list)
Console.WriteLine(p);
Console.ReadLine();
}
}
public class Person
{
public int Id { get; set; }
public int PrevId { get; set; }
public int NextId { get; set; }
public bool Out { get; set; }
public override string ToString()
{
return string.Format("Id: {0} 是否出局:{1}"
, this.Id > 9 ? this.Id.ToString() : " " + this.Id.ToString()
, this.Out ? "---------->是" : "否");
}
}
}
上面的解法第一个出局的人是10号, 如果希望第一个出局按顺序是9号, 将初始的currId改成30号即可。
标签:
原文地址:http://blog.csdn.net/yenange/article/details/45850305