2015-09-08 45 views
-2

即时尝试做一个工作程序,必须通过给定的X元素数组中的所有3个数字排列,并在每个循环中总和所有3个数字并进行比较它给定数量正在被应用的下一条规则是:从给定的置换任意2个号码的总和必须>比排列3位 - 非重复排列 - 从X元素阵列

第3号是我的尝试:

for (int q = 0; q < sizeofarray; q++) 

for (int w = 0; w < sizeofarray; w++) 

    for (int e = 0; e < sizeofarray; e++){ 

compare_digits_from_permutation_to_given_number 

(givennumber,array[q],array[w],array[e]); 


} 

我的代码绝对不列入工作,这只是应该做我正在问的事情的一部分,但它只是前3个元素的排列,阵列是动态的,我也不要有想法如何做到这一点,任何两个数字的总和必须大于第三边

+1

我试图编译,但遗漏了很多的代码。请编辑您的文章,以便编译。 –

+0

什么是数组[数组] [数组] [数组] [数组] [E]?什么是compare_digits_from_permutation_to_given_number? –

+0

请不要删除原来的问题重新评论。本网站保留问题和答案,以便未来的观众可以从您收到的帮助中受益。 –

回答

0

既然你标记你的C++质疑更多,我会建议使用内置的std::next_permutation()

#include <algorithm> 
#include <string> 
#include <iostream> 

int main() 
{ 
    std::vector<int> v = {1,2,3} 
    do { 
     compare_digits_from_permutation_to_given_number(givennumber,v[0],v[1],v[2]); 
    } while(std::next_permutation(v.begin(), v.end())); 
} 
+0

这将从'begin()'到'end()'(或任何其他迭代器)进行所有迭代器的排列。你可以很容易地将它扩展到n个元素的数组。 – syntagma

+0

@ josh31然后这些不是排列组合。 – syntagma

0

你可以这样做:

void foo(std::vector<int> v, int n) 
{ 
#if 1 // remove duplicate input, so with {3, 3, 3, 4, 5}, 
     // the triplet (3, 4, 5) is shown only once. 
    std::sort(v.begin(), v.end()); 
    v.erase(std::unique(v.begin(), v.end()), v.end()); 
#endif 

    for (const auto& e1 : v) 
    { 
     for (const auto& e2 : v) 
     { 
      if (e2 == e1) { 
       continue; 
      } 
      for (const auto& e3 : v) 
      { 
       if (e3 == e1 || e3 == e2) { 
        continue; 
       } 
       if (e1 >= e2 + e3 || e2 >= e1 + e3 || e3 >= e1 + e2) { 
        continue; 
       } 
       const auto total = e1 + e2 + e3; 
       std::cout << e1 << "+" << e2 << "+" << e3 << "=" << total; 
       if (total < n) { 
        std::cout << " is less than " << n << std::endl; 
       } else if (total == n) { 
        std::cout << " is equal to " << n << std::endl; 
       } else { 
        std::cout << " is more than " << n << std::endl; 
       } 
      } 
     } 
    } 
} 

Live Demo