저장을 습관화

프로그래머스 LV.0 외계어 사전 본문

코딩 테스트/프로그래머스 - 자바스크립트

프로그래머스 LV.0 외계어 사전

ctrs 2023. 10. 3. 15:32

프로그래머스 LV.0 외계어 사전

https://school.programmers.co.kr/learn/courses/30/lessons/120869

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

1. 문제 명

외계어 사전


2. 문제 설명

PROGRAMMERS-962 행성에 불시착한 우주비행사 머쓱이는 외계행성의 언어를 공부하려고 합니다. 알파벳이 담긴 배열 spell과 외계어 사전 dic이 매개변수로 주어집니다. spell에 담긴 알파벳을 한번씩만 모두 사용한 단어가 dic에 존재한다면 1, 존재하지 않는다면 2를 return하도록 solution 함수를 완성해주세요.


3. 제한 사항

  • spell과 dic의 원소는 알파벳 소문자로만 이루어져있습니다.
  • 2 ≤ spell의 크기 ≤ 10
  • spell의 원소의 길이는 1입니다.
  • 1 ≤ dic의 크기 ≤ 10
  • 1 ≤ dic의 원소의 길이 ≤ 10
  • spell의 원소를 모두 사용해 단어를 만들어야 합니다.
  • spell의 원소를 모두 사용해 만들 수 있는 단어는 dic에 두 개 이상 존재하지 않습니다.
  • dic과 spell 모두 중복된 원소를 갖지 않습니다.


4. 예시

spell dic result
["p", "o", "s"] ["sod", "eocd", "qixm", "adio", "soo"] 2
["z", "d", "x"] ["def", "dww", "dzx", "loveaw"] 1
["s", "o", "m", "d"] ["moos", "dzx", "smm", "sunmmo", "som"] 2


5. 기본 제공 코드

function solution(spell, dic) {
    var answer = 0;
    return answer;
}


6. 제출한 내 답

const solution = (spell, dic) => {
  let word = spell.sort().join("");
  for (i = 0; i < dic.length; i++) {
    if (word === dic[i].split("").sort().join("")) {
      return 1;
    }
  }
  return 2;
};
테스트 1 〉	통과 (0.09ms, 33.6MB)
테스트 2 〉	통과 (0.12ms, 33.5MB)
테스트 3 〉	통과 (0.07ms, 33.5MB)
테스트 4 〉	통과 (0.06ms, 33.4MB)
테스트 5 〉	통과 (0.08ms, 33.4MB)
테스트 6 〉	통과 (0.11ms, 33.6MB)
테스트 7 〉	통과 (0.06ms, 33.4MB)
테스트 8 〉	통과 (0.06ms, 33.4MB)
테스트 9 〉	통과 (0.08ms, 33.4MB)

 

6-2. VSC에 작성한 내용

const solution = (spell, dic) => {
  // spell에 담긴 알파벳을 한번씩만 모두 쓰인 단어가
  // dic에 존재한다면 1, 아니라면 2
  let word = spell.sort().join("");
  for (i = 0; i < dic.length; i++) {
    if (word === dic[i].split("").sort().join("")) {
      return 1;
    }
  }
  return 2;
};

// 테스트
console.log(solution(["p", "o", "s"], ["sod", "eocd", "qixm", "adio", "soo"]));
console.log(solution(["z", "d", "x"], ["def", "dww", "dzx", "loveaw"]));
console.log(
  solution(["s", "o", "m", "d"], ["moos", "dzx", "smm", "sunmmo", "som"])
);


7. 특이사항

없음


8. 다른 사람이 작성한 답

8-1. 좋아요 가장 많이 받은 풀이법

function solution(p, d) {
    return d.some(s => p.sort().toString() == [...s].sort().toString()) ? 1 : 2;
}

배열 메소드 .some

배열의 각 엘리먼트에 대해서 검사한 후, 반환 값이 하나라도 true가 있는지 확인한다

하나라도 true가 있다면 true를 반환한다.

모두 false인 경우 false를 반환한다. || (or) 연산자와 같은 조건이다

기존 배열값은 변경되지 않는다

 

문법

arr.some(function(currentValue, index, array), thisValue))

 

예시

var objArr = [{name: '철수', age: 10},{name: '영희', age: 10}, {name: '바둑이', age: 2}]

console.log(objArr.some((item)=> item.age>5)); //true
console.log(objArr.some((item)=> item.age>10)); //false (모두 탈락!)

 

 

반대로 && (and) 연산자로는 .every 메소드가 있다

배열의 각 엘리먼트에 대해서 검사한 후 모두 true라면 true를 반환한다

하나라도 false라면 false를 반환한다

기존 배열값은 변경되지 않는다.

 

문법

arr.every(function(currentValue, index, array), thisValue))

 

예시

var objArr = [{name: '철수', age: 10}, {name: '영희', age: 10}, {name: '바둑이', age: 2}]

console.log(objArr.every((item)=> item.age>5)); //false (바둑이 탈락!)
console.log(objArr.every((item)=> item.age>1)); //true

 

8-2. 가장 많이 쓰인 풀이법, filter, every

function solution(spell, dic) {
    return dic.filter(v=>spell.every(c=>v.includes(c))).length ? 1 : 2;
}