티스토리 뷰

ALGORITHM/Theory

재귀 challenge 문제

Harimad 2022. 4. 22. 21:03

문제 풀다가 막힐 때 느끼는 고통을 즐기자🤣

이동국 명언: 참고 이겨내🤗


목차

1. reverse
2. isPalindrome
3. someRecursive
4. flatten

5. capitalizeFirst
6. nestedEvenSum
7. capitalizeWords
8. stringifyNumbers
9. collectStrings

 

1. reverse

//Write a recursive function called reverse which accpets a string and returns a new string in reverse.
function reverse(){
	//
}

// reverse('awesome') // 'emosewa'
// reverse('rithmschool') // 'loohcsmhtir'

 

Solution

더보기
// SELF
function reverse(){
  return str ? reverse(str.substring(1)) + str[0] : str
}

// ANSWER
function reverse(str){
	if(str.length <= 1) return str;
	return reverse(str.slice(1)) + str[0];
}

// reverse('awesome') // 'emosewa'
// reverse('rithmschool') // 'loohcsmhtir'

 

 

 

2. isPalindrome

// Write a recursive function called isPalindrome which returns true 
// if the string passed to it a palindrome (reads the same forward and backward). 
// Otherwise it returns false.

// isPalindrome('awesome') // false
// isPalindrome('foobar') // false
// isPalindrome('tacocat') // true
// isPalindrome('amanaplanacanalpanama') // true
// isPalindrome('amanaplanacanalpandemonium') // false

function isPalindrome(){
	//
}

Solution

더보기
// Self

function isPalindrome(){
    function reverse(str) {
      return str ? reverse(str.substring(1)) + str[0] : str;
  }
  return reverse(str) === str
}

// Answer
function isPalindrome(str){
    if(str.length === 1) return true;
    if(str.length === 2) return str[0] === str[1];
    if(str[0] === str.slice(-1)) return isPalindrome(str.slice(1,-1))
    return false;
}

// isPalindrome('awesome') // false
// isPalindrome('foobar') // false
// isPalindrome('tacocat') // true
// isPalindrome('amanaplanacanalpanama') // true
// isPalindrome('amanaplanacanalpandemonium') // false

 

3. someRecursive

// Write a recursive function called someRecursive which accepts an array and a callback.
// The function returns true if a single value in the array returns true when passed to the callback.
// Otherwise it returns false.

// Array.prototype.some()구현하기임
// [1,2,3,4].some(v => v % 2 !==0) //true

// SAMPLE INPUT / OUTPUT
// const isOdd = val => val % 2 !== 0;

// someRecursive([1,2,3,4], isOdd) // true
// someRecursive([4,6,8,9], isOdd) // true
// someRecursive([4,6,8], isOdd) // false
// someRecursive([4,6,8], val => val > 10); // false

function someRecursive(){
	//
}

Solution

더보기
// Self

// SAMPLE INPUT / OUTPUT
const isOdd = val => val % 2 !== 0;

function someRecursive(){
  if (arr.length === 0) return false
  if (callback(arr[0])) return true
  return someRecursive(arr.slice(1), callback)
}

// Answer
function someRecursive(array, callback) {
    if (array.length === 0) return false;
    if (callback(array[0])) return true;
    return someRecursive(array.slice(1),callback);
}

// someRecursive([1,2,3,4], isOdd) // true
// someRecursive([4,6,8,9], isOdd) // true
// someRecursive([4,6,8], isOdd) // false
// someRecursive([4,6,8], val => val > 10); // false

 

 

4. flatten

🎁어려움 - 아래 코드시각화 사이트를 참고해서 이해하길

https://pythontutor.com/visualize.html#mode=edit

// Write a recursive function called flatten which accepts an array of arrays 
// and returns a new array with all values flattened.

// Array.prototype.flat() 구현

function flatten(arr){
	//
}

// flatten([1, 2, 3, [4, 5] ]) // [1, 2, 3, 4, 5]
// flatten([1, [2, [3, 4], [[5]]]]) // [1, 2, 3, 4, 5]
// flatten([[1],[2],[3]]) // [1,2,3]
// flatten([[[[1], [[[2]]], [[[[[[[3]]]]]]]]]]) // [1,2,3]

Solution

더보기
// Self
function flatten(arr){
    if (!arr.length) return []

    let first = arr.shift()
    return (Array.isArray(first) ? flatten(first) : [first]).concat(flatten(arr))
}

// Answer
function flatten(oldArr){
  var newArr = []
  	for(var i = 0; i < oldArr.length; i++){
    	  if(Array.isArray(oldArr[i])){
      		newArr = newArr.concat(flatten(oldArr[i]))
    	} else {
      		newArr.push(oldArr[i])
    	}
  } 
  return newArr;
}

// flatten([1, 2, 3, [4, 5] ]) // [1, 2, 3, 4, 5]
// flatten([1, [2, [3, 4], [[5]]]]) // [1, 2, 3, 4, 5]
// flatten([[1],[2],[3]]) // [1,2,3]
// flatten([[[[1], [[[2]]], [[[[[[[3]]]]]]]]]]) // [1,2,3]

Answer 실행흐름


 

 


5. capitalizeFirst

🎁 복습

// Write a recursive function called capitalizeFirst.
// Given an array of strings, capitalize the first letter of each string in the array.

function capitalizeFirst () {

}

// capitalizeFirst(['car','taco','banana']); // ['Car','Taco','Banana']

Solution

더보기
function capitalizeWords (arr) {
 if (arr.length === 1) {
    return [arr[0][0].toUpperCase() + arr[0].slice(1)];
 }

  const res = capitalizeWords(arr.slice(0, -1));
  const string = arr.slice(arr.length-1)[0][0].toUpperCase() + arr.slice(arr.length-1)[0].substring(1);
  res.push(string);
  return res
}

