본문 바로가기

C#/공부

C# 실력 늘리기 8일차

171~172. 게임 가능한 16 퍼즐 만들기: 게임을 할 수 있는 16 퍼즐을 만들어보자.

 

172를 푸는데 171의 내용이 들어가서 결과적으로 둘 다 푼 셈이 되었다.

 

 풀 수 있는 퍼즐의 조건 = (행의 개수 + 뒤집힌 개수 + 0이 있는 행 %2 != 0)

 

using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    public class Program
    {
        public static void Main(String[] args)
        {
            int row=4;
            int []m=new int[row*row];
            SixTeenInvert inverter;      
            List <int>list=new List<int>();
            for(int i=0;i<m.Length;i++){
                list.Add(choose(list,16));
                m[i]=list[i];
            }
            int[,]puzzle=MatrixTrans.Mat1to2<int>(m,row,row);
            inverter = new SixTeenInvert(puzzle);
            while(!inverter.isPossible()){
                print2D<int>(puzzle);
                Console.WriteLine("완성 할수 없는 퍼즐입니다.");
                list.Clear();
                for (int i = 0; i < m.Length; i++)
                {
                    list.Add(choose(list, 16));
                    m[i] = list[i];
                }
                puzzle = MatrixTrans.Mat1to2<int>(m, row, row);
                inverter = new SixTeenInvert(puzzle);
            }
            print2D<int>(puzzle);
            Console.WriteLine("완성 할수 있는 퍼즐입니다.\n");
        }
        public static int choose(List<int> list,int range)  //리스트에 없는 값 생성
        {
            int result;
            Random r = new Random(DateTime.Now.Millisecond);
            while (true)
            {
                result = r.Next(range);
                if (list.Contains(result))
                    continue;
                else
                    return result;
            }
        }
        public static void print2D<T>(T[,] t)   //2차원 배열 출력
        {
            int row = t.GetLength(0);
            int col = t.GetLength(1);
            for(int i=0;i<row;i++){
                for (int j = 0; j < col; j++)
                    Console.Write(t[i, j] + "\t");
                Console.WriteLine();
                Console.WriteLine();
            }
        }
    }
    public class SixTeenInvert  //172
    {
        private int inverNum = 0;
        private int[,] sti;
        public SixTeenInvert(int[,] sti)
        {
            this.sti = sti;
        }
        public bool isPossible()
        {
            if ((sti.GetLength(0) + inverNum + ZeroRow()) % 2 == 0)
                return false;
            return true;
        }
        public void InvertNumbers()
        {
            int[] m = MatrixTrans.Mat2to1<int>(sti);
            int num = m.GetLength(0);
            for (int i = 0; i < num - 1; i++)
            {
                for (int j = i + 1; j < num; j++)
                    if (m[j] != 0 && m[i] > m[j])
                        inverNum++;
            }
        }
        public int ZeroRow()
        {
            int locate = 0;
            int col = sti.GetLength(1);
            int[] m = MatrixTrans.Mat2to1<int>(sti);
            int num = m.GetLength(0);
            for (int i = 0; i < num; i++)
                if (m[i] == 0)
                {
                    locate = i / col;
                    break;
                }
            return locate;
        }
    }
    public class MatrixTrans    //171
    {
        public static T[] Mat2to1<T>(T[,] t)
        {
            T[] m;
            int row = t.GetLength(0);
            int col = t.GetLength(1);
            m = new T[row * col];
            for (int i = 0; i < row; i++)
                for (int j = 0; j < col; j++)
                    m[i * col + j] = t[i, j];
            return m;
        }
        public static T[,] Mat1to2<T>(T[] t, int row, int col)
        {
            T[,] m = new T[row, col];
            int tmp = t.Length;
            for (int i = 0; i < tmp; i++)
                m[i / col, i % col] = t[i];
            return m;
        }
    }
}

 

 

 

176~178: 만년달력 만들기: 만년달력을 만들어보자.

 

달력은 28년마다 완벽하게 같아진다고 한다.

 

176~178이 똑같은 내용이라 178만 구현함

 

using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Globalization;

