기본 틀 :
using System;
public class Solution {
public int[] solution(int[] lottos, int[] win_nums) {
int[] answer = new int[] {};
return answer;
}
}
지문은 굉장히 길지만 문제는 간단하다.
풀이 1)
lottos의 요소 중 0인 요소의 개수를 구하고,
lottos와 win_nums가 요소가 같은 개수를 구한다.
새로운 배열을 만들고
요소로는
Math.Min(6, 7 - (같은 요소 개수 + 0 개수))으로
최고 순위를 결정하고,
Math.Min(6, 7 - (0 개수))으로
최소 순위를 결정한다.
using System;
using System.Linq;
public class Solution {
public int[] solution(int[] lottos, int[] win_nums) {
int max = 0, min = 0;
for(int i = 0; i < lottos.Length; i++)
{
if(lottos[i] == 0)
{
max++;
continue;
}
for(int j = 0; j < win_nums.Length; j++)
if(lottos[i] == win_nums[j]) min++;
}
return new int[] { 7 - (max + min) == 7 ? 6 : 7 - (max + min), 7 - (min) == 7 ? 6 : 7 - (min) };
}
}
풀이 2) 두 배열의 교집합을 구하는 함수 사용
using System;
using System.Linq;
public class Solution {
public int[] solution(int[] lottos, int[] win_nums) {
int min = lottos.Intersect(win_nums).Count();
int max = lottos.Where(element => element == 0).Count();
return new int[] { Math.Min(6, 7 - (max + min)) , Math.Min(6, 7 - (min)) };
}
}
풀이 1을 바탕으로,
Where(element => element == 0).Count();
을 사용하면
'0의 개수를 반복문 없이 구할 수 있는데..., 같은 요소의 수를 구하는 방법은 없을까?'
라는 생각을 했다.
인터넷에 찾아본 결과
Intersect()
라는 함수를 찾게 됐다.
( Where(element => 함수.Contains(element))도 된다는 사실을 늦게 알아 차렸다... )
1. Intersect()는
헤시셋(HashSet)과 Equals() 함수를 사용하기 때문에
int[] set1 = { 1, 2, 2, 3, 4 };
int[] set2 = { 2, 2, 3, 5 };
var result = set1.Intersect(set2);
// 결과 : 2, 3
set1과 set2에 2와 3이 여러 개 있어도
2와 3을 하나 씩만 출력하게 된다.
또한 비교 대상을 지정할 수 있는데
using System;
using System.Linq;
using System.Collections.Generic;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class PersonComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.Name == y.Name;
}
public int GetHashCode(Person obj)
{
return obj.Name.GetHashCode();
}
}
List<Person> list1 = new List<Person>
{
new Person { Name = "Alice", Age = 25 },
new Person { Name = "Bob", Age = 30 },
new Person { Name = "Charlie", Age = 35 }
};
List<Person> list2 = new List<Person>
{
new Person { Name = "Bob", Age = 28 },
new Person { Name = "Charlie", Age = 40 }
};
var result = list1.Intersect(list2, new PersonComparer());
foreach (var person in result)
{
Console.WriteLine(person.Name);
}
/*
결과 :
Bob
Charlie
*/
그 결과, 나이가 다르더라도 이름이 같은 녀석을 비교 대상으로 설정했기 때문에
이름이 같은 요소가 출력되는 것을 확인할 수 있다.
1. Intersect()와 유사한 함수 Union 합집합, Except 차집합
int[] set1 = { 1, 2, 2, 3, 4 };
int[] set2 = { 2, 2, 3, 5 };
var unionSet = set1.Union(set2); // 합집합
var exceptSet1 = set1.Except(set2); // 차집합
var exceptSet2 = set2.Except(set1); // 차집합
// unionSet 결과
// 1, 2, 3, 4, 5
// exceptSet1 결과
// 1, 4
// exceptSet2 결과
// 5
로
Union은 중복을 제거한 요소들의 전체를 보여주었고,
Except는 중복을 제거한 요소들의 차집합을 보여줬다.
'문제 풀기 > C#' 카테고리의 다른 글
63. 숫자 짝수 (Dictionary) (0) | 2025.02.11 |
---|---|
62. 옹알이 (2) (정규식) (0) | 2025.02.11 |
60. 기사단원의 무기 (0) | 2025.02.10 |
59. 덧칠하기 (0) | 2025.02.07 |
58. 소수 만들기 (0) | 2025.02.07 |