尝试获取等于特定总和的 3 个独立整数的排列.编程新手

Trying to get permutations of 3 seperate integers that equal a particular sum. New to programming

本文关键字:整数 独立 排列 新手 编程 获取 于特定 和的      更新时间:2023-10-16
// This program gives the possible combination of power
// distributor settings after giving it one of the variables.
// EG: sys=0>>> will return one option of eng=4 wep=8 for macro creations.
//
#include <iostream>
#include <algorithm>
using namespace std;
    int sys[9] = {0,1,2,3,4,5,6,7,8};
    int eng[9] = {0,1,2,3,4,5,6,7,8};
    int wep[9] = {0,1,2,3,4,5,6,7,8};
class power
{
    public:
        char sys;
        char eng;
        char wep;
};

我试图完成的是从每个不同的数组中获取一个值,并找到所有等于 12 的排列。例如: sys[3]+eng[5]+wep[7]=12.我想通过能够输入 1 个已知值来做到这一点,例如 sys[3],并让它告诉我其他两个部分的其他可能值,但不知道从哪里开始,我遇到的所有排列代码字符串我无法根据我的特定需求进行定制,并且遇到了障碍, 这只是一件有趣的事情,但真的很想弄清楚。

我的橡皮鸭说使用 3 个嵌套循环。每个循环遍历其中一个数组。在最里面的循环中,将三个值相加并进行比较 12。

根据对同一数据类型进行计算的次数,可能会有更好的解决方案。

另一种不那么暴力的方法是为两个变量的所有组合生成表,对其进行排序和保存,以便可以通过二进制搜索完成计算,然后将每次调用的复杂度从 O(mn) 降低到 O(log(mn))。

这可以使用std::mapstd::unordered_map轻松实现。

下面是一个简短的示例,它实现了已知sumwep的情况,并计算syseng

Table类可以重用于其他两种情况。

#include <iostream>
using namespace std;
// This program gives the possible combination of power
// distributor settings after giving it one of the variables.
// EG: sys=0>>> will return one option of eng=4 wep=8 for macro creations.
//
#include <iostream>
#include <algorithm>
#include <map>
#include <utility>
using namespace std;
    int sys[9] = {0,1,2,3,4,5,6,7,8};
    int eng[9] = {0,1,2,3,4,5,6,7,8};
    int wep[9] = {0,1,2,3,4,5,6,7,8};
class Table
{
public:
    Table(int *a, int *b, size_t size)
    {
        for(size_t i=0;i<size;i++){
            for(size_t j=0;j<size;j++){
                table[a[i]+b[j]] = std::pair<int, int>(a[i], b[j]);
            }
        }
    }
    bool find(const int sum, const int other,
          int *first, int *second)
    {
        bool ret;
        std::pair<int, int> lookedUp = table[sum-other];
        ret = lookedUp.first||lookedUp.second;
        if(ret){
            *first = lookedUp.first;
            *second = lookedUp.second;
        }else{
            table.erase(sum-other);
        }
        return ret;
    }
private:
    std::map<int, std::pair<int, int> > table;
};

int main() {
    Table t1(sys, eng, 9);
    int sys, eng;
    if(t1.find(12, 8, &sys, &eng)){
        cout << "for sum=12, wep=8, found " <<"sys=" <<sys << " "<< "eng=" << eng;
    }
    return 0;
} 

这种方法的问题在于它无法处理成员可以为 0 的数据集,因为这样std::map无法区分它是失败的查找还是返回值为 (0,0) 的成功查找。

如果您只使用未签名的数据集,则可以通过向数据集添加一个常量来解决此问题,以便有效数据永远不会为 0。

演示: https://ideone.com/JwP15r