【发布时间】:2019-07-14 21:53:04
【问题描述】:
我需要一个针对字母数字字符的蛮力算法。
我使用的代码只是将所有排列打印到标准输出。我尝试了几个小时,但未能以这样的方式重写代码,以至于我可以在需要时调用函数 brute_next() 来获取下一个代码字。
有人可以帮我重写这段代码吗?函数brute_next() 应该返回一个char* 或者获取一个char* 作为参数。我在 Mac 下使用 CLion 和 gcc。
代码是(source):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static const char alphabet[] =
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789";
static const int alphabetSize = sizeof(alphabet) - 1;
void bruteImpl(char* str, int index, int maxDepth)
{
for (int i = 0; i < alphabetSize; ++i)
{
str[index] = alphabet[i];
if (index == maxDepth - 1) printf("%s\n", str);
else bruteImpl(str, index + 1, maxDepth);
}
}
void bruteSequential(int maxLen)
{
char* buf = malloc(maxLen + 1);
for (int i = 1; i <= maxLen; ++i)
{
memset(buf, 0, maxLen + 1);
bruteImpl(buf, 0, i);
}
free(buf);
}
int main(void)
{
bruteSequential(3);
return 0;
}
这是我将递归转换为生成器的无效尝试。只是无法弄清楚排列算法是如何工作的。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char alphabet[] =
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789"
"$%&/()=.-_;!+*#";
static const int alphabetSize = sizeof(alphabet) - 1;
struct bruteconfig {
int index;
int i1;
int i2;
char* str;
int maxDepth;
};
static struct bruteconfig* config;
void brute_init(int maxLen){
free(config);
config = malloc(sizeof(struct bruteconfig*));
config->i1 = 1;
config->i2 = 0;
config->index = 0;
config->maxDepth = maxLen;
}
void bruteImpl()
{
if(config->i2 > alphabetSize) // how to transform for to iterative?
config->i2 = 0;
config->str[config->index] = alphabet[config->i2];
if (config->index == config->maxDepth - 1) {
//printf("%s\n", config->str);
return; // str filled with next perm
}
else {
config->index++;
//bruteImpl(config->str, config->maxDepth);
}
config->i2++;
}
char* bruteSequential()
{
config->str = malloc(config->maxDepth + 1);
if(config->i1 >= config->maxDepth)
return NULL;
memset(config->str, 0, config->maxDepth + 1); // clear buf
bruteImpl(config->str, config->i1); // fill with next perm
return config->str;
//free(buf); // needs to be done by the caller
}
【问题讨论】:
-
请在问题本身中包含任何相关代码,而不是作为外部链接。修剪任何不必要的内容来重现您遇到的问题。
-
1:将递归函数转换为迭代函数。请注意,您的函数每次调用只会将索引增加一,因此它可能是
for (int index = 0; index != maxDepth - 1; index++)。 2:识别“上下文” - 即。识别您在代码中的位置所需的所有变量。那将是您的函数中的所有局部变量。 3:创建一个struct brute_ctx_s { /* members */ }结构,它将保存函数的所有上下文变量,并通过指向函数的指针传递上下文。让所有局部变量使用上下文。 -
@KamilCuk 谢谢!这正是我的尝试。但是,我只是无法弄清楚该算法是如何工作的。我试图将其转换为将局部变量保存在结构中的迭代算法,但输出完全错误......
-
4:注意,如果你返回一个
char*变量,你必须管理它的内存。确定您是否知道此类变量的最大长度并希望使用静态分配或动态分配。 5. 所以这个函数可能看起来像char *brute_next(struct brute_ctx_s *ctx),你很可能还需要int brute_start(struct brute_ctx_s *ctx)和bool brute_end(struct brute_ctx_s *ctx)来启动和停止你生成的暴力序列。主观上,我会选择指针,例如。int brute_next(struct brute_ctx_s *ctx, char **ret, size_t *size),但那是我。 6.size_t类型用于表示大小。 -
@KamilCuk 我会再次尝试发布我的尝试..
标签: c brute-force