pangfengliu / programmingtasks

programming tasks from my courses
68 stars 17 forks source link

Pairing #318

Open morris821028 opened 8 years ago

morris821028 commented 8 years ago

Problem Description

You have $n$ integers and you want to pair them into $n/2$ pairs. You first sort the numbers, then pair the largest number with the smallest number, then the second largest number with the second smallest number, and so on. Repeat this process then you will get $n/2$ pairs of numbers, then you compute the sums of every pair.

void pairPrint(int numbers[], int n);

For example, if numbers are ${1, 3, 5, 2}$. The output should be as follows if DEC is specified.

6 = numbers[2] + numbers[0]
5 = numbers[3] + numbers[1]

For example, if numbers are ${1, 3, 4, 2}$. The output should be as follows if INC is specified. Note that since both ${1, 4}$ and ${2, 3}$ have sum 5, the pair ${1, 4}$ is printed first because the index of 1 (i.e., 0) is smaller than the index of 3 (i.e., 2).

5 = numbers[0] + numbers[2]
5 = numbers[1] + numbers[3]

Subtasks

#include "pair.h"
#include <stdio.h>
#include <stdlib.h>

int main() {
    int n;
    while (scanf("%d", &n) == 1) {
        int *A = (int *) malloc(sizeof(int)*n);
        for (int i = 0; i < n; i++)
            scanf("%d", &A[i]);
        pairPrint(A, n);
        free(A);
    }
    return 0;
}

pair.h

void pairPrint(int numbers[], int n);

pair.c

#include <stdio.h>

void pairPrint(int numbers[], int n){
    // Fill your code here.
}

Sample Input

4
1 3 5 2

Sample Output (if a #define INC is defined)

5 = numbers[1] + numbers[3]
6 = numbers[0] + numbers[2]

Sample Output (if a #define DEC is defined)

6 = numbers[2] + numbers[0]
5 = numbers[3] + numbers[1]