Algorithm 26 - Sum without highest and lowest number

Q.

Description:
Sum all the numbers of the array (in F# and Haskell you get a list) except the highest and the lowest element (the value, not the index!).
(The highest/lowest element is respectively only one element at each edge, even if there are more than one with the same value!)

Example:

{ 6, 2, 1, 8, 10 } => 16
{ 1, 1, 11, 2, 3 } => 6

If array is empty, null or None, or if only 1 Element exists, return 0.
Note:In C++ instead null an empty vector is used. In C there is no null. ;-)

-- There's no null in Haskell, therefore Maybe [Int] is used. Nothing represents null.
Have fun coding it and please don't forget to vote and rank this kata! :-)

I have created other katas. Have a look if you like coding and challenges.

A)

int sum(int* numbers, int numbersCount)
{
  int mid_sum = 0;
  int min_idx = 0;
  int max_idx = 0;
  for (int i = 1; i < numbersCount; i++)
  {
    if (numbers[min_idx] > numbers[i])
      min_idx = i;
  }
  for (int i = 1; i < numbersCount; i++)
  {
    if (numbers[max_idx] < numbers[i])
      max_idx = i;
  }
  for (int i = 0; i < numbersCount; i++)
  {
    if (i != min_idx & i != max_idx)
      mid_sum += numbers[i];
  }  
  return mid_sum;
}

another solution
남들은 for 문 하나로 모든 원소 sum 하면서 max랑 min 찾아내고 나중에 max, min을 sum에서 뻄.

좋은 웹페이지 즐겨찾기