Algorithm

[문제풀이] Recursion 심화 (1)

주인장 꼬비 2022. 7. 26. 20:26

function reverse(str) {
  let newStr = "";

  innerReverse(str);
  function innerReverse(str) {
    if (!str) return;
    newStr += str[str.length - 1];
    return innerReverse(str.slice(0, -1));
  }
  return newStr;
}
// Udemy solution
function reverse(str){
	if(str.length <= 1) return str;
	return reverse(str.slice(1)) + str[0];
}

function isPalindrome(str) {
  if (str.length % 2 === 0) return false;

  const reverseStr = reverse(str);

  if (reverseStr === str) {
    return true;
  }
  return false;
}

function reverse(str) {
  let newStr = "";

  innerReverse(str);
  function innerReverse(str) {
    if (!str) return;
    newStr += str[str.length - 1];
    return innerReverse(str.slice(0, -1));
  }
  return newStr;
}
// Udemy Solution
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;
}

 

 

function someRecursive(arr, cb) {
  if (arr.length <= 1) {
    return cb(arr.slice(-1));
  }

  if (cb(arr.slice(-1))) {
    return cb(arr.slice(-1));
  }

  return someRecursive(arr.slice(0, -1), cb);
}
// Udemy Solution
function someRecursive(array, callback) {
    if (array.length === 0) return false;
    if (callback(array[0])) return true;
    return someRecursive(array.slice(1),callback);
}

 

function flatten(arr) {
  const flattenArr = [];

  function pushElem(arr) {
    for (const data of arr) {
      if (typeof data === "object") {
        pushElem(data);
      } else {
        flattenArr.push(data);
      }
    }
  }

  pushElem(arr);
  return flattenArr;
}
// Udemy Solution
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;
}

'Algorithm' 카테고리의 다른 글

Searching Algorithm  (0) 2022.07.27
[문제풀이] Recursion 심화 (2)  (0) 2022.07.27
[문제풀이] Recursion  (0) 2022.07.24
Helper Method Recursion (+ Pure Recursion)  (0) 2022.07.24
Call Stack  (0) 2022.07.24