capitalizeWords(['car','taco','banana']); // ['Car','Taco','Banana']

Answer 실행흐름

 

capitalizeFirst( 'car', 'taco', 'banana' )
	capitalizeFirst( 'car', 'taco' ). push ('Banana')  //	↑ [ 'Car', 'Taco', 'Banana' ]
		capitalizeFirst( 'car' ). push ('Taco')    //	↑ [ 'Car', 'Taco' ]
			return 'Car' //  → → → → → → → → →↑

 

 

6. nestedEvenSum

// 중첩된 객체를 가진 변수에서 value값이 짝수인 값만 더한 결과를 구하시오.

function nestedEvenSum () {
  // add whatever parameters you deem necessary - good luck!
}


var obj1 = {
  outer: 2,
  obj: {
    inner: 2,
    otherObj: {
      superInner: 2,
      notANumber: true,
      alsoNotANumber: "yup"
    }
  }
}

var obj2 = {
  a: 2,
  b: {b: 2, bb: {b: 3, bb: {b: 2}}},
  c: {c: {c: 2}, cc: 'ball', ccc: 5},
  d: 1,
  e: {e: {e: 2}, ee: 'car'}
};

nestedEvenSum(obj1); // 6
nestedEvenSum(obj2); // 10

Solution

더보기
function nestedEvenSum (obj) {
  let sum = 0;
  for (let key in obj) {
    if (typeof obj[key] === 'object') {
      sum += nestedEvenSum(obj[key]);
    } else if (typeof obj[key] === 'number' && obj[key] % 2 === 0){
      sum += obj[key]
    }
  }
  return sum;
}

Answer 실행흐름

 

var obj1 = {
  outer: 2,
  obj: {
    inner: 2,
    otherObj: {
      superInner: 2,
      notANumber: true,
      alsoNotANumber: "yup"
    }
  }
}

nestedEvenSum ( obj1 )				=> return 6 ←←← ④
	sum += 2 (outer: 2)			=> return 4+2 ↑↑③
		typeof obj === 'object'
		sum += nestedEvenSum( obj )
			sum += 2 (inner: 2)	=> return 2+2 ↑↑↑②
			typeof otherObj === 'object'
				sum += 2 (superInner: 2)
                        			=> return 2  ↑↑↑↑①

 


 

 

7. capitalizeWords

// Write a recursivie function called capitalizeWords.
// Given an array of words, return a new array containing each word capitalized.

function capitalizeWords () {
	//
}

capitalizeWords(['car', 'taco', 'banana']) // ['CAR', 'TACO', 'BANANA']

Solution

더보기
function capitalizeWords (array) {
  if (array.length === 1) {
    return [array[0].toUpperCase()];
  }
  let res = capitalizeWords(array.slice(0, -1));
  res.push(array.slice(array.length-1)[0].toUpperCase());
  return res;
 
}

capitalizeWords(['car', 'taco', 'banana']) // ['CAR', 'TACO', 'BANANA']

 


 

8. stringifyNumbers

// Write a function called stringifyNumbers which takes in an object 
// and finds all of the values which are numbers and converts them to stirngs.
// Recursion would be a great way to solve this!

// (번역) 객체를 인자로 받고, 
// 객체안의 모든 숫자인 value값을 찾고 문자로 바꾸는 함수를 만드시오.
// 재귀를 사용하시오.

let obj = {
    num: 1,
    test: [],
    data: {
        val: 4,
        info: {
            isRight: true,
            random: 66
        }
    }
}

function stringifyNumbers(obj) {
	//
}

stringifyNumbers(obj)

//{
//    num: "1",
//    test: [],
//    data: {
//        val: "4",
//        info: {
//           isRight: true,
//            random: "66"
//        }
//    }
//}

Solution

더보기
function stringifyNumbers(obj) {
  const answer = {};
    for (let key in obj) {
      //key 의 value가 숫자일 때
      if (typeof obj[key] === 'number') {
        answer[key] = obj[key].toString();
      }
      //key 의 value가 객체일 때
      else if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
        answer[key] = stringifyNumbers(obj[key]);
      }
      //key 의 value가 배열일 때
      else {
        answer[key] = obj[key];
      }
    }
  return answer;
}

 

9. collectStrings

version1 : pure function needed

version2 : helper function needed

// Write a function called collectStrings which accepts an object 
// and returns an array of all the values in the object that have a typeof string

const obj = {
    stuff: "foo",
    data: {
        val: {
            thing: {
                info: "bar",
                moreInfo: {
                    evenMoreInfo: {
                        weMadeIt: "baz"
                    }
                }
            }
        }
    }
}

collectStrings(obj) // ["foo", "bar", "baz"])

function collectStrings() {
	//
}

Solution

더보기
function collectStrings(obj) {
  let answer = [];
  for (let key in obj) {
    if (typeof obj[key] === 'string') {
      answer.push(obj[key]);
    } else if (typeof obj[key] === 'object') {
      answer = answer.concat(collectStrings(obj[key]));
    }
  }
  return answer;
}
collectStrings(obj) // ["foo", "bar", "baz"])

'ALGORITHM > Theory' 카테고리의 다른 글

Bubble Sort  (0) 2022.04.27
Searching Algorithms  (0) 2022.04.27
재귀 기본 문제  (0) 2022.04.22
재귀(Recursion)  (0) 2022.04.22
Frequency Counter, Multiple Pointers, Sliding Window  (0) 2022.04.01
댓글
다크모드
Document description javascript psychology
더보기 ,제목1 태그 호버