타입 챌린지 35191 - Trace

소파의 벨로그·2025년 6월 11일

타입챌린지

목록 보기
111/131

문제 링크

문제

정행렬의 대각합은 정행렬의 주대각에 있는 요소의 합이다.

그러나, 타입 시스템에서 그 합을 계산하는 것은 어렵다.

간단하게, 주대각에 있는 요소를 유니온 타입으로 반환하라.

The trace of a square matrix is the sum of the elements on its main diagonal.
However, it's difficult to calculate the sum with type system.
To make things simple, let's return the elements on the main diagonal with union type.

내 풀이

type TraceImpelment<T extends any[][],Arr extends any[]=[]>=
 Arr['length'] extends T['length']?never:
  T[Arr['length']][Arr['length']]|TraceImpelment<T,[...Arr,1]>

type Trace<T extends any[][]> = TraceImpelment<T>

우선 사용처에서 구현용 제네릭을 사용하지 못하게 하기 위해 구현과 실제 타입을 분리했다.

주대각은 행과 열의 번호가 같은 요소이므로,
재귀적으로 확인하여 반환하였다.

0개의 댓글