[F-Lab 모각코 챌린지-21일차] - 알고리즘 일지

Big One·2023년 5월 31일
0

F-Lab

목록 보기
64/69

문제

1. capitalizeWords

Write a recursive function called capitalizeWords. Given an array of words, return a new array containing each word capitalized.
조건 : 재귀

나의 풀이

function capitalizeWords(arr) {
    if(arr.length === 1) return arr[0].toUpperCase();
    let result = [];
    result.push(arr[0].toUpperCase());
    return result.concat(capitalizeWords(arr.slice(1)));
}

다른 풀이

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;
 
}

느낀점

다른 풀이와 비슷하게 잘 풀은 것 같다. 다른 점은 앞에서부터인지 뒤에서부터인지 차이점이 있다. 음 .. 어느정도 재귀 사용법에 익숙해진 것 같다!

2. stringifyNumbers

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

나의 풀이

function stringifyNumbers(obj) {
    for(let key in obj) {
        if(typeof obj[key] === 'object' && obj[key].length !== 0) {
            stringifyNumbers(obj[key]);
        }else if (typeof obj[key] === 'number'){
            obj[key] = obj[key].toString();
        }
    }
    return obj;
}

다른 풀이

function stringifyNumbers(obj) {
  var newObj = {};
  for (var key in obj) {
    if (typeof obj[key] === 'number') {
      newObj[key] = obj[key].toString();
    } else if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
      newObj[key] = stringifyNumbers(obj[key]);
    } else {
      newObj[key] = obj[key];
    }
  }
  return newObj;
}

느낀점

일단 내 풀이는 테스트 결과 1개를 통과하지 못했다. 1을 예상했는데 '1' 이 나왔다였나 그랬다. 그런데 .... 난 진짜 왜 틀린지 모르겠고 어느 테스트예제에서 막히는건지 잘 모르겠다 .. 아무리 테스트 예시를 생각해도 잘 통과하는 것 같은데 ... 맞는 풀이와 다른거라고는 새 객체를 생성하고 생성한 객체에 넣어주는 것 밖에 없는 것 같은데 .... 이건 정말 모르겠지만 찾아봐야겠다.

2. collectStrings

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

나의 풀이

function collectStrings(obj) {
    let result = [];
    for(let key in obj) {
        if(typeof obj[key] === 'object'){
            result = result.concat(collectStrings(obj[key]));
        }else if(typeof obj[key] === 'string'){
            result.push(obj[key]);
        }
    }
    return result;
}

다른 풀이

function collectStrings(obj) {
    var stringsArr = [];
    for(var key in obj) {
        if(typeof obj[key] === 'string') {
            stringsArr.push(obj[key]);
        }
        else if(typeof obj[key] === 'object') {
            stringsArr = stringsArr.concat(collectStrings(obj[key]));
        }
    }
 
    return stringsArr;
}

느낀점

이번 풀이는 갓벽하게 같다. 그런데 맨 처음 실수한게

result.concat(collectStrings(obj[key]));

이 코드로 썼는데 .. ㅠㅠ concat 함수는 그냥 .. 붙여주는거지 앞에 변수에 대해 변경이 일어나는 것은 아니다. 이걸 착각해서 재할당됐다고 생각하고 진행했었다 ㅠ

result = result.concat(collectStrings(obj[key]));
profile
이번생은 개발자

0개의 댓글