namespace ConsoleApplication1
{
    public class Program
    {
        public static void Main(String[] args)
        {
            Calender cal = new Calender();
            cal.PrintCalender(2022); 
        }
    }
    public class Calender
    {
        public void PrintCalender(int year)
        {
            for (int i = 1; i < 13; i++)
                PrintCalender(year, i);
        }
        public void PrintCalender(int year, int month)
        {
            DateTime dt = new DateTime(year, month, 1, new GregorianCalendar());
            Console.WriteLine("\t------- {0} 년 {1} 월 -------", dt.Year, dt.Month);
            String s = "월\t화\t수\t목\t금\t토\t일";
            Console.WriteLine(s);
            int startOfWeek = ((int)dt.DayOfWeek) % 7;  //1일의 요일 구하기
            Calendar cal = CultureInfo.InvariantCulture.Calendar;
            int lastDay = cal.GetDaysInMonth(dt.Year, dt.Month, Calendar.CurrentEra);	//달의 마지막 날
            for (int i = 1; i < startOfWeek; i++)
                Console.Write("\t");
            for (int i = 1; i <= lastDay; i++)
            {
                Console.Write("{0,2}\t", i);
                if ((startOfWeek + i) % 7 == 1)
                    Console.WriteLine();
            }
            Console.WriteLine();
        }
    }
}

 

너무 길어서 일부만 캡쳐함

 

 

 

179~180. DateTime을 이용한 바이오리듬 보여주기: 바이오리듬을 구하자.

 

유사과학이다. 사용자 정의 컨트롤을 사용해서 cs 파일이 두개이다. 교재 코드가 부실함

 

Form1.cs

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Globalization;

namespace BioRhythm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
    public class BioRhythm
    {
        private DateTime birthDay;
        private DateTime today;

        public BioRhythm(int year, int month, int day)
        {
            this.birthDay = new DateTime(year, month, day, new GregorianCalendar());
            today = DateTime.Now;
        }
        public DateTime Today
        {
            get { return today; }
            set { today = value; }
        }
        public int HowLong(){
            TimeSpan howSpan=today-birthDay;
            return howSpan.Days;
        }
        public void setToday(int year,int month,int day){
            today = new DateTime(year, month, day, new GregorianCalendar());
        }
        public void PreviousDay()
        {
            today = today.AddDays(-1);
        }
        public void Nextday()
        {
            today = today.AddDays(1);
        }
        public double Physical()
        {
            return Math.Sin(2.0 * Math.PI * HowLong() / 23.0);
        }
        public double Emotial()
        {
            return Math.Sin(2.0 * Math.PI * HowLong() / 28.0);
        }
        public double Intellectual()
        {
            return Math.Sin(2.0 * Math.PI * HowLong() / 33.0);
        }
        public double Perceptive()
        {
            return Math.Sin(2.0 * Math.PI * HowLong() / 38.0);
        }
    }
    public class PointFS
    {
        private List<PointF> pointList = new List<PointF>();
        Color color;

        public PointFS(Color c)
        {
            this.color = c;
        }
        public void Add(PointF p)
        {
            pointList.Add(p);
        }
        public void Remove()
        {
            pointList.Clear();
        }
        public void Draw(Graphics g){
                int count=pointList.Count;
                Pen xPen=new Pen(color,1);  
                for(int i=0;i<count-1;i++)
                    g.DrawLine(xPen,pointList[i], pointList[i+1]);
                xPen.Dispose();
            }
    }
}

 

XYControl.cs

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Globalization;

