arrays - ruby - 如何制作不同长度的字母(az)数组,最大长度为 5
问题描述
所以我试图制作一个包含所有可能排列的字母(全部小写)的数组,其中字母可以重复并且长度从 1 到 5 不等。例如,这些是数组中的一些可能性:
['this','is','some','examp','le']
我试过这个,它得到了 5 个字母长的单词的所有变体,但我不知道如何找到不同的长度。
("a".."z").to_a.repeated_permutation(5).map(&:join)
编辑:
我正在尝试这样做以破解 SHA1 加密字符串:
require 'digest'
def decrypt_string(hash)
("a".."z").to_a.repeated_permutation(5).map(&:join).find {|elem| Digest::SHA1.hexdigest(elem) == hash}
end
Hash 为单词的 SHA1 加密,如'e6fb06210fafc02fd7479ddbed2d042cc3a5155e'
解决方案
您可以稍微修改您的方法。
require 'digest'
def decrypt_string(hash)
arr = ("a".."z").to_a
(1..5).each do |n|
arr.repeated_permutation(n) do |a|
s = a.join
return s if Digest::SHA1.hexdigest(s) == hash
end
end
end
word = "cat"
hash = Digest::SHA1.hexdigest(word)
#=> "9d989e8d27dc9e0ec3389fc855f142c3d40f0c50"
decrypt_string(hash)
#=> "cat"
word = "zebra"
hash = Digest::SHA1.hexdigest(word)
#=> "38aa53de31c04bcfae9163cc23b7963ed9cf90f7"
decrypt_string(hash)
#=> "zebra"
在我的 2020 Macbook Pro 上,计算"cat"
时间不到一秒;那些"zebra"
花了大约 15 秒。
请注意,join
应该在repeated_permutation
's 块内应用,因为repeated_permutation(n).map(&:join)
将创建一个具有尽可能多的26**5 #=> 11,881,376
元素(for n = 5
)的临时数组。
推荐阅读
- google-apps-script - Copy File One folder to another folder in Google Drive using file list from text file
- angularjs - AngularJS $scope vs this
- css - 条件 CSS 声明
- r - How to convert list of characters to columns
- python - pipenv or virtualenv , which one is better to use?
- java - Visual Studio Code 不再编译 Java
- objective-c - iOS NSURLRequest uploadTaskWithRequest 仅在 iOS 13 后台超时
- c# - How to make a bullet fly where it is pointed
- spring-boot - Postman 中用于 POST 请求的消息 400
- android - 清理应用程序数据后,Room 数据库中仍保留一个用户对象