尝试获取等于特定总和的 3 个独立整数的排列.编程新手
Trying to get permutations of 3 seperate integers that equal a particular sum. New to programming
// 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::map
或std::unordered_map
轻松实现。
下面是一个简短的示例,它实现了已知sum
和wep
的情况,并计算sys
和eng
。
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
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- 如何在c++中从文本文件中逐行读取整数
- 独立读取-修改-写入顺序
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 独立于实现的浮点/整数转换
- 你能在任何独立于架构的低级语言中获得更小的整数吗?
- C++,为什么我不能使用两个默认随机引擎生成独立的随机整数样本
- C 如何将字节读取为整数enderness独立
- 尝试获取等于特定总和的 3 个独立整数的排列.编程新手