Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Count With Multiple Arrays

Tags:

arrays

ruby

I am trying to create a list of numbers and letters in order from 0-9 and a-z.

I have an array of values value_array = ['0','1','2','3','4','5','6','7','8','9','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']

and an array for the list of combinations, in order, that these numbers can produce for x number of characters, let's say three

list_array = []

and an array for the current combination of letters and numbers (which I will turn into a string before pushing it to the list array,]

current_combo ['0','0', '0']

How do I get the value array to count up for the current combo array so that I can create arrays like" ['0','0','1'] ['0','0','2'] ['0','0','3'] ['0','0','4'] ['0','0','5'] ['0','0','6'] .. .. .. ['a','z','1'] .. .. and finally to ['z','z','z']?

Here is my code thus far. Sorry if it's really crazy. I'm a noob at this:

    exponent = test.count('?')


puts 36 ** exponent

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

list = []

combo = []
end_combo = []

exponent.times do |e|
  combo << '0'
  end_combo << 'z'
end

puts combo.to_s

while combo != end_combo



end
like image 213
Melanie Shebel Avatar asked Mar 23 '11 19:03

Melanie Shebel


2 Answers

  value_array.repeated_permutation(n).to_a 
like image 40
sawa Avatar answered Oct 20 '22 14:10

sawa


xs = ("0".."9").to_a + ("a".."z").to_a
xs.product(xs, xs)
# [["0", "0", "0"], ["0", "0", "1"], ..., ["z", "z", "y"], ["z", "z", "z"]]

As Mladen noted, with Ruby 1.9 it's even easier:

(("0".."9").to_a + ("a".."z").to_a).repeated_permutation(3)
like image 73
tokland Avatar answered Oct 20 '22 14:10

tokland