ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 부족한 금액 계산하기
    너의말이보여네약점algorithm 2022. 4. 6. 11:06

    풀이

    function solution(price, money, count) {
        const totalCost = (price+price*count)*count/2
        const calculatedValue = money-totalCost
        return money-totalCost > 0 ? 0 : Math.abs(money-totalCost) 
    }

    빨리 풀긴 했는데 뭔가 아쉽다 ㅠㅠ왜냐면 시그마 공식 n(n+1)/2을 사용했으면 조금 더 깔끔하지 않았을까? 싶기도 하고

    일단 변수명이 너무 구리다 다른사람들이 알아볼 수 있을까 싶기도 하고...

    목요일에 피드백을 받아보아야겠다 스터디 유잼~

     


    생각할 여지가 생겨서 좋았던 풀이

    function solution(price, money, count) {
        var answer = 0;
        let total =0;
    
        for(let j = 1; j<=count; j++){
            total = total + (price *j);
        }
        //이 부분의 Math.sign
        if (Math.sign(total-money)<=0){
            answer = 0
        } else {
            answer = (total - money)
        }
    
        return answer 
    
    }

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign

     

    Math.sign() - JavaScript | MDN

    The Math.sign() function returns either a positive or negative +/- 1, indicating the sign of a number passed into the argument. If the number passed into Math.sign() is 0, it will return a +/- 0. Note that if the number is positive, an explicit (+) will no

    developer.mozilla.org

    금곰님의 풀이중에서 Math.sign을 쓰신 것이 보였는데 if문의 true/false를 숫자로 표현한게 명시적으로 드러나는 메서드여서 하나 또 배웠다고 생각했다~ 물론 Math.sign이 없어도 돌아가긴 하겠지만 math.sign으로 감싸준 아이디어가 특이하달까.. 역시 내가 생각하지 못한 부분을 또 배워가서 좋았다.

    그리고 truthy/falsy한 값에 대한 개념, OR연산에 대해서 지난번에 정리를 안한 부분이 있는데 그것도 정리해야겠다는 생각을 했다~

    The Math.sign() function returns either a positive or negative +/- 1, indicating the sign of a number passed into the argument. If the number passed into Math.sign() is 0, it will return a +/- 0. Note that if the number is positive, an explicit (+) will not be returned.

    MDN Math.sign()의 설명과 용례

    console.log(Math.sign(3));
    // expected output: 1
    
    console.log(Math.sign(-3));
    // expected output: -1
    
    console.log(Math.sign(0));
    // expected output: 0
    
    console.log(Math.sign('-3'));
    // expected output: -1

    보니까 양수면 1을 반환하고, 음수면 -1, 0이면 0을 반환하는데 true이면 1, false이면 2인데 이걸 if문이 음수일 때(=참)로 구현한 아이디어가 재미있었다. 이렇게 연결시키는 게 좋았달까!

     

     


    디스캣님 풀이

    function solution(price, money, count) {
        return (
    			Math.abs(
    				Math.min(
    					0,
    					(money - ((count)*(count+1)/2)*price)
    				)
    			)
    		)
    }
    function solution(p, m, c) {
        return Math.abs(Math.min(0,(m-((c)*(c+1)/2)*p)))
    }

    파이프라인 연산자를 사용한 풀이(이걸 위한 빌드업)

    //F#
    let solution price money count = 
    		money - ((count)*(count+1)/2) * price
    		|> min 0 //number->number->number
    		|> abs   //number->number
    
    //파이프만 있었더라면!!~~
    //커링(하스켈함수 partial applied 함수
    
    커링된 함수 (a) => Math.min(a, 0);
    
    Maht.abs(Math.min(-30, 0))
    -30
    	|> Math.min(0, %)
    	|> Math.abs(%)

    F#은 처음보는 친구인데 F#은 C# 프레임워크 닷넷에서 보이는 ocaml이라는 언어의 사촌 격인 언어라고 한다 모든 함수형 언어들은 oCaml의 파생이라고 할 만큼 시초 격인 언어라고 한다~

     

    무튼 저렇게 파이프라인 연산자 | 를 사용하면 매개변수의 이름 따위 신경쓰지 않고 그냥 함수의 output을 넘겨주기만 하면 된다

    저런 함수들을 커링함수라고 하는데 partial applied 함수라고 한단다...(근데 아직 정확한 정보도 아니고 이해도 제대로못했음)

    Ref

    https://www.geeksforgeeks.org/scala-partially-applied-functions/

     

    Scala | Partially Applied functions - GeeksforGeeks

    A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

    www.geeksforgeeks.org


    탐토님 함수형교수님2 풀이

    function solution(price, money, count) {
        const fee = price * count * (1+ count) / 2;
        const remain = money - fee;
        return remain < 0 ? -remain : 0;
    }

    abs()를 써주지 않고 remain에 -를 붙여주어서 왜 저렇게 했냐고 질문했더니 어차피 절대 음수밖에 안나오고 연산자를 써주는게 더 간결해보여서 저렇게 썼다고 하셨다~

    탐토님 풀이2 (몽키 패치)

    Number.prototype.min = function(b){ return Math.min(this, b) }
    Number.prototype.abs = function(){ return Math.abs(this) };
    //monkey patch
    function solution(price, money, count) { 
        return (money - (price * count * (1+ count) / 2))
            .min(0)
            .abs();
    }

    이렇게 자바스크립트 prototype에 대해 function을 추가할 수 있다는 것을 보여주려고 작성하신 코드이다. (처음알음)

    JS의 this에 대해서는 아직 잘 모르겠다 

     

     


    둘다 등차수열의 합공식을 이용했다는 점에서 명확했다. 내가 고민하던 부분 n(n+1)/2를 사용하는 것에 대한 해답이어서 그 부분을 볼 수 있어서 좋은 것 같다. 가우스의 등차수열의 합공식 중 유도식(처음 수 + 마지막 수)를 저렇게 다르게 나타낸 것이다. 

Designed by Tistory.