約瑟夫環(線性列表的思想)

何畢之發表於2018-06-11
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 = "開始解密";
        }
    }
}


相關文章