
인프런 워밍업 클럽 CS 3기 2주차 미션 (자료구조와 알고리즘)
1개월 전
자료구조
재귀함수에서 기저조건을 만들지 않거나 잘못 설정했을 때 어떤 문제가 발생할 수 있나요?
종료 조건을 설정하지 않거나 잘못 설정했을 경우 콜스택의 누적으로 인한 메모리 부족으로 강제 종료되거나 혹은 의도하지 않은 결과값을 얻을 수 있습니다.
0부터 입력 n까지 홀수의 합을 더하는 재귀 함수를 만들어보세요.
function sumOdd(n){
// 탈출(기저) 조건 : n이 1일 때
if (n == 1){
return 1;
}
// 재귀 조건 : n이 1보다 큰 홀수일 때
if (n%2 == 1){
return sumOdd(n-2) + n;
}
else{
return sumOdd(n-1);
}
}
console.log(sumOdd(10)) // 25
다음 코드는 매개변수로 주어진 파일 경로(.는 현재 디렉토리)에 있는 하위 모든 파일과 디렉토리를 출력하는 코드입니다. 다음 코드를 재귀 함수를 이용하는 코드로 변경해보세요.
변경 이전
const fs = require("fs"); // 파일을 이용하는 모듈
const path = require("path"); // 폴더와 파일의 경로를 지정해주는 모듈
function traverseDirectory1(directory){
const stack = [directory]; // 순회해야 할 디렉토리를 저장할 스택
while (stack.length > 0) { // 스택이 빌 때까지 반복
const currentDir = stack.pop(); // 현재 디렉토리
const files = fs.readdirSync(currentDir); // 인자로 주어진 경로의 디렉토리에 있는 파일or디렉토리들
for (const file of files) { // 현재 디렉토리의 모든 파일or디렉토리 순회
const filePath = path.join(currentDir, file); //directory와 file을 하나의 경로로 합쳐줌
const fileStatus= fs.statSync(filePath); // 파일정보 얻기
if (fileStatus.isDirectory()) { // 해당 파일이 디렉토리라면
console.log('디렉토리:', filePath);
stack.push(filePath);
} else { // 해당 파일이 파일이라면
console.log('파일:', filePath);
}
}
}
}
traverseDirectory1("."); // 현재 경로의 모든 하위 경로의 파일, 디렉토리 출력
변경 이후
const fs = require("fs"); // 파일을 이용하는 모듈
const path = require("path"); // 폴더와 파일의 경로를 지정해주는 모듈
function traverseDirectory2(directory){
const files = fs.readdirSync(directory);
for (const file of files) { // 모든 파일 및 디렉토리를 순회
const filePath = path.join(directory, file); // 현재 디렉토리와 파일/디렉토리 이름을 결합하여 전체 경로 생성
const fileStatus = fs.statSync(filePath); // 파일/디렉토리 정보를 가져옴
/* 재귀조건: 해당 경로가 디렉토리인 경우 */
if (fileStatus.isDirectory()) {
console.log('디렉토리:', filePath);
traverseDirectoryRecursive(filePath); // 재귀 호출
}
/* 탈출조건: 해당 경로가 파일인 경우 */
else {
console.log('파일:', filePath);
}
}
}
traverseDirectory2("."); // 현재 경로의 모든 하위 경로의 파일, 디렉토리 출력
댓글을 작성해보세요.