dimanche 22 septembre 2019

Algorithm that can sum 4 digits in pairs so that their sum difference would be as close as possible

I have homework in C++ that requires me to enter 4 natural numbers and pair them so that the difference between their sum would be as low as possible.

Example:

I have entered 4 numbers: 4; 3; 2; 1;
The smallest between the numbers would be 0 --> 4 + 1 and 3 + 2

I have written some code using if statements, but to check every combination takes a lot of code to write, so I was wondering if there is a shorter way to do this task

#include <iostream>
using namespace std;

int main()
{
    int a, b, c, d;
    int x, y, z;

    cout << "Insert 1st number" << endl;
    cin >> a;
    cout << "Insert 2nd number" << endl;
    cin >> b;
    cout << "Insert 3rd number" << endl;
    cin >> c;
    cout << "Insert 4th number" << endl;
    cin >> d;

    if ((a > b) && (b > c) && (c > d))
    {
        x = a + d;
        y = b + c;
        z = x - y;

        cout << "The smallest differnce is: " << z << endl;
        cout << endl;
    }
    else if ((a > b) && (b > c) && (c < d))
    {
        x = a + c;
        y = b + d;
        z = x - y;
        cout << "The smallest differnce is: " << z << endl;
        cout << endl;
    }
    else if ((a > b) && (b < c) && (c > d))
    {
        x = a + b;
        y = d + c;
        z = x - y;
        cout << "The smallest differnce is: " << z << endl;
        cout << endl;
    }
}

Aucun commentaire:

Enregistrer un commentaire