3. 반복문 1~3

2020. 7. 4. 22:50Retrospection/Sprint

1.

n까지의 총 합: n을 매개변수로 받아 0 부터 n 까지 모든 수의 총 합을 반환하는 함수를 작성하세요.

sum(3); // => 6
sum(4); // => 10
sum(5); // => 15
function sum(n) {
    let result = 0 ;
    for(i= 0; i <= n ; i ++){
        result = result + i  //<- 이부분을 어떻게 표현해야 할지 몰라서 어려웠다.
    }
    return result ; 
}

sum 함수 안에 일단 result 를 선언하고 값을 0 으로 준다. 

for loop 를 만들고 i 라는 숫자를 만들어 n보다 작거나 같을때 라는 가정을 해준다 . 

그안에 result = result + i 를 선언하고 리턴했다. 

 

꽤 오랫동안 고민한 문제인데 풀기는 풀었다. 

단순히 문제를 푸는게 중요한게 아니고 문제를 풀어가는 과정에서 레퍼런스 보지않고 내가 결과를 도출하는게 좋은 것 같다. 

그리고 의사코드 작성하는거 .. 꼭 작성하고 풀자 앞으론. 

 

 

 

 

참고 

https://java.meritcampus.com/core-java-topics/for-loop-example-java-program-sum-of-numbers

 

for Loop Example Program In Java - Sum Of Numbers

You have exceeded the limit to read number of knowledge chapters/per day. For unlimited access to MeritCampus knowledge chapters, upgrade to premium membership. 2 years unlimited access for just Rs100/$2

java.meritcampus.com

 

 

2.

Write a function called "repeatString". 

Given a string and a number, "repeatString" returns the given string repeated the given number of times

 

let output = repeatString('code', 3); console.log(output); // --> 'codecodecode'
function repeatString(string, num) {
    return string.repeat(num);
}

위가 내가 한 방법. 

keyword : repeat string javascript .

 

참고사이트 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

 

String.prototype.repeat()

repeat() 메서드는 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환합니다.

developer.mozilla.org

 

근데 반복문 챕터라서 그런지 레퍼런스는 반복문이 나와있다. 

반복문으로 다시한번 만들어 보았다. 

검색을 통해 for loop 와 while loop 로 각각 만들어 보았다.

for loop 는 좀 더 어려웠는데 

조건을 만들때 i <= num 이라고 만들었다가 계속 테스트에 통과하지 못했다. 

알고보니 i < num 이라고 했어야 했다. 

//while loop 사용 //
function repeatString(string, num) {
    //result = ''를 선언하고 (빈문자열)
    let result = '';
    //while 조건문에 num이 0보다 클때 라는 조건을 넣는다 
    while(num > 0){
    // while loop 안에다가 result= result + string 을 선언한다
    result = result + `${string}` ;
    num--;
    }
      //while loop 밖에 return result를 한다. 
    return result ; 
  
}

이렇게 해서 통과하기는 했는데 사실 좀 이해하기가 힘들었다. 

 

// for loop 사용 //
function repeatString(string, num) {
    let result = '';
    for(i = 0 ; i < num; i++){
        result = result + string;
    }  
    return result ;
}

 

 

 

참고사이트 

 

Three ways to repeat a string in JavaScript

In this article, I’ll explain how to solve freeCodeCamp’s “Repeat a string repeat a string [https://www.freecodecamp.com/challenges/repeat-a-string-repeat-a-string]” challenge. This involves repeating a string a certain number of times. There are t

www.freecodecamp.org

 

 

//조건문 사용//
function repeatString(string, num) {
    if(num <= 0){
        return '';
    }else if ( num === 1){
        return string;
    }else if (num > 1 ){
        return string + repeatString(string, num - 1);
    }
}

위 사이트에서 나온 두번째 방법으로 한번 더 만들어본 코드가 위에 코드 

테스트는 잘 통과했다.

 

 

 

 

 

3.

Given a string input and a character, "countCharacter" returns the number of occurences of a given character in the given string.

 

 //letter count 함수를 만든다 값을 0으로 한다
 //반복문을 만들고 position = 0; position <str.length ; position++ 라는 조건문에다가 
 //만약 str 안에 position 위치의 문자가 letter와 같을때 lettercount +=1 한다. 
 //리턴 레터카운트 를 하면 완성 . 
    function countCharacter(str, letter) {
    let letterCount = 0;
    for(let position = 0; position < str.length ; position++){
        if(str.charAt(position) === letter){
            letterCount += 1;
        }
    }
    return letterCount;
}

검색을 통해 테스트에 통과하는 코딩을 해냈다. 

밑에는 레퍼런스 . 

가장 큰 차이는 str.charAt(position) 을 쓰지않고

str[position] 이런식으로 쓴것. 

저렇게 해도 문자 추출이 되는구나 . 

 

function countCharacter(str, char) {
  let counter = 0;

  for (let i = 0; i < str.length; i++) {
    if (str[i] === char) {
      counter = counter + 1;
    }
  }

  return counter;
}

 

 

 

 

 

 

 

참고링크 

 

JavaScript function: Letter count within a string - w3resource

JavaScript exercises, practice and solution: Write a JavaScript function that accepts two arguments, a string and a letter and the function will count the number of occurrences of the specified letter within the string.

www.w3resource.com

 

 

'Retrospection > Sprint' 카테고리의 다른 글

윈도우 사이즈  (0) 2020.07.06
3. 배열의 반복 1 , 2  (0) 2020.07.04
배열기초 /타입 1 , 배열기초 1-3  (0) 2020.07.04
2. 타입 1 ~3  (0) 2020.07.02
2. 수학 - 1~3.  (0) 2020.07.02