Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate alphanumeric sequence in Ruby

Tags:

string

ruby

How would I go about generating a sequential alphanumeric string?

Each string should only be 8 characters.

The characters possible for each position are:

["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "B", "C", "D", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "X", "Y", "Z"]

Also, If possible I would like to choose the starting point of the sequence.

For example:

00000001
00000002
00000003
00000005
...
0000L3FH
0000L3FJ
0000L3FK
0000L3FL
0000L3FM
0000L3FN
0000L3FP
...
0000L4FP
0000L4FQ
0000L4FR
0000L4FS
...
0000M000
0000M001
0000M002
like image 626
OpenCoderX Avatar asked Feb 08 '13 14:02

OpenCoderX


1 Answers

That is a permutation with repetition. Arrays can do that out of the box.

chars = %w(0 1 2 B C)
sequencer = chars.repeated_permutation(chars.size) #OP:replace chars.size by 8
10.times{p sequencer.next}
#["0", "0", "0", "0", "0"]
#["0", "0", "0", "0", "1"]
#["0", "0", "0", "0", "2"]
#["0", "0", "0", "0", "B"]
#["0", "0", "0", "0", "C"]
#["0", "0", "0", "1", "0"]
#["0", "0", "0", "1", "1"]
#["0", "0", "0", "1", "2"]
#["0", "0", "0", "1", "B"]
#["0", "0", "0", "1", "C"]

p sequencer.next
#["0", "0", "0", "2", "0"]
like image 132
steenslag Avatar answered Oct 16 '22 23:10

steenslag