namespace BioRhythm
{
    public partial class XYControl : UserControl
    {
        Rectangle rect;
        BioRhythm bio;
        DateTime dt;
        Calendar cal;
        int lastOfDay;
        float steps;
        private float orginX = 0.0f;
        private float orginY = 0.0f;
        private float pixH = 100.0f;
        bool isFirst = true;
        PointFS physical = new PointFS(Color.Red);
        PointFS emotial = new PointFS(Color.Blue);
        PointFS intellectual = new PointFS(Color.Green);
        PointFS perceptive = new PointFS(Color.Pink);
        public XYControl()
        {
            InitializeComponent(); 
            rect = this.ClientRectangle;
            this.orginX = rect.Left + 100.0f;
            this.orginY = rect.Top + (rect.Height) / 2;
            this.BackColor = Color.White;
            this.remove();
        }
        public void DrawCross(Graphics g)
        {  //기준선 그리기(추가)
            Pen xPen = new Pen(Color.Black, 1);
            Font font = new Font("Ariel", 9);
            SolidBrush brush = new SolidBrush(System.Drawing.Color.Black);
            StringFormat format = new StringFormat();
            g.DrawLine(xPen, new Point((int)orginX, (int)orginY), new Point(570, (int)orginY)); //가로
            g.DrawLine(xPen, new Point((int)orginX, 30), new Point((int)orginX, 280));  //세로
            for (int i = 1; i <= lastOfDay; i++)    //날짜 그리기
                g.DrawString((i).ToString(), font, brush
                    , new Point((int)orginX + (i - 1) * (470 / lastOfDay), (int)orginY), format);
        }
        public void DrawPhysical(Graphics g)
        {
            Pen xPen = new Pen(Color.Red, 1);
            float stX = this.orginX;
            float stY = this.orginY;
            bio.setToday(dt.Year, dt.Month, 1);
            bio.PreviousDay();
            float xy = stY - pixH * ((float)bio.Physical());
            physical.Add(new PointF(stX, xy));
            for (int i = 1; i <= lastOfDay; i++)
            {
                bio.setToday(dt.Year, dt.Month, i);
                xy = stY - pixH * ((float)bio.Physical());
                physical.Add(new PointF(stX + steps * i, xy));
            }
            physical.Draw(g);
            xPen.Dispose();
        }
        public void DrawEmotial(Graphics g)
        {
            Pen xPen = new Pen(Color.Red, 1);
            float stX = this.orginX;
            float stY = this.orginY;
            bio.setToday(dt.Year, dt.Month, 1);
            bio.PreviousDay();
            float xy = stY - pixH * ((float)bio.Emotial());
            emotial.Add(new PointF(stX, xy));
            for (int i = 1; i <= lastOfDay; i++)
            {
                bio.setToday(dt.Year, dt.Month, i);
                xy = stY - pixH * ((float)bio.Emotial());
                emotial.Add(new PointF(stX + steps * i, xy));
            }
            emotial.Draw(g);
            xPen.Dispose();
        }
        public void DrawIntellectual(Graphics g)
        {
            Pen xPen = new Pen(Color.Red, 1);
            float stX = this.orginX;
            float stY = this.orginY;
            bio.setToday(dt.Year, dt.Month, 1);
            bio.PreviousDay();
            float xy = stY - pixH * ((float)bio.Intellectual());
            intellectual.Add(new PointF(stX, xy));
            for (int i = 1; i <= lastOfDay; i++)
            {
                bio.setToday(dt.Year, dt.Month, i);
                xy = stY - pixH * ((float)bio.Intellectual());
                intellectual.Add(new PointF(stX + steps * i, xy));
            }
            intellectual.Draw(g);
            xPen.Dispose();
        }
        public void DrawPerceptive(Graphics g)
        {
            Pen xPen = new Pen(Color.Red, 1);
            float stX = this.orginX;
            float stY = this.orginY;
            bio.setToday(dt.Year, dt.Month, 1);
            bio.PreviousDay();
            float xy = stY - pixH * ((float)bio.Perceptive());
            perceptive.Add(new PointF(stX, xy));
            for (int i = 1; i <= lastOfDay; i++)
            {
                bio.setToday(dt.Year, dt.Month, i);
                xy = stY - pixH * ((float)bio.Perceptive());
                perceptive.Add(new PointF(stX + steps * i, xy));
            }
            perceptive.Draw(g);
            xPen.Dispose();
        }
        private void XYControl_Load(object sender, EventArgs e)
        {
            DateInit(false);
        }
        private void DateInit(bool bs)
        {
            this.label1.Visible = !bs;
            this.label2.Visible = !bs;
            this.dateTimePicker1.Visible = !bs;
            this.dateTimePicker2.Visible = !bs;
        }
        public void remove()
        {
            physical.Remove();
            emotial.Remove();
            intellectual.Remove();
            perceptive.Remove();
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            this.remove();
            bio = new BioRhythm(this.dateTimePicker1.Value.Year
                , this.dateTimePicker1.Value.Month, this.dateTimePicker1.Value.Day);
            dt = new DateTime(this.dateTimePicker2.Value.Year, this.dateTimePicker2.Value.Month
                , this.dateTimePicker2.Value.Day, new GregorianCalendar());
            cal = CultureInfo.InvariantCulture.Calendar;
            lastOfDay = cal.GetDaysInMonth(dt.Year, dt.Month, Calendar.CurrentEra);
            //steps = (rect.Width - 140.0f);
            steps = (rect.Width-100)/31;
            Graphics g = e.Graphics;
            if (!isFirst)
            {
                this.DrawCross(g);
                this.DrawPhysical(g);
                this.DrawEmotial(g);
                this.DrawIntellectual(g);
                this.DrawPerceptive(g);     
            }
            this.DrawCross(g);
            base.OnPaint(e);
        }
        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            this.Invalidate();
            this.isFirst = false;
        }
        private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
        {
            this.Invalidate();
            this.isFirst = false;
        }
    }
}

 

'C# > 공부' 카테고리의 다른 글

C# 실력 늘리기 10일차  (0) 2022.08.01
C# 실력 늘리기 9일차  (0) 2022.07.29
C# 실력 늘리기 7일차  (0) 2022.07.27
C# 실력 늘리기 6일차  (0) 2022.07.26
C# 실력 늘리기 5일차  (0) 2022.07.25