本文介绍了如何更有效地生成所有可能的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我正在尝试编写随机电话号码生成器。最后6位必须等于33.我已经将随机生成部分放下了。 我想要的是生成属于此规则的所有可能组合。我想我可以通过一长串FOR循环,IF和数学来实现它。我想知道是否有更有效的方法吗? 由于评论没有正确显示...这是格式化的代码 for ( int number [ 1 ] = 0 ;数字[ 1 ]< = 9 ; number [ 1 ] ++){ // 这里的一些数学运算确保它在末尾等于33 ( int number [ 2 ] = 0 ; number [ 2 ]< = 9 ; number [ 2 ] ++){ // 这里有一些数学最后它等于33 ( int number [ 3 ] = 0 ;数字[ 3 ]< = 9 ; number [ 3 ] ++){ // 一些数学运算确保它在结尾处等于33 ( int number [ 4 ] = 0 ; number [ 4 ]< = 9 ;编号[ 4 ] ++){ // 这里的一些数学运算确保它在结尾处等于33 for ( int number [ 5 ] = 0 ;数字[ 6 ]< = 9 ;数字[ 5 ] ++){ // 这里的一些数学确保它在末尾等于33 ( int number [ 6 ] = 0 ;编号[ 6 ]< = 9 ; number [ 6 ] ++){ // 这里的一些数学确保它最终等于33 } } } } } } 解决方案 您不需要嵌套for循环。你可以使用一个循环到999999并检查交叉总和: ( unsigned long n = 0 ; n< = 999999 ; n ++) { if (digit_sum(n)== 33 ) printf( (xxx)x%lu \ n,n); } 可能的优化是循环起始值(数字总和为33的最小数字)和计算数字总和的函数(33的特殊版本检查) )。 I'm currently trying to write a random phone number generator. The Last 6 digits must equal 33. I've got the random generating part down.What I want is to generate all possible combinations that fall under this rule. I was thinking I can go about it with a long list of FOR loops, IFs, and math. I was wondering if there's a more efficient way of doing this?Since the comment doesn't display it correctly... This is the formatted codefor(int number[1] = 0; number[1] <= 9; number[1]++){ //some math here making sure it equals 33 at the end for(int number[2] = 0; number[2] <= 9; number[2]++){ //some math here making sure it equals 33 at the end for(int number[3] = 0; number[3] <= 9; number[3]++){ //some math here making sure it equals 33 at the end for(int number[4] = 0; number[4] <= 9; number[4]++){ //some math here making sure it equals 33 at the end for(int number[5] = 0; number[6] <= 9; number[5]++){ //some math here making sure it equals 33 at the end for(int number[6] = 0; number[6] <= 9; number[6]++){ //some math here making sure it equals 33 at the end } } } } }} 解决方案 You don't need nested for loops. You can use one loop up to 999999 and check the cross sum:for (unsigned long n = 0; n <= 999999; n++){ if (digit_sum(n) == 33) printf("(xxx) x%lu\n", n);}Possible optimizations are the loop start value (lowest number with digit sum of 33) and the function to calculate the digit sum (special version checking for 33). 这篇关于如何更有效地生成所有可能的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-02 00:50