Ruby 按顺序从字符串中获取所有长度的排列 [英] Ruby get permutations of all lengths from a string in order

查看:26
本文介绍了Ruby 按顺序从字符串中获取所有长度的排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码-

$arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"
def scan(f)
    begin
        if f.size == 6
              exit
        end
        $arr.each_char do |y|
            t =  f + y
            puts t
            scan(t)
        end
    end
end

我希望将所有排列和长度打印到 6,我已经尝试过这种递归方法.我得到的输出是 -

I wish to print all permutations and lengths upto 6, I've tried this recursive approach. The output I get is -

A 
AA
AAA 
AAAA
AAAAA

但是我寻求这样的东西-

However I seek something like this-

A
AA
AB
AC
.
.
AZ
AAA
AAB
.
.
AAZ
.
.
upto 6 chars

在评论递归调用时,我看到它打印了

On commenting the recursive call I see that it prints

AA
AB
AC
.
.

不用递归就可以,但不用递归就不行.任何类型的建议表示赞赏.谢谢.

Which is fine without recursion but not with recursion. Any kinds of suggestions are appreciated. Thank you.

推荐答案

Array#repeated_permutation 可以在这里为您完成繁重的工作:

Array#repeated_permutation can do the heavy lifting for you here:

$arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"
def scan
  characters = $arr.chars

  (1..6).each do |length|
    characters.repeated_permutation(length) do |sequence|
      t = sequence.join
      puts t
    end
  end
end

或者作为更可重用的枚举器:

Or as a more reusable enumerator:

CHARACTERS = [*"A".."Z", *"a".."z", *"0".."9", "_", "-"]
def each_permuted_string(max_length = 6, &block)
  sequences = (1..max_length).map { |n| CHARACTERS.repeated_permutation(n) }

  if block_given?
    sequences.each { |seq| seq.lazy.map(&:join).each(&block) }
  else
    enum_for(__method__, max_length) { sequences.map(&:size).inject(:+) }
  end
end

each_permuted_string do |t|
  puts t
end

这将需要很长时间,不过——有 each_permuted_string.size =>69810262080 值.这听起来像是一个 XY 问题,您可能会通过询问有关更高级别的问题来获得更好的解决方案-您正在解决的级别问题.

It's going to take a very long time, though -- there are each_permuted_string.size => 69810262080 values. This sounds like it could be an XY Problem, and you might get a better solution by asking a question about the higher-level problem you're solving.

这篇关于Ruby 按顺序从字符串中获取所有长度的排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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