Juni_Dev_log

(200207_TIL) 'Word Count' 본문

CodingTest/Exercism

(200207_TIL) 'Word Count'

Juni_K 2021. 2. 7. 13:32

▶ Word Count

Word Count

📌 Problem

Introduction

Given a phrase, count the occurrences of each word in that phrase.

For the purposes of this exercise you can expect that a word will always be one of:

  1. A number composed of one or more ASCII digits (ie "0" or "1234") OR
  2. A simple word composed of one or more ASCII letters (ie "a" or "they") OR
  3. A contraction of two simple words joined by a single apostrophe (ie "it's" or "they're")

숫자는 ASCII 숫자의 하나 또는 다수로 이루어져있다.

간단한 단어는 하나 또는 다수의 ASCII 문자로 이루어져있다.

두 단어의 단축은 하나의 아포스트로피에 의해 결합되어 있다.

 

When counting words you can assume the following rules:

  1. The count is case insensitive (ie "You", "you", and "YOU" are 3 uses of the same word)
  2. The count is unordered; the tests will ignore how words and counts are ordered
  3. Other than the apostrophe in a contraction all forms of punctuation are ignored
  4. The words can be separated by any form of whitespace (ie "\t", "\n", " ")

You, you, YOU는 3개로 이루어진 같은 단어이다. (세는 것은 둔감한 경우이다.)

정렬되지 않았으며, 이 검사는 어떻게 단어와 수가 정렬되는지를 무시할 것이다.

구두점 찍기의 형태로 축약된 아포스트로리보다다른 형태의 찍기는 무시된다.

단어는 공백의 형태에 의해 구분된다.

 

For example, for the phrase 

"That's the password: 'PASSWORD 123'!", cried the Special Agent.\nSo I fled. 

the count would be:

 

that's: 1
the: 2
password: 2
123: 1
cried: 1
special: 1
agent: 1
so: 1
i: 1
fled: 1

예제)

countWords() 함수 안에 'word' 가 들어간다면, 해당 함수를 통해서 나오는 값은 {word:1} 이 되어야 함.

 

Tip)

- 공백 / , / \n 으로 구분해서 배열 형태로 주어진 문자열을 나눠야한다.

- 주어진 문자열을 배열 형태로 쪼갠 후, for문을 통해서 반복을 진행하면서 새롭게 만든 객체에 key : value 값으로 삽입한다.

- 만약, 이미 들어있는 key 값이 있다면 value ++ 해준다.

- 객체에 들어가는 모든 문자들은 소문자로 진행한다.

- 주어진 문자열에 문자열이 아닌 것은 다 제외한다.

 

💯 Solution

const regex = /(\d+)|(\b[\w']+\b)/g;

export const countWords = (stringWords) => {
    // 반환할 객체 생성
    var expectedObject = {};
    // 소문자로 변형
    var lowerPhrase = stringWords.toLowerCase();
    // regex와 매칭시키는 stringWords 만들기
    var wordsArray = lowerPhrase.match(regex);

    wordsArray.forEach(function(word){
        // 해당 단어가 객체에 있는 단어라면
        if(expectedObject[word]){
            expectedObject[word] += 1;
        }
        else{
            expectedObject[word] = 1;
        }
    })
    return expectedObject;
}

- 정규표현식 regex를 만든다. (정규표현식을 통해서, 해당 문자열의 ASCII 문자가 아닌 경우 필터링 된다.)

- expectedObject 객체를 만든다.

- 문자열을 소문자로 바꾼다. (toLowerCase())

- 소문자로 바꾼 문자열을 match 를 통해서 정규표현식을 사용한다.

- forEach문을 통해서 배열을 반복하는데, 만약 expectedObjet 객체 안에 해당 word 로 되어있는 키가 있다면, 키에 해당하는 값에 1을 더하고, 키가 없다면 그 키에 1을 배정한다.

 

 

📚 참고

yuddomack.tistory.com/entry/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-Array-forEach

 

자바스크립트 Array forEach

이번 글에서는 자바스크립트 Array(배열) 객체의 메서드인 forEach에 대해 작성하겠습니다. forEach는 for문과 마찬가지로 반복적인 기능을 수행할 때 사용합니다. 하지만 for문처럼 index와 조건식, inc

yuddomack.tistory.com

developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/match

 

String.prototype.match() - JavaScript | MDN

match() 메서드는 문자열이 정규식과 매치되는 부분을 검색합니다. regexp 정규식 개체입니다.  RegExp가 아닌 객체 obj가 전달되면, new RegExp(obj)를 사용하여 암묵적으로 RegExp로 변환됩니다. 매개변수

developer.mozilla.org

www.youtube.com/watch?v=5pN3_yGmbrA

developer.mozilla.org/ko/docs/Web/JavaScript/Guide/%EC%A0%95%EA%B7%9C%EC%8B%9D

 

정규 표현식 - JavaScript | MDN

정규 표현식은 문자열에 나타는 특정 문자 조합과 대응시키기 위해 사용되는 패턴입니다. 자바스크립트에서, 정규 표현식 또한 객체입니다.  이 패턴들은 RegExp의 exec 메소드와 test 메소드  ,

developer.mozilla.org

 

✏️ 공부할 것

- 정규 표현식 공부하기

'CodingTest > Exercism' 카테고리의 다른 글

(200209_TIL) "Perfect Numbers"  (0) 2021.02.09
(200208_TIL) "Difference Of Squares"  (0) 2021.02.08
(200205_TIL) 'Raindrops'  (0) 2021.02.05
(200204_TIL) 'Hamming'  (0) 2021.02.04
(200203_TIL) 'ETL'  (0) 2021.02.03
Comments