TIL_21.11.13

이서현·2021년 11월 13일
0

항해99

목록 보기
2/14
post-thumbnail

14번 부터 22번 까지 문제 풀이

👽나누어 떨어지는 숫자 배열

문제 보러가기

array의 각 element 중
divisor로 나누어 떨어지는 값을
오름차순으로 정렬한 배열을
반환하는 함수, solution을 작성

// let array = [5, 9, 7, 10];
// let divisor = 5;
// return [5, 10]
function solution(arr, divisor){
	let answer = [];
  	// 베열을 돌면서 나누어 떨어지는 값 배열에 담기
  	for(let i = 0; i < arr.length; i++){
        if(arr[i]%divisor === 0){
            answer.push(arr[i])
        } 
    }
  // 나누어 떨어지는 값이 없기 때문에 빈 배열
    if(answer.length === 0){
        answer.push(-1)
    }
    return answer.sort((a,b) => a-b)
}

filter()를 사용 할 수도 있다

function solution(arr, divisor) {
    var answer = arr.filter(v => v%divisor == 0);
    return answer.length == 0 ? [-1] : answer.sort((a,b) => a-b);
}

filter()

filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환

구문
arr.filter(callback(element[, index[, array]])[, thisArg])

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// ["exuberant", "destruction", "present"]

옵션인 thisArg는 이렇게 사용 할 수 있다

(function test(){
    var testArray = [1,2,3,4,5,50,100];
    var obj = {min : 1, max : 10};
    function getThreeUpper(value){
        return value >= this.min && value <= this.max;
    }
    var newArray = testArray.filter(getThreeUpper, obj);
    console.log(newArray);
	// [1, 2, 3, 4, 5]
})(); 
//참조 https://aljjabaegi.tistory.com/312

👽내적

문제 보러가기

문제 설명
길이가 같은 두 1차원 정수 배열 a, b가 매개변수로 주어집니다.
a와 b의 내적을 return 하도록 solution 함수를 완성

function solution(a, b) {
    let  answer = 0;
    for (let i = 0; i < a.length; i++){
        let process1 = a[i] * (b[i]);
        answer += process1
    }
    return answer;
}

👽문자열 내 p와 y의 개수

문제 보러가기

내가 짠 코드

function solution(s){
  let result = true;
  // \ig는 대소문 상관없이 매칭할 수 있다
  let charP = s.match(/p/ig);
  let charY = s.match(/y/ig);

  if((charP.length == charY.length) || charP.length == 0 && charY.length == 0) {
    result = true;
  } else if(charP.length == 0 && charY.length == 0){
      result = true;
  } else {
    result = false;
  }
  return result;
}

다른 사람 풀이

function solution(s) {
  return s.match(/p/ig).length === s.match(/y/ig).length;
}
/* 
p, y가 둘 다 없을 때는 match 함수는 null을 반환
그래서 null은 length함수를 가지고 있지 않기에, 
length 함수가 없다는 undefined 에러가 나기 때문에 변수를 선언하고,
해당 match의 결과가 null일 때는 그 변수에 0을 넣어준 뒤 
그 변수를 비교하는 방식으로 해결해야 예외처리를 완벽하게 할 수 있습니다.
.*/

위 코드의 해결방안

const solution = s => (s.match(/p/ig)||[]).length === (s.match(/y/ig)||[]).length;
/*
p와 y가 없을 때 true가 출력되는 이유가
둘 모두 length가 없는 관계로 
undefined === undefilned가 되기 때문에 true 반환
*/

👽문자열 다루기 기본

문제 보러가기

문제 설명
문자열 s의 길이가 4 혹은 6이고,
숫자로만 구성돼있는지 확인해주는 함수, solution을 완성하세요.
예를 들어 s가 "a234"이면 False를 리턴하고
"1234"라면 True를 리턴하면 됩니다.

제한 사항
s는 길이 1 이상, 길이 8 이하인 문자열입니다.

function solution(s){
  let result = false;
  // 길이가 4 또는 6이고 = (s.length == 4 || s.length == 6)
  // 숫자만 구성 = /^[0-9]+$/.test(s)
  if((s.length == 4 || s.length == 6) && /^[0-9]+$/.test(s)) {
    result = true;
  }
  return result;
}

👽서울에서 김서방 찾기

문제 보러가기

function solution(seoul) {
    let answer = seoul.indexOf('Kim');
    return `김서방은 ${answer}에 있다`;
}

👽수박수박수박수박수박수?

문제 보러가기

n이 홀수면 '수박수', 짝수면 '수박수박'

function solution(n) {
    let result = ""
    for(let i = 1; i<=n; i++){
        if(i % 2 === 0){
            result += "박"
        }else{
            result += "수"
        }
    }
    return result
}

👽완주하지 못한 선수

문제 보러가기

function solution(participant, completion) {
  // 첫머리 글자 순서대로 정렬
  // 두 배열의 교집합이 있다면 똑같은 index로 정렬
    participant.sort();
    completion.sort();
	// 두 배열을 비교 하면 끝
    for(let i = 0; i < participant.length; i++){
        if(participant[i] !== completion[i]){
            return participant[i];
        }
    }
}

👽이상한 문자 만들기

문제 보러가기

입출력 예 설명
"try hello world"는 세 단어 "try", "hello", "world"로 구성되어 있습니다. 각 단어의 짝수번째 문자를 대문자로, 홀수번째 문자를 소문자로 바꾸면 "TrY", "HeLlO", "WoRlD"입니다. 따라서 "TrY HeLlO WoRlD" 를 리턴합니다.

function solution(s) { 
    let answer = '';
    let num = 0;
    for(let i = 0; i < s.length; i++){ 
        let str= s[i]; 
        if(str == " "){
            answer = answer +str; 
            num=0; 
        } else{
            answer += num %2 === 0 ? str.toUpperCase() : str.toLowerCase(); 
            num++;
        } 
    } return answer; 
}

👽자릿수 더하기

문제 보러가기

괜히 자릿수라고 알려주는 이유가 있는 것 같다
예를 들어 123이라면 일의자릿수가 될 때 까지 %10을 해주면 된다

do...while문()

let result = '';
let i = 0;

do {
  // 1. 코드 실행
  i = i + 1;
  result = result + i;
} while (i < 5); // 2. 조건 확인 ? 다시 1번으로 : 종료

console.log(result);
// "12345"

그럼 do...while을 이용해서 풀어보자

function solution(n){
    let sum = 0;
    do {
      // 123 % 10 = 3 -> 12 % 10 = 2 -> 1 % 10 = 1
        sum += n % 10;
      // 변형된 n값 다시 할당 
        n = Math.floor(n/10);
    } while(n > 0);
    return sum;
}

쉬운 단계 문제이지만 메소드를 찾아보고 공부하면서 푸니까 10시간도 모자라다.

profile
🌿💻💪🧠👍✨🎉

0개의 댓글