生成所有可能的字符串组合

编程入门 行业动态 更新时间:2024-10-09 04:17:47
本文介绍了生成所有可能的字符串组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试生成字符串的所有可能组合。

I am trying to generate all possible combinations of a string.

例如。对于下面的列表:a1q5z!H9,b1q5z!H9,c1q5z!H9,d1q5z!H9,a2q5z!H9 ......等

e.g. for the list below: a1q5z!H9, b1q5z!H9, c1q5z!H9, d1q5z!H9, a2q5z!H9 ... etc

而不是制作大量嵌套循环,我以为我会尝试用MODULO聪明的东西......但是碰到了一堵墙。

Rather than make lots of nested loops, I thought I would try something clever with MODULO ... but hit a wall.

这是我想出的Javascript - 任何关于我如何去的指示在?

This is the Javascript I have come up with - any pointers to how I might go on?

var c = [ ['a', 'b', 'c', 'd'], ['1', '2', '3', '4'], ['q', 'w', 'e', 'r'], ['5', '6', '7', '8'], ['z', 'x', 'c', 'v'], ['!', '"', '£', '$'], ['H', 'J', 'K', 'L'], ['9', '8', '7', '6'], ]; var o = document.getElementById('output'); var pw = ""; var chars = c.length; for( var i = 0; i <20; i++) { pw = "" for(var j = 0; j < chars; j++ ) { pw += c[j][i%4]; } op(pw); } function op(s) { o.innerHTML = o.innerHTML + "<br>" + s; }

这只输出列表中的前20个,但重复...我几乎拥有它但不完全。任何帮助或指示赞赏。

This just outputs the first 20 in the list, but repeats ... I nearly have it but not quite. Any help or pointers appreciated.

推荐答案

很容易编写递归函数演示。

function permutate(abc, memo) { var options; memo = memo || abc.shift().slice(0); if(abc.length) { options = abc.shift(); return permutate(abc, memo.reduce(function(all, item){ return all.concat(options.map(function(option){ return item + option; })) }, [])); } return memo; }; console.log(permutate(c).length); //65536 items

或更多必要方法

function permutate2(abc) { var options, i, len, tmp, j, optionsLen, memo = abc.pop().slice(0); //copy first the last array while(options = abc.pop()) { //replace recursion tmp = []; optionsLen = options.length; for(i = 0, len = memo.length; i < len; i++) { //for every element in memo for(j = 0; j < optionsLen; j++) { //do cartesian product with options tmp.push(options[j] + memo[i]); } } memo = tmp; } return memo; }

更多推荐

生成所有可能的字符串组合

本文发布于:2023-11-30 07:29:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649172.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!