본문 바로가기
코딩 테스트/알고리즘

알고리즘 10번 - js, c++

by GREEN나무 2024. 11. 12.
728x90

JS

문제

정수 배열 numbers가 매개변수로 주어집니다. numbers의 원소의 평균값을 return하도록 solution 함수를 완성해주세요.

제한사항
0 ≤ numbers의 원소 ≤ 1,000
1 ≤ numbers의 길이 ≤ 100
정답의 소수 부분이 .0 또는 .5인 경우만 입력으로 주어집니다.

 


계획

for of 반복문 사용


function solution(numbers) {
    let sum = 0;  
    for (let num of numbers) {
        sum += num;
    }
    return sum / numbers.length;
}

코드 간략화하기

function solution(numbers) {
    return numbers.reduce((a, b) => a + b) / numbers.length;
}

reduce((a, b) => a + b)를 사용해 numbers 배열의 모든 원소 합을 구합니다.


출처 

for in, for of 반복 : https://jsdev.kr/t/for-in-vs-for-of/2938


 

◆ C++

참고, 풀이

c++에서 배열의 길이 numbers.length가 아니라 numbers.size()


#include <string>
#include <vector>
#include <bits/stdc++.h>
using namespace std;

double solution(vector<int> numbers) {
    if (numbers.empty()) return 0.0;
    return accumulate(numbers.begin(), numbers.end(), 0.0) / numbers.size();
}

 

#include <vector>
#include <numeric>
#include <cmath>
using namespace std;

double solution(vector<int> numbers) {
    if (numbers.empty()) return 0.0;
    double result = accumulate(numbers.begin(), numbers.end(), 0.0) / numbers.size();
    return round(result * 2) / 2; // 소수점 첫째 자리에서 반올림
}

코드 간략화하기

#include <vector>
#include <numeric>
#include <cmath>
using namespace std;

double solution(vector<int> numbers) {
    return round(accumulate(numbers.begin(), numbers.end(), 0.0) / numbers.size() * 2) / 2;
}

다른사람 답

#include <string>
#include <vector>
#include <numeric>
using namespace std;

double solution(vector<int> numbers) {
    double answer = 0;
    int sum = accumulate(begin(numbers), end(numbers), 0, plus<int>());
    answer = (double)sum / numbers.size();
    return answer;
}

출처 

https://0xffffffff.tistory.com/44

 

 

 

'코딩 테스트 > 알고리즘' 카테고리의 다른 글

알고리즘 12번 - JS, C++  (0) 2024.11.13
알고리즘 11번-JS, c++  (2) 2024.11.13
알고리즘 9번 - js, c++  (0) 2024.11.12
알고리즘 8번 - js, c++  (0) 2024.11.12
알고리즘 7번 - js, c++  (0) 2024.11.12