gpt4 book ai didi

algorithm - 如何编写暴力算法?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:18:28 25 4
gpt4 key购买 nike

我目前正在寻找一种暴力算法,但我找不到一个好的/简单的算法。
所以我试着自己写一个,但我失败了。我只是在数学或其他方面太差了。 :/
我不需要特定编程语言的算法,如果你有,我可能可以将它移植到我需要的语言中。
我基本上是在寻找像这样简单的东西:
(我尝试写一个暴力破解函数)

function BruteForce(chars,minLen,maxLen)
curCharArray = {}
for i=1, maxLen do
curCharArray[i] = 0
end
generatedString = ""
for currentLength = minLen, maxLen, 1 do
curCharArray[currentLength] = 1
Pos=currentLength
while Pos>0 do

if string.len(generatedString) < 1 then
generatedString= string.sub(chars,curCharArray[Pos],curCharArray[Pos])
else
generatedString= string.sub(generatedString,1,Pos-1) .. string.sub(chars,curCharArray[Pos],curCharArray[Pos])
end

print(generatedString)

curCharArray[Pos] = curCharArray[Pos]+1
Pos = currentLength
while curCharArray[Pos]==string.len(chars)+1 do
curCharArray[Pos]=1
Pos = Pos-1
end
end
end
end

BruteForceAttack("abc",2,3)

它是用Lua写的,你可以在这里在线运行代码:http://www.lua.org/cgi-bin/demo输出是:

a
ab
ac

a
ab
ac
a
aa
ab
ac
b
ba
bb
bc
c
ca
cb
cc
cca
ccb
ccc
ca
caa
cab
cac
cb
cba
cbb
cbc
cc
cca
ccb
ccc
a
aa
aab
aac
aa
aaa
aab
aac
ab
aba
abb
abc
ac
aca
acb
acc
b
ba
bab
bac
ba
baa
bab
bac
bb
bba
bbb
bbc
bc
bca
bcb
bcc
c
ca
cab
cac
ca
caa
cab
cac
cb
cba
cbb
cbc
cc
cca
ccb
ccc

如您所见,一些输出是相同的,并且未考虑最小长度。另外,顺序不对。我希望输出是:

aa
ab
ac
ba
bb
bc
ca
cb
cc
aaa
aab
aac
aba
abb
abc
aca
acb
acc
baa
bab
bac
bba
bbb
bbc
bca
bcb
bcc
caa
cab
cac
cba
cbb
cbc
cca
ccb
ccc

最佳答案

不幸的是,我不知道 LUA,但我认为这个 JavaScript 片段的想法很清楚:

function generate(current, len, chars) 
{
if (current.length == len)
console.log(current);
if (current.length < len)
for (var i in chars) {
generate(current + chars[i], len, chars)
}
}

function brute(chars, min, max)
{
for (var l = min; l <= max; ++l)
generate("", l, chars);
}

brute(['a', 'b', 'c'], 2, 3);

更新:没有递归的片段:

function generateNoRecursion(len, chars) 
{
// Indices that indicate what char to use on corresponding place.
var indices = [];
for (var i = 0; i < len; ++i)
indices.push(0);

// While all indices in set of chars
while (indices[0] < chars.length)
{
// Print current solution
var str = "";
for (var i = 0; i < indices.length; ++i)
str += chars[indices[i]];
console.log(str);
// Go to next solution by incrementing last index and adjusting
// if it is out of chars set.
indices[len-1]++;
for (var i = len-1; i > 0 && indices[i] == chars.length; --i)
{
indices[i] = 0;
indices[i-1]++;
}
}
}

function brute(chars, min, max)
{
for (var l = min; l <= max; ++l)
generateNoRecursion(l, chars);
}

关于algorithm - 如何编写暴力算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25899839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com