Software Engineering

How to Find the Middle Element in C


The challenge

You need to create a function that when provided with a triplet, returns the index of the numerical element that lies between the other two elements.

The input to the function will be an array of three distinct numbers (Haskell: a tuple).

For example:

gimme([2, 3, 1]) => 0

2 is the number that fits between 1 and 3 and the index of 2 in the input array is __.

Another example (just to make sure it is clear):

gimme([5, 10, 14]) => 1

10 is the number that fits between 5 and 14 and the index of 10 in the input array is 1.

The solution in C

Option 1:

int gimme (const int triplet[3]) {
  int maxi = 0;
  int mini = 0;
  for(int i = 1; i < 3; i++){
    if(triplet[i] < triplet[mini]){
      mini = i;
    } else if(triplet[i] > triplet[maxi]){
      maxi = i;
    }
  }
  return 3 - maxi - mini;
}

Option 2:

int gimme (const int triplet[3]) {
  int a = triplet[0];
  int b = triplet[1];
  int c = triplet[2];
  return a > b && a < c || a > c && a < b ? 0 : b > a && b < c || b > c && b < a ? 1 : 2;
}

Option 3:

int gimme(const int _[3]) {
    int a=_[0],b=_[1],c=_[2],t;
    if(a>b){t=a;a=b;b=t;}
    if(b>c){t=b;b=c;c=t;}
    if(a>b){t=a;a=b;b=t;}
    return _[0]==b?0:_[1]==b?1:2;
}

Test cases to validate our solution

#include <criterion/criterion.h>

extern void do_test (const int triplet[3], int expected);

Test(tests_suite, sample_tests)
{
	do_test((int[3]){2, 1, 3}, 0);
	do_test((int[3]){2, 3, 1}, 0);
	do_test((int[3]){1, 2, 3}, 1);
	do_test((int[3]){3, 2, 1}, 1);
	do_test((int[3]){1, 3, 2}, 2);
	do_test((int[3]){3, 1, 2}, 2);
}