카타 8급 Count of positives / sum of negatives

1 C[ | ]

#include <stddef.h>
void count_positives_sum_negatives(
  int *values, size_t count, int *positivesCount, int *negativesSum) {
  for(int i = 0; i < count; i ++) {
    if(values[i] > 0) *positivesCount += 1;
    else  *negativesSum += values[i];
  }
}
#include <stddef.h>
void count_positives_sum_negatives(
  int *values, size_t count, int *positivesCount, int *negativesSum) {
  int posCount = 0; 
  int negSum = 0;
  for(int i=0; i<count; i++) {
    if( values[i]>0 ) posCount++;
    else negSum += values[i];
  }
  *positivesCount = posCount;
  *negativesSum = negSum;
}

2 C++[ | ]

#include <vector>

std::vector<int> countPositivesSumNegatives(std::vector<int> input)
{
    if(input.empty()) return {};
    int posCnt=0, negSum=0;
    for(int x: input)
      x>0 ? posCnt++ : negSum+=x;
    return {posCnt, negSum};
}
#include <vector>

std::vector<int> countPositivesSumNegatives(std::vector<int> input)
{
    std::vector<int> res = {};
    if(input.empty()) return res;
    int posCnt=0, negSum=0;
    for(int num: input) {
      if(num>0) posCnt++;
      else negSum += num;
    }
    res.push_back(posCnt);
    res.push_back(negSum);
    return res;
}

3 Kotlin[ | ]

fun countPositivesSumNegatives(input : Array<Int>?) : Array<Int> {
    if( input == null || input.size == 0 ) return arrayOf<Int>()
    var count: Int = 0
    var sum: Int = 0
    input.forEach {
        if( it > 0 ) count++
        else sum += it
    }
    return arrayOf(count, sum)
}
fun countPositivesSumNegatives(input : Array<Int>?) : Array<Int> {
    if (input == null || input.isEmpty()) return emptyArray()
    val (positive, negative) = input.partition { it > 0 }
    return arrayOf(positive.count(), negative.sum())
}
fun countPositivesSumNegatives(input : Array<Int>?) : Array<Int> {
    if (input == null || input.isEmpty()) return arrayOf()
    return arrayOf(input.filter{ it > 0 }.count(), input.filter{ it < 0 }.sum())
}
fun countPositivesSumNegatives(input : Array<Int>?) = when {
  input.isNullOrEmpty() -> emptyArray<Int>()
  else -> arrayOf(input.filter{ it > 0 }.count(), input.filter{ it < 0 }.sum())
}

4 PHP[ | ]

function countPositivesSumNegatives($input) {
  if (empty($input)) return [];
  $posCount = $negSum = 0;
  foreach($input as $value) {
    if ($value > 0) $posCount++;
    else $negSum += $value;
  }
  return [$posCount, $negSum];
}
function countPositivesSumNegatives($input) {
  $count = count($input);
  if( $count < 1 ) return [];
  $posCount = 0;
  $negSum = 0;
  for($i=0; $i<$count; $i++) {
    if( $input[$i] > 0 ) $posCount++;
    else $negSum += $input[$i];
  }
  return [$posCount, $negSum];
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}