using System; using System.Collections.Generic; using System.Windows.Forms; namespace 约瑟夫环 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //所有人n围成一圈 //顺时针报数,每次报到q的人将被杀掉 //被杀掉的人将从房间内被移走 //然后从被杀掉的下一个人重新报数,继续报q,再清除,直到剩余一人 static int num;//人数 static int sec;//密钥Q static int flag = 0;//上一次删除的位置 private void button1_Click(object sender, EventArgs e) { textBox4.Text = ""; //获取人数和密码 num = Convert.ToInt16(textBox1.Text); sec = Convert.ToInt16(textBox2.Text); //为每个人附一个号码,就坐 List<int> list = new List<int>(); for (int i = 0; i < num; i++) { list.Add(i + 1); } while (list.Count > 1) { if (flag + sec - 1 < list.Count) { flag += sec - 1; textBox4.Text += list[flag].ToString() + " "; list.RemoveAt(flag); } else { flag = (flag + sec - 1) % list.Count; textBox4.Text += list[flag].ToString() + " "; list.RemoveAt(flag); } } textBox3.Text = list[0].ToString(); } private void Form1_Load(object sender, EventArgs e) { label1.Text = "人数"; label2.Text = "密钥"; label3.Text = "剩余号码"; label4.Text = "过程"; button1.Text = "开始解密"; } } }
约瑟夫环(线性列表的思想)
猜你喜欢
转载自blog.csdn.net/hebizhi1997/article/details/80653691
今日推荐
周排行