如何生成所有可能的字符串,所有的 ascii 字符,到一定长度 [英] How to generate all possible strings, with all ascii chars, to a certain length

查看:57
本文介绍了如何生成所有可能的字符串,所有的 ascii 字符,到一定长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天一直在努力,试图制作一个函数,它可以生成所有可能的字符串,以及所有可能的 ascii 字符,直到一定长度.

I've been struggling a bit today, trying to make a function, that can generate all possible strings, with all possible ascii chars, up to a certain length.

所以基本上,首先是单个字符,从 0 到 255.然后是两个,我得到 AA,然后是 AB,然后是 AC ......等等(但使用 ascii 字符代码,以获取每个点的所有可能值).
有意义吗?

So basically, first a single char, from 0-255. Then two where I get AA, then AB, then AC... etc (but using ascii char codes, to get all possible values in each spot).
Does that make sense?

我想我很擅长递归,因为我所做的每一次尝试,要么太复杂,我自己无法弄清楚,要么最终只增加了字符串中的最后一个位置.

I guess I suck at recursion, because every attempt I make, either gets way too complicated for myself to figure it out, or ends up only increasing the last position in my string.

我完全被困在这里,无法了解我在做什么.
我试过谷歌搜索无济于事,通常以相同的文章结尾,但似乎不是同一个问题.

I'm completely stuck here and loosing all overview of what I'm doing.
I've tried googling to no avail, usually ending up in the same articles that doesn't quite seem to be the same problem.

我会对任何示例感到满意,它不一定是 javascript.

I'll be happy with any examples, it doesn't have to be javascript.

帮助我 stackoverflow,你是我唯一的希望.

Help me stackoverflow, you're my only hope.

推荐答案

您可以使用生成器,递归地构建字符串并将结果返回给调用者:

You could use a generator, that recursively builds up the string and yields up the results to the caller:

  function* chars() {
    for(let i = 0; i < 255; i++) 
      yield String.fromCharCode(i);
  }

 function* combinations(length, previous = "") {
   if(length <= 0) {
      yield previous;
      return;
   }

   for(const char of chars())
      yield* combinations(length - 1, previous + char);
}

这样你就可以得到所有的组合:

That way you can get all combinations as:

  const result = [...combinations(5)];

请注意,255 ** n 很多,因此您可能需要一个接一个地使用这些组合:

Note that 255 ** n is a lot, so you might want to consume the combinations one after another:

  const timer = ms => new Promise(res => setTimeout(res, ms));

  (async function() {
     for(const combo of combinations(5)) {
       console.log(combo);
       await timer(1);
     }
 })();

这篇关于如何生成所有可能的字符串,所有的 ascii 字符,到一定长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