【问题标题】:Algorithm that can sum 4 digits in pairs so that their sum difference would be as close as possible可以将 4 位数字成对相加的算法,使它们的和差尽可能接近
【发布时间】:2019-09-22 18:29:52
【问题描述】:

我在C++ 有作业,要求我输入4 自然数并将它们配对,以使它们的总和之间的差异尽可能小。

例子:

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

我已经使用 if 语句编写了一些代码,但是要检查每个组合需要编写大量代码,所以我想知道是否有更短的方法来完成这项任务

#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;
    }
}

【问题讨论】:

  • 你的代码是什么样的?还有,0 是从哪里来的?
  • @PhoenixBlue 我添加了代码。它不完整,但我希望你能明白。 0 来自将这 4 个数字成对相加:4+1 = 5 和 3 + 2 = 5,它们的差为 0

标签: c++ algorithm if-statement simplify


【解决方案1】:

如果只是4自然数,请执行以下操作。

  • 首先,创建一个普通数组(即int[4] 或)std::array&lt;int, 4&gt; 并获取用户输入。
  • 对数组进行升序(或降序)排序。
  • (1st + 4th) 元素和(2th + 3th 的区别) 元素 给出结果。

这里是示例代码

#include <iostream>
#include <array>     // std::array
#include <algorithm> // std::sort

int main()
{
    std::array<int, 4> arr;
    for (int& element : arr) std::cin >> element;
    std::sort(arr.begin(), arr.end());
    int result = (arr[0] + arr[3]) - (arr[1] + arr[2]);
    std::cout << "The smallest difference is: " << result << "\n";
}

(See live online)

【讨论】:

  • 为什么是这个答案?
  • @0x499602D2 我认为这是不言自明的。嗯..老实说,除了上面给出的操作示例之外,我不知道如何解释。我发现这种情况适用于 4 个数字的数组。
  • 是的,我发现这也是答案,但我不知道如何证明。
  • 可能有 6 种情况,其中一种只需表明其中 5 种不是最佳的。
  • @NeilEdelman 但是如何证明这始终是答案。
【解决方案2】:

为了证明排序后的版本|(a + d) - (b + c)|,其中a ≤ b ≤ c ≤ d 始终有效:(1) 显然cd 永远不会配对,因为这会使一侧的总和最大化而另一侧的总和最小化,从而导致最大可能的差异。现在我们知道c 位于一侧,d 位于另一侧,显然我们希望添加到较大的一侧(相同或)少于我们将添加到较小的一侧。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多