글쓰는쿼카의 PM 여정

⏳재귀함수 (2024. 6. 10.) 본문

개발/알고리즘 & 코딩테스트

⏳재귀함수 (2024. 6. 10.)

글쓰는쿼카 joymet33 2024. 6. 10. 23:25

#스파르타코딩클럽 #내일배움캠프(프론트엔드_React)

#알고리즘 탐험반 #week4

학습일: 2024.6. 10.(월)


배운 내용 요약

1. 재귀함수

함수 안에 자신의 함수를 다시 호출하는 함수를 의미합니다. 이러한 재귀함수는 자신의 로직을 내부적으로 반복하다가, 일정한 조건이 만족되면 함수를 이탈하여 결과를 도출합니다. 

 

('재귀함수'를 검색하면 위와 같은 그래프가 나옵니다)
(실제로 재귀함수를 사용할 때 위와 같은 도식대로 함수가 퍼지고 갈라집니다)
(처음 호출한 함수부터 마지막으로 호출한 함수까지 차례대로 쌓이고, 반대로 반환할 때는 마지막에 호출한 함수부터 처음에 호출한 함수가 차례대로 반환됩니다.)

2. Splice vs. Slice / array.slice vs. string.slice

1) Splice vs. Slice ==> 차이점: 기존 요소의 불변성 여부

Splice() 메서드배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경함

// 기본 구문
    array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

// 예시
// 2번 인덱스에서 한 개 요소 제거하고 "trumpet" 추가
var myFish = ["angel", "clown", "drum", "sturgeon"];
var removed = myFish.splice(2, 1, "trumpet");
// myFish is ["angel", "clown", "trumpet", "sturgeon"]
// removed is ["drum"]

Slice() 메서드는 어떤 배열의 시작(begin)부터 끝(end)까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환하며, 원본 배열은 바뀌지 않음

let fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
let citrus = fruits.slice(1, 3);

// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']

(공식 문서 추가 예제)

더보기
// 다음 예제에서 slice()는 myCar에서 newCar라는 새 배열을 만듭니다. 
// 두 가지 모두 myHonda 객체에 대한 참조를 포함합니다.
// myHonda의 색상이 자주색으로 변경되면 두 배열 모두 변경 사항을 반영합니다.

// Using slice, create newCar from myCar.
let myHonda = { color: "red", wheels: 4, engine: { cylinders: 4, size: 2.2 } };
let myCar = [myHonda, 2, "cherry condition", "purchased 1997"];
let newCar = myCar.slice(0, 2);

// Display the values of myCar, newCar, and the color of myHonda
//  referenced from both arrays.
console.log("myCar = " + JSON.stringify(myCar));
console.log("newCar = " + JSON.stringify(newCar));
console.log("myCar[0].color = " + myCar[0].color);
console.log("newCar[0].color = " + newCar[0].color);

// Change the color of myHonda.
myHonda.color = "purple";
console.log("The new color of my Honda is " + myHonda.color);

// Display the color of myHonda referenced from both arrays.
console.log("myCar[0].color = " + myCar[0].color);
console.log("newCar[0].color = " + newCar[0].color);

 

2) array.slice vs. string.slice ==> Slice() 배열/문자열 모두 사용

slice 함수는 배열과 문자열 모두 쓰일 수 있습니다

(array.slice는 위에서 다뤘기 때문에 string.slice에 대해 알아보고자 합니다.)

  • beginIndex : 추출 시작점인 0부터 시작하는 인덱스
  • endIndex : 0부터 시작하는 추출 종료점 인덱스로 그 직전까지 추출됨
  • 반환 값 : 문자열의 추출된 부분을 담는 새로운 문자열이 반환됨
// 기본 문법
str.slice(beginIndex[, endIndex])

// 예시
var str1 = "The morning is upon us.", // the length of str1 is 23.
  str2 = str1.slice(1, 8),
  str3 = str1.slice(4, -2),
  str4 = str1.slice(12),
  str5 = str1.slice(30);
console.log(str2); // OUTPUT: he morn
console.log(str3); // OUTPUT: morning is upon u
console.log(str4); // OUTPUT: is upon us.
console.log(str5); // OUTPUT: ""

기본 개념을 익히는 문제(practice 1, 2)는 쉬우니까 생략!

문제 3. 글자 뒤집기

// 문제 정의:
// 주어진 문자열을 뒤집으시오.

// 조건
// 꼭 재귀함수(Recursion) 형식으로 해답을 작성해야 합니다.

// 예시:
// 입력: "hello"
// 출력: "olleh"
// 설명: "hello"를 뒤집으면 "olleh"가 됩니다.
// 입력: "world"
// 출력: "dlrow"
// 설명: "world"를 뒤집으면 "dlrow"가 됩니다.
// 입력: "recursion"
// 출력: "noisrucer"
// 설명: "recursion"을 뒤집으면 "noisrucer"가 됩니다.

나의 답변 3)

function reverseString(str) {
  let oneMinusLength = str.length - 1;
  if (oneMinusLength === 0) return str[0];
  if (str === "") return "";
  return str[oneMinusLength] + reverseString(str.slice(0, oneMinusLength));
}