The way to To find the Center Component in C

The problem

You wish to have to create a serve as that after supplied with a triplet, returns the index of the numerical component that lies between the opposite two parts.

The enter to the serve as shall be an array of 3 distinct numbers (Haskell: a tuple).

For instance:

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

2 is the quantity that matches between 1 and 3 and the index of 2 within the enter array is __.

Every other instance (simply to verify it’s transparent):

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

10 is the quantity that matches between 5 and 14 and the index of 10 within the enter array is 1.

The answer in C

Possibility 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;
    }
  }
  go back 3 - maxi - mini;
}

Possibility 2:

int gimme (const int triplet[3]) 

Possibility 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;}
    go back _[0]==b?0:_[1]==b?1:2;
}

Take a look at instances to validate our resolution

#come with <criterion/criterion.h>

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

Take a look at(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);
}

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: