Machineboy空

Excercism - Matrix : 2차원 배열 본문

Computer/Coding Test

Excercism - Matrix : 2차원 배열

안녕도라 2025. 2. 28. 16:11

 

문제요약

주어진 행렬에 대한 열과 행의 정보를 출력하라.


난이도

Medium


풀이 포인트

  • 입력값 원하는 대로 변환 (string 값 => 정수의 2차원 배열로)
  • 2차원 배열 사용

고정 크기 배열과 가변 길이 배열

https://machineboy0.tistory.com/305

 

C# 컬렉션 - 배열, 다차원 배열 - rank, getLength, Array.IndexOf(), Array.Sort()

컬렉션(Collection)이란?data structures that can hold zero or more elements are known as collections0개 혹은 더 많은 요소를 가질 수 있는 데이터 구조배열(Array) 이란 ? + 특징컬렉션 중 하나fixed size, elements must all be o

machineboy0.tistory.com

 


REVIEW

 

2차원 배열 선언과 활용이 갑자기 헷갈렸던 문제라 정리해둔다.

  • [][] 는 가변 길이 배열
  • [,]는 고정 크기의 배열이다.

 


CODE

// 1. 고정 크기 배열일 경우

using System;
using System.Collections.Generic;

public class Matrix
{
    private int[,] matrix;

    public Matrix(string input)
    {
        string[] rows = input.Split('\n');
        int rowCount = rows.Length;
        int colCount = rows[0].Split(' ').Length; 

        matrix = new int[rowCount, colCount];


        for (int i = 0; i < rowCount; i++)
        {
            string[] cols = rows[i].Split(' ');

            for (int j = 0; j < colCount; j++)
            {
                matrix[i, j] = int.Parse(cols[j]); 
            }
        }
    }

    public int[] Row(int row)
    {
        int colCount = matrix.GetLength(1);
        int[] result = new int[colCount];

        for (int i = 0; i < colCount; i++)
        {
            result[i] = matrix[row - 1, i];
        }

        return result;
    }

    public int[] Column(int col)
    {
        int rowCount = matrix.GetLength(0);
        int[] result = new int[rowCount];

        for (int i = 0; i < rowCount; i++)
        {
            result[i] = matrix[i, col - 1]; 
        }

        return result;
    }
}
// 2. 가변 크기 배열일 경우

public class Matrix
{

    private string[][] matrix;
        
    public Matrix(string input)
    {
        string[] rows = input.Split('\n');
        
        this.matrix = new string[rows.Length][];
            
        for(int i = 0; i < rows.Length; i++)
        {
            this.matrix[i] = rows[i].Split(' ');
        }
    }

    public int[] Row(int row)
    {
        string[] str = matrix[row-1];
        List<int> rows = new List<int>();

        foreach(string c in str)
        {
            rows.Add(int.Parse(c));
        }
        return rows.ToArray();
    }

    public int[] Column(int col)
    {
        List<int> cols = new List<int>();
        
        foreach(string[] s in matrix)
        {
            cols.Add(int.Parse(s[col-1].ToString()));
        }

        return cols.ToArray();
    }
}