Pergunta

I need to create / generate long string contains permutation of characters and numbers at the same time I need to control the string length the most famous examples of this approach are

Metasploit project :

pettern_create.rb [string length as arg]

ex. pattern_create.rb 100

and

Ronin project:

String.generate([:alpha, 1], :numeric).take(100).each do |pattern| 
   print pattern
end

both will generate

A0A1A2A3A4A5A6A7A8A9B0B1B2B3B4B5B6B7B8B9C0C1C2C3C4C5C6C7C8C9D0D1D2D3D4D5D6D7D8D9E0E1E2E3E4E5E6E7E8E9F0F1F2F3F4F5F6F7F8F9G0G1G2G3G4G5G6G7G8G9H0H1H2H3H4H5H6H7H8H9I0I1I2I3I4I5I6I7I8I9J0J1J2J3J4J5J6J7J8J9

I tried with

all  = ["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",
         "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",
         "0","1", "2", "3", "4", "5", "6", "7", "8", "9"]

puts  all.permutation(4).to_a

puts this will take a huge time because it'll generate ALL permutations without control, the control is the way to prevent unwanted strings

there is no issue in specifying the particular position of a string like "4C5C6" I can use

str = "A0A1A2A3A4A5A6A7A8A9B0B1B2B3B4B5B6B7B8B9C0C1C2C3C4C5C6C7C8C9D0D1D2D3D4D5D6D7D8D9E0E1E2E3E4E5E6E7E8E9F0F1F2F3F4F5F6F7F8F9G0G1G2G3G4G5G6G7G8G9H0H1H2H3H4H5H6H7H8H9I0I1I2I3I4I5I6I7I8I9J0J1J2J3J4J5J6J7J8J9"
puts str.index("4C5C6")   #=> 46

Notes:

  • permutation should be generated with same sequence all the time.
  • I don't want to force user to gem huge project for small function
  • I need to understand the algorithm or programmatic trick to do that

Thanks

Foi útil?

Solução

The permutation method results in a enumerator, which is what you want. Don't turn it into an array with to_a, just take what you need.

all  = ["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",
         "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",
         "0","1", "2", "3", "4", "5", "6", "7", "8", "9"]

p  all.permutation(4).first(100) #take(100) is fine too

Ruby strings work in a Range btw, so you can do:

('aaaa'..'zzzz').first(100) #or
('A0'..'Z9').first(100).join
#=> "A0A1A2A3A4A5A6A7A8A9B0B1B2B3B4B5B6B7B8B9C0C1C2C3C4C5C6C7C8C9D0D1D2D3D4D5D6D7D8D9E0E1E2E3E4E5E6E7E8E9F0F1F2F3F4F5F6F7F8F9G0G1G2G3G4G5G6G7G8G9H0H1H2H3H4H5H6H7H8H9I0I1I2I3I4I5I6I7I8I9J0J1J2J3J4J5J6J7J8J9"
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top