ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자바스크립트 문법 12 - 함수(function)의 기본 해답
    프론트엔드/Javascript 연습과제 해답 2022. 1. 26. 12:43
    728x90

     

    * 연습과제 1

    해답 1

    function findMaxValue(...args){
        let max = -Infinity
        for(let arg of args){
            if(max < parseFloat(arg)){ // 숫자가 아닌 값들은 NaN 이며 NaN 과 비교하면 모두 false 이므로 조건문을 건너뛴다
                max = parseFloat(arg)
            }
        }
        return max
    }
    
    // 테스트 케이스 
    console.log(findMaxValue(-3, 7, -345, 41, 9, 137, 69))
    console.log(findMaxValue(-31, 8, null, -26, false, 92, {}, 284, 923, [], "2045.8", 'zip', 54, "1024"))

    해답 2

    function findMaxValue(...args){
        let max = -Infinity
        for(let arg of args){
            if(arg == parseFloat(arg)){ // 값이 서로 같고 자료형만 다른 경우 == 는 true 를 반환함
                // console.log(parseFloat(arg)) // 숫자만 걸러짐(문자로 된 숫자 포함)
    
                if(max < parseFloat(arg)){ // 숫자가 아닌 값들은 NaN 이며 NaN 과 비교하면 모두 false 이므로 조건문을 건너뛴다
                    max = parseFloat(arg)
                }
            }
        }
        return max
    }
    
    // 테스트 케이스 
    console.log(findMaxValue(-3, 7, -345, 41, 9, 137, 69))
    console.log(findMaxValue(-31, 8, null, -26, false, 92, {}, 284, 923, [], "2045.8", 'zip', 54, "1024"))

    해답 3

    function findMaxValue(...args){
        let max = -Infinity
        for(let arg of args){
            if(typeof arg === 'number' || typeof arg === 'string'){
                // console.log(parseFloat(arg))
                if(!isNaN(parseFloat(arg))){
                    if(max < parseFloat(arg)) max = parseFloat(arg)
                }
            }
        }
        return max
    }
    
    // 테스트 케이스 
    console.log(findMaxValue(-3, 7, -345, 41, 9, 137, 69))
    console.log(findMaxValue(-31, 8, null, -26, false, 92, {}, 284, 923, [], "2045.8", 'zip', 54, "1024"))

     

    * 연습과제 2

    function Movie(title, author, release){
        this.title = title
        this.author = author
        this.release = release
    
        this.printMovieInfo = () => {
            const getInfo = () => {
                return `${this.title}-${this.author}는 ${this.release}에 발매되었다.`
            }
            console.log(getInfo()) 
        }
    }
    
    const movie = new Movie("해리포터", "조앤K롤링", "2003 년 3월 23일")
    movie.printMovieInfo()

     

    * 연습과제 3

    function getDistance(p1, p2 = {x: 0 , y: 0}){
        return Math.sqrt( (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y) )
     }
     
     // 테스트 케이스
     console.log(getDistance({x: 3, y: 2}, {x: 8, y: 14}))
     console.log(getDistance({x: 3, y: 4}))

     

    * 연습과제 4

    function countDuplication(keyword, ...words){
        let cnt = 0
        words.forEach(word => {
            if(word === keyword) cnt++
        })
        return cnt
    }
    
    console.log(countDuplication('cat', 'apple', 'cat', 'tiger', 'cat', 'water', 'computer', 'cat', 'lion', 'pear', 'cat')) // 4

     

    * 연습과제 5

    function add(...args){
        console.log(args)
        
        let sum  = 0
        for(let arg of args){
            sum += !isNaN(parseFloat(arg)) ? parseFloat(arg) : 0  // isNaN 함수는 주어진 값이 숫자인지 판별한다
        }
        return sum
    }
    
    console.log(add(3, null, 19, false, '9', [], 7, {}, '', 34, 'earth', '3.9')) // 75.9

     

    * 연습과제 6

    function divider(denominator, ...args){
        // console.log(args)
    
        if(denominator === 0) return args // 데이터 유효성 검증
    
        return args.map(arg => arg / denominator)
    }
    
    console.log(divider(2, 39, 4, 7, 28, 62, 28))
    console.log(divider(0, 39, 4, 7, 28, 62, 28))

     

    * 연습과제 7

    const numbers = [121, 23, 345, 43, 59]
    
    function pickIndex(len){
        return Math.floor(Math.random() * len)
    }
    function shuffle(arr){
        // 구현하기
        
        let temp = null
        
        for(let i in arr){
            pIndex = pickIndex(arr.length)
            
            temp = arr[pIndex]
            arr[pIndex] = arr[i]
            arr[i] = temp
        }
        return arr
    }
    
    console.log(shuffle(numbers))

     map 은 셔플한 값을 계속 새로운 배열에 추가한다. 예를 들어서 이전에 랜덤한 값으로 4를 뽑았으면 해당 값이 새로운 배열에 추가된다. 그 다음에 또 랜덤한 값으로 4를 뽑으면 4가 아래와 같이 또 새로운 배열에 추가된다. 이때 셔플한 결과는 중복이 발생된다. 

    const numbers = [121, 23, 345, 43, 59]
    const pickedIndexes = []
    
    function pickIndex(len){
        return Math.floor(Math.random() * len)
    }
    function shuffle(arr){
        function changeNumber(number, index){
            
            let randomIndex = pickIndex(arr.length)
            console.log(arr[randomIndex])  // 뽑은 인덱스 값과 상관없이 이전과 같은 값을 뽑은 경우 새로운 배열에 담게 되면 중복이 발생함
    
            let temp = null
    
            temp = number
            number = arr[randomIndex]
            arr[randomIndex] = temp
    
            return number
        }
        return arr.map(changeNumber)
    }
    
    console.log(shuffle(numbers))

    그래서 이러한 문제를 해결하려면 이전에 뽑았던 모든 랜덤값들을 배열에 저장해뒀다가 현재 뽑은 랜덤값이 이전에 뽑은 모든 랜덤값과 중복이 되는지 체크를 해주고 중복되면 다시 뽑고 아니면 셔플을 진행하면 된다. 

    const numbers = [121, 23, 345, 43, 59]
    const pickedRandomValues = []
    
    function pickIndex(len){
        return Math.floor(Math.random() * len)
    }
    function shuffle(arr){
        function changeNumber(number){
            let randomIndex = pickIndex(arr.length)
            while(pickedRandomValues.includes(arr[randomIndex])){
                randomIndex = pickIndex(arr.length)
            }
            
            pickedRandomValues.push(arr[randomIndex])
    
            let temp = null
    
            temp = number
            number = arr[randomIndex]
            arr[randomIndex] = temp
    
            return number
        }
        return arr.map(changeNumber)
    }
    
    console.log(shuffle(numbers))
     
     
    728x90
Designed by Tistory.