生成由"a-z"26 位字母组成的 ,五位长度的所有字符串,不限语言,不限方法!

2014-09-12 15:10:49 +08:00
 xming
7893 次点击
所在节点    问与答
62 条回复
bigcoon
2014-09-12 15:31:58 +08:00
var a = 'abcdefghijklmnopqrstuvwxyz';
var f = function (d, p) {
!p && (p = '');
for (var i = 0; i < a.length; i++) {
var s = a[i], s2 = p + s;
if (s2.length < d)f(d, s2);
else console.log(s2);
}
}
f(5);
Automan
2014-09-12 15:34:27 +08:00
重复还是不重复?
ChanneW
2014-09-12 15:37:22 +08:00
26^5
kamal
2014-09-12 15:43:28 +08:00
这是考手写排列公式?
clino
2014-09-12 15:44:11 +08:00
python:

import itertools
print map("".join,list(itertools.product("abcdefghijklmnopqrstuvwxyz",repeat=5)))
clino
2014-09-12 15:47:46 +08:00
不用map会更好一点,这样不会占太多内存
import itertools
for l in itertools.product("abcdefghijklmnopqrstuvwxyz",repeat=5):print "".join(l)
ziyuan
2014-09-12 15:49:23 +08:00
java

import java.util.ArrayList;
import java.util.List;

public class Test {
private static char[] is = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h','i', 'j', 'k', 'l', 'm', 'n', 'o', 'p','q', 'r', 's', 't', 'u', 'v', 'w', 'x','y','z'};
private static int total;
private static int m = 5;
public static void main(String[] args) {
List<Integer> iL = new ArrayList<Integer>();
new Test().plzh("", iL, m);
System.out.println("total : " + total);
}
private void plzh(String s, List<Integer> iL, int m) {
if(m == 0) {
System.out.println(s);
total++;
return;
}
List<Integer> iL2;
for(int i = 0; i < is.length; i++) {
iL2 = new ArrayList<Integer>();
iL2.addAll(iL);
if(!iL.contains(i)) {
String str = s + is[i];
iL2.add(i);
plzh(str, iL2, m-1);
}
}
}
}
imn1
2014-09-12 15:52:30 +08:00
import itertools
list("".join(x) for x in itertools.product('abcdefghijklmnopqrstuvwxyz', repeat=5))
YouXia
2014-09-12 15:53:56 +08:00
题意有点不明啊,是否有序啊,比如 a b c d e 与 a c b d e 是否相同?
xming
2014-09-12 15:58:41 +08:00
@Automan 不能重复,要不同
xming
2014-09-12 15:59:06 +08:00
@YouXia 无序的
xming
2014-09-12 16:00:55 +08:00
@clino 不计算内存消耗,只要不卡死。
ziyuan
2014-09-12 16:04:27 +08:00
@imn1 python居然这么方便啊。。赞
hahastudio
2014-09-12 16:07:12 +08:00
那么就
from itertools import combinations
from string import ascii_lowercase as lowercase
for c in combinations(lowercase, 5):
....print ''.join(c)
toctan
2014-09-12 16:07:52 +08:00
Ruby

('aaaaa'..'zzzzz').to_a
imn1
2014-09-12 16:09:20 +08:00
itertools还是太慢了,array+tobytes应该更快,或者用numpy或pandas直接生成一个数字矩阵,再chr/tobytes后合并变形~
机器太旧,不测试了~
rails3
2014-09-12 16:09:26 +08:00
@toctan ruby更方便
paolongtao
2014-09-12 16:10:44 +08:00
@toctan 哈哈
iptux
2014-09-12 16:15:08 +08:00
BASH 来一发

```bash
echo {a..z}{a..z}{a..z}{a..z}{a..z}
```
ChiangDi
2014-09-12 16:15:26 +08:00
哈哈哈哈看起来没有哪种语言能短过 Ruby 了。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/133080

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX