2016-08-18 75 views
-2
#include <iostream> 

using namespace std; 

int main() 
{ 
    cout << "starting program" << endl; 
    for (int a=1; a<10; a++) 
    { 
     for (int b=1; b<10; b++) 
     { 
     for (int c=1; c<10; c++) 
     { 
     for (int d=1; d<10; d++) 
     { 
     for (int e=1; e<10; e++) 
     { 
     for (int f=1; f<10; f++) 
     { 
     for (int g=1; g<10; g++) 
     { 
     for (int h=1; h<10; h++) 
     { 
     for (int i=1; i<10; i++) 
     if (a+(13 * b/c) +d +(12 * e)- f - 11 + (g * h/i) - 10 == 66) 
     { 
      cout << a << b << c << d << e << f << g << h << i << endl ; 
     } 
    } 
    } 
    } 
    } 
    } 
    } 
    } 
    } 
    return 0; 
} 

因此,我找到了代码1和9之间的所有可能组合,以查看哪一个可以解决方程,正如您所看到的,我有9个变量。检查一个组变量在if语句条件下是否彼此相等

这个方程式可以用许多不同的组合来解决,但是我的目标是让变量不相等。当然,我可以通过写入if声明条件中的每一个条件来解决这个问题,但这将会导致81条件,这是很多和愚蠢的。有没有办法以更聪明的方式来解决这个问题?顺便说一下,我是初学者,所以如果你有任何先进的方法提供,请简要解释一下。

+0

如果你检查变量是否能解出方程,为什么不把它们填入方程中,并检查结果是否是你想要的? – rubenvb

+0

这个问题可以通过回溯来轻松解决。我的建议是等到你到达那个课程或者自己去学习回溯。除此之外,你现在可以做的事情不多。 – bolov

+1

btw。我喜欢你,因为你缩进了第一个2'',然后你就像“啊......这个“ – bolov

回答

2

正如@n.m所述。在评论中,因为所有的变量必须是不同的,你正在寻找排列范围的1 1到9这是因为C++已经为您提供了std::next_permutation将产生排列为您带来:

// Array for your variables, vars[0] is a, vars[1] is b, and so on... 
std::array<int, 9> vars; 

// Fill the array from number from 1 to 9 (so a = 1, b = 2, and so on...) 
std::iota(std::begin(vars), std::end(vars), 1); 

// Loop through all permutations of this array (see std::next_permutation): 
// 1 2 3 4 5 6 7 8 9 
// 1 2 3 4 5 6 7 9 8 
// 1 2 3 4 5 6 8 7 9 
// ... 
// 9 8 7 6 5 4 3 2 1 
do { 
    // Check if the variables matches what you want (see below for check): 
    if (check(vars)) { 
     std::cout << "Solution found: "; 
     for (auto v: vars) 
      std::cout << v << ' '; 
     std::cout << '\n'; 
    } 
} while(std::next_permutation(std::begin(vars), std::end(vars))); 

其中check是,例如:

int check(std::array<int, 9> const& vars) { 
    // Remember that vars[0] is a, vars[1] is b, ..., I rewrote your comparison as: 
    // c * i * (a + d + 12 * e - f - 11 -10) + 13 * b * i + c * g * h == 66 * c * i 
    // ...in order to avoid division. 
    return vars[2] * vars[8] * (vars[0] + vars[3] + 12 * vars[4] - vars[5] - 11 - 10) 
     + (13 * vars[1] * vars[8]) 
     + (vars[2] * vars[6] * vars[7]) == 66 * vars[2] * vars[8]; 
} 

还有其他的方法来找到你的解决方案:你可以降低你打算使用已经影响变量的值(例如,指派下一个变量的域,有没有必要循环最后一个变量,因为最后只有零个或一个可能的值),但是这更复杂,可能是你想要做的事情的矫枉过正。如果您想了解更多关于这一点,你可以寻找constraint programming

我重新组织的计算,因为你在做整数除法其截断的结果,所以你可以得到不正确的解决方案。


关于代码的一些细节你可能不熟悉,作为一个初学者:

  • std::array<int, 9>(C++ 11)是一个静态数组,取代int vars[9],你应该更喜欢使用这种过度只要可以,就可以使用c-style数组。
  • std::iota距离<algorithm>报头中的功能,将填补范围std::begin(vars)std::end(vars)与起始1(作为最后一个参数中提供的值)增加的值。
  • for (auto x: vars)是一个range-based for loop(自C++ 11以来可用),它允许您以简单的方式遍历任何容器。
相关问题