- //
- // main.c
- // Exhaust_pwd
- //
- // Created by 颜风 on 14-4-19.
- // Copyright (c) 2014年 天启传媒. All rights reserved.
- //
- #include <stdio.h>
- #include <string.h>
- #include <math.h>
- #include <stdlib.h>
- //------------------函数的声明--------------
- /*穷举由给定选项组成的指定位数的所有不重复的密码组合.
- *函数核心思想在于在函数的递归调用.
- *options char* 指定密码可选项
- *opt_length unsigned 可选项总个数
- *digits unsigned 密码位数
- *pwds char** 一个用于存储生成的密码的二维数组.函数调用者需要保证它有合适的长度和宽度.
- */
- void exhaust_pwd(char* options, unsigned opt_length,unsigned digits, char** pwds);
- //------------------函数的定义--------------
- //密码穷举
- void exhaust_pwd(char* options, unsigned opt_length, unsigned digits,char** pwds){
- //调用深度
- static unsigned depth = 1;
- //计数,统计有效密码组合的总个数.
- static unsigned count = 0;
- for (int i = 1; i <= opt_length; i++) {
- //是否是密码的最后一位?
- if (depth == digits) {
- //把密码组合复制存储到pwds
- //仅最后一位不同,即最后一位需要单独设定
- for (int k=1; k < digits; k++) {
- pwds[count][k-1] = pwds[0][k-1];
- }
- pwds[count][depth-1] = options[i-1];
- //pwds存储的有效密码总个数加1.
- count++;
- continue;
- }else{
- //由于pwds的第一个密码组合是既定的,故暂时使用pwds[0]作为临时字符数组存储各个密码组合
- pwds[0][depth-1] = options[i-1];
- //遍历深度自增1
- depth++;
- exhaust_pwd(options, opt_length, digits, pwds);
- }
- }
- //判断是否穷举所有有效组合.
- if (count == pow(opt_length, digits)) {
- //正确设定pwds[0];
- for (int i = 1; i <= digits; i++) {
- pwds[0][i-1] = options[0];
- }
- }else{
- // 未穷巨额所有有效密码组合,则返回上层,继续执行
- depth--;
- }
- return;
- }
- int main(int argc, const char * argv[])
- {
- /*
- 请你用循环给我穷举字母abcdef,大写ABCDEF,数字0~9组成的所有的不重复的
- 密码组合,并输出出来.密码为6位数.
- */
- //方法一:六重嵌套,每一重控制密码的一个位数.
- char options[22] =
- {'a','b','c','d','e','f','A','B','C','D','E','F','0','1','2','3','4','5','6','7','8','9'};
- for (int i1=1; i1 <= 22; i1++) {
- for (int i2=1; i2 <= 22; i2++) {
- for (int i3=1; i3 <= 22; i3++) {
- for (int i4=1; i4 <= 22; i4++) {
- for (int i5=1; i5<=22; i5++) {
- for (int i6=1; i6<=22; i6++) {
- //共113379904种可能的组合,故先注释掉,以方便其他代码的调试.
- // printf("%c%c%c%c%c%c\\n",options[i1-1],options[i2-1],options[i3-1],options[i4-1],options[i5-1],options[i6-1]);
- }
- }
- }
- }
- }
- }
- printf("\\n");
- //方法二:调用自己写的 密码穷举函数
- int digits = 3;//位数 此处仅使用2,以方便测试此函数
- int opt_length = strlen(options);//可选项数目
- //动态内存分配:定义一个行列都是动态的二维数组,用于存储所有的密码组合
- char **pwds = (char**)malloc(sizeof(char*)*pow(opt_length, digits));
- for (int i = 1; i <= pow(opt_length, digits); i++)
- pwds[i-1] = (char*)malloc(sizeof(char)*digits);
- //函数调用
- exhaust_pwd(options, opt_length, digits, pwds);
- //使用pwds进行相关操作
- //简单地遍历输出
- for (int i = 1; i <= pow(opt_length, digits); i++){
- for (int j = 1; j <= digits; j++) {
- printf("%c",pwds[i-1][j-1]);
- }
- printf("\\n");
- }
- //手动释放pwds分配的内存
- for (int i = 1; i < pow(opt_length, digits); i++){
- free(pwds[i-1]);
- }
- free(pwds);
- printf("\\n");
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/1809201410466.html
来源: http://www.codesnippet.cn/detail/1809201410466.html