0319 2차원 배열 복습

2021. 3. 19. 10:58C#/수업내용

public class App
    {
        public struct Indexes 
        {
            public int rowIndex;
            public int colIndex;

            public Indexes(int rowIndex, int colIndex) 
            {
                this.rowIndex = rowIndex;
                this.colIndex = colIndex;
            }
        }
        private int[,] arr;
        private int row;
        private int col;
        public App()
        {
            Console.WriteLine("App");

            //int형 배열 초기화
            this.arr = new int[4, 3]; //row, col

            //2차원 배열의 길이 출력
            this.row = arr.GetLength(0); //1차원 row의 길이
            this.col = arr.GetLength(1); //2차원 col의 길이

            //배열 요소에 값 할당
            this.arr[1, 2] = 100;
            this.PrintArray();
            Console.WriteLine("=========================");
            this.arr[2, 0] = 300;
            this.PrintArray();
            Console.WriteLine("=========================");

            Indexes indexesA = new Indexes(1, 2);
            Indexes indexesB = new Indexes(2, 0);

            this.Swap(indexesA,indexesB);
            this.PrintArray();
        }
        private void PrintArray()
        {
            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    Console.Write("{0,3} ", arr[i, j]);
                }
                Console.WriteLine();
            }
        }

        private void Swap(Indexes a, Indexes b) 
        {
            int temp = arr[b.rowIndex, b.colIndex];
            arr[b.rowIndex,b.colIndex]= arr[a.rowIndex, a.colIndex];
            arr[a.rowIndex, a.colIndex] = temp;
        }
    }