読者です 読者をやめる 読者になる 読者になる

数独を解く(4日目)

検証ボタンのClickイベントハンドラを記述。

        private void kensyo_Click(object sender, EventArgs e)
        {
            //数字の拾い出し
            int d;
            for (int i = 0; i < 81; i++)
            {
                int.TryParse(IDbutton[i].Text, out d);
                kazu[i] = d;
            }
            //検証を実行
            if (kensyo_do())
            {
                zikko.Enabled = true;
                kensyo.Enabled = false;
                foreach (Button a in IDbutton)
                {
                    a.Enabled = false;
                }
            }
            else
            {
                MessageBox.Show("入力が不適です",Application.ProductName
                    , MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private bool kensyo_do()
        {
            int[] box_kensyo = new int[9];
            int[] tate_kensyo = new int[9];
            int[] yoko_kensyo = new int[9];
            
            for (int i = 0; i < 9; i++)
            {
                for (int ii = 0; ii < 9; ii++)
                {
                    //3×3の検証
                    box_kensyo[ii] = kazu[start_position[i] + next_position[ii]];
                    //横の検証
                    yoko_kensyo[ii] = kazu[i * 9 + ii];
                    //縦の検証
                    tate_kensyo[ii] = kazu[i + ii * 9];
                }
                if (box_kensyo.Where(c => c > 0).Count() != box_kensyo.Where(c => c > 0).Distinct().Count()) return false;
                if (yoko_kensyo.Where(c => c > 0).Count() != yoko_kensyo.Where(c => c > 0).Distinct().Count()) return false;
                if (tate_kensyo.Where(c => c > 0).Count() != tate_kensyo.Where(c => c > 0).Distinct().Count()) return false;
            }
            return true;
        }