풀이시간 : 10분 02초
1. 배열을 통해 좌표를 표현 vs 개별 변수에 좌표 표현
2. 최소값 , 최대값 비교는 나중에 한번에 처리 가능
function solution(wallpaper) {
const start = [Infinity, Infinity]; // 최소값
const end = [-Infinity, -Infinity]; // 최대값
const file = '#';
for (const [i, line] of wallpaper.entries()) {
const startX = line.indexOf(file);
const endX = line.lastIndexOf(file);
if (startX !== -1) { // 파일이 존재하는 경우
start[0] = Math.min(start[0], i); // y축 최소값
start[1] = Math.min(start[1], startX); // x축 최소값
end[0] = Math.max(end[0], i); // y축 최대값
end[1] = Math.max(end[1], endX); // x축 최대값
}
}
// 파일이 1칸을 차지함으로 x, y 축 +1 씩
return [start[0], start[1], end[0] + 1, end[1] + 1];
}
해당 문제는 #로 표시된 파일의 위치를 탐색하여 x 축과 y축의 최대값과 최소값을 계산하는것이 핵심인 문제입니다. 최대값과 최소값을 계산하기 위해서 indexOf 와 lastIndexOf 메서드를 활용해 x 좌표를 계산하였고, file 존재 여부를 기준으로 y축의 최소값과 최대값을 구했습니다.
function solution(wallpaper) {
const minX = [];
const minY= [];
const maxX = [];
const maxY= [];
const file = '#';
for (const [i, line] of wallpaper.entries()) {
const startX = line.indexOf(file);
const endX = line.lastIndexOf(file);
if (startX !== -1) { // 파일이 존재하는 라인일 경우
minX.push(startX);
minY.push(i);
maxX.push(endX + 1);
maxY.push(i + 1);
}
}
// 파일이 1칸을 차지함으로 x, y +1 씩
return [Math.min(...minY), Math.min(...minX), Math.max(...maxY), Math.max(...maxX)];
}
기존에는 배열로 x, y 좌표를 관리하던 방식을 minX, maxY 등 직관적인 변수로 변경하여 가독성을 높였으며, 모든 라인에서 최소값과 최대값을 반복적으로 계산하던 과정을 제거하고, 마지막에 한 번에 계산하도록 수정하엿습니다.