C# 11650번 좌표 정렬하기, 11651번 좌표 정렬하기2, Linq문법

2022. 1. 10. 13:51C#/[백준] 정렬

좌표 정렬하기
좌표 정렬하기2

좌표 정렬하기 코드 :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _6
{
    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();
            int N = Convert.ToInt32(Console.ReadLine());
            List<List<int>> points = new List<List<int>>();
            int[,] p = new int[N, 2];

            for (int i = 0; i < N; i++)
            {
                string input = Console.ReadLine();
                string[] inputdata = input.Split(' ');
                points.Add(new List<int> { Convert.ToInt32(inputdata[0]), Convert.ToInt32(inputdata[1]) });
            }            

            var output = from point in points
                         orderby point[0], point[1]   
                         select point[0] + " " + point[1];

            foreach (var item in output)
            {
                sb.AppendLine(item);
            }
            Console.WriteLine(sb);

        }
    }
}

좌표 정렬하기2 코드 :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _6
{
    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();
            int N = Convert.ToInt32(Console.ReadLine());
            List<List<int>> points = new List<List<int>>();
            int[,] p = new int[N, 2];

            for (int i = 0; i < N; i++)
            {
                string input = Console.ReadLine();
                string[] inputdata = input.Split(' ');
                points.Add(new List<int> { Convert.ToInt32(inputdata[0]), Convert.ToInt32(inputdata[1]) });
            }            

            var output = from point in points
                         orderby point[1], point[0]
                         select point[0] + " " + point[1];

            foreach (var item in output)
            {
                sb.AppendLine(item);
            }
            Console.WriteLine(sb);
        }
    }
}

코드 풀이 :

2차원 배열정리를 할 수 있는 어떤 메소드가 있지 않을까하고 찾다가 Linq문법을 알게 되었다.

C#에는 Linq(Language-Integrated Query)문법이라는게 있다. 마치 쿼리 문을 작성하듯이 하는 방법이다. 이를 통해 쉽게 정렬할 수 있다. 

Linq

orderby에서 point[0], point[1]을 point[1], point[0]로 바꿔주면 y정렬 후 같다면 x정렬의 의미이다.

 

깃허브 :

https://github.com/CheongHo-Lee/Algorithm-Study

 

GitHub - CheongHo-Lee/Algorithm-Study: Algorithm Study For Coding Test

Algorithm Study For Coding Test. Contribute to CheongHo-Lee/Algorithm-Study development by creating an account on GitHub.

github.com

 

'C# > [백준] 정렬' 카테고리의 다른 글

C# 18870번 좌표 압축  (0) 2022.01.10
C# 10814번 나이순 정렬  (0) 2022.01.10
C# 1181번 단어 정렬  (0) 2022.01.10
C# 1427번 소트인사이드  (0) 2022.01.10
C# 2750번 수 정렬하기, 2751번 수 정렬하기2  (0) 2022.01.10