Skip to content

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
Code language: plaintext (plaintext)

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
Code language: plaintext (plaintext)

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 = ; int mini = ; 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; }
Code language: C++ (cpp)

Option 2:

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

Option 3:

int gimme(const int _[3]) { int a=_[],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 _[]==b?:_[1]==b?1:2; }
Code language: C++ (cpp)

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}, ); do_test((int[3]){2, 3, 1}, ); 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); }
Code language: C++ (cpp)

See also  How to Convert a String to the NATO Phonetic Alphabet in C
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x