카타 8급 Sum of positive

1 C[ | ]

#include <stddef.h>
int positive_sum(const int *values, size_t count) {
  int sum = 0;
  for(int i=0; i<count; i++) {
    if(values[i]>0) sum+=values[i];
  }
  return sum;
}

2 C++[ | ]

#include <vector>
int positive_sum (const std::vector<int> arr){
  int sum = 0;
  for(int i=0; i<arr.size(); i++) {
    if(arr[i]>0) sum+=arr[i];
  }
  return sum;
}

3 Kotlin[ | ]

fun sum(numbers: IntArray): Int {
    var res = 0
    numbers.forEach {
        if( it>0 ) res+=it
    }
    return res
}
fun sum(numbers: IntArray) = numbers.filter { it > 0 }.sum()
fun sum(numbers: IntArray) = numbers.sumBy{if(it>0) it else 0}
fun sum(numbers: IntArray) = numbers.sumBy { it.coerceAtLeast(0) }
fun sum(numbers: IntArray): Int {
    var sum: Int = 0
    for (n: Int in numbers) {
        if(n > 0) sum += n
    }
    return sum
}
fun sum(numbers: IntArray) = numbers.fold(0) { acc, n -> if (n > 0) acc + n else acc }

4 PHP[ | ]

function positive_sum($arr) {
  $sum = 0;
  foreach($arr as $n) {
    if( $n > 0 ) $sum += $n;
  }
  return $sum;
}
function positive_sum($arr) {
  return array_sum(array_filter($arr, function ($v) {return $v>0;}));
}
function positive_sum($arr) {
  $sum = 0;
  foreach ($arr as $v) {
    $sum += $v>0 ? $v : 0;
  }
  return $sum;
}
function positive_sum($arr) {
  return array_reduce($arr, function($sum, $v){
    if ($v > 0) $sum += $v;
    return $sum;
  }, 0);
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}