codewars: Shortest Word

Jieun·2021년 1월 9일
0

js알고리즘

목록 보기
2/6

✅ 문제

Simple, given a string of words, return the length of the shortest word(s).

String will never be empty and you do not need to account for different data types.

해석 : 단어들로 이루어진 하나의 스트링에서 제일 짧은 단어의 길이를 리턴하라. 문장은 공백이 될 수 없고 다른 타입의 데이타는 세지 않아도 된다.


✅ 샘플 테스트

Test.describe("Example tests",_=>{
Test.assertEquals(findShort("bitcoin take over the world maybe who knows perhaps"), 3);
Test.assertEquals(findShort("turns out random test cases are easier than writing out basic ones"), 3); 
});



✅ 내가 만든 답

function findShort(s){
    let str = s.split(' ');
    let mapStr = str.map( a => a.length );
    let min = Math.min(...mapStr);
    return min;
}
  • 샘플 테스트를 보자마자 (1)스트링을 배열로 만드는 split을 떠올렸다. 띄어쓰기를 기준으로 배열을 만들어서 (2)map으로 배열의 길이를 다른 배열로 만들고 저번 코드테스트에서 썼던 배열 중에서 (3)가장 작은 수를 찾는 Math.min을 사용했다.
  • 문제를 잘못 이해하서 제일 작은 길이의 단어를 리턴하라는 줄 알고 코드를 다시 짜야하나 한 10분 동안 생각하다가 문제를 다시 읽고 뭐야! 하며 테스트를 해보니 패쓰.


✅ 다른 사람 답

const findShort = s => Math.min(...s.split(' ').map(x => x.length));
  • 한 줄 짜리 내 코드..🤐
function findShort(s) {
  return s.split(' ').reduce((min, word) => Math.min(min, word.length), Infinity);
}
  • 대략 생각의 흐름은 비슷한 거 같은데 reduce를 아무리 구글링해봐도 시원하게 이해되는 설명이 없다.


0개의 댓글

관련 채용 정보