Reputation: 1442
I need a method written in Ruby which computes Variations. I have already written it in Java, but as I'm new to Ruby, there's just something I'm missing about the Ruby implementation.
The method is supposed to do this:
method(1, "01") => ["0", "1"] <br>
method(2, "01") => ["00", "01", "10", "11"] ...so you get the idea.
note: in the Ruby implementation, I give params like this:
method(2, ["0", 1"])
but that's not an issue.
My Java implementation:
public static List<String> Variations(int strength, String usableChars) {
List<String> list =
new ArrayList<String>((int) Math.pow(usableChars.length(), strength));
if (strength == 0) {
list.add("");
} else {
List<String> l = Variations(strength - 1, usableChars);
for (char c : usableChars.toCharArray()) {
for (String s : l) {
list.add(c + s);
}
}
}
return list;
}
And it's working fine. But this is my Ruby implementation:
def Variation (strength, arrayOfString)
array = Array.new(arrayOfString.size**strength)
if strength == 0
array << ""
else
a = Variation(strength-1, arrayOfString)
for i in arrayOfString do
for j in a do
array << (i + j)
end
end
end
return array
end
In this, I keep getting an error message
test.rb:10:in `Variation': can't convert nil into String (TypeError).
Upvotes: 2
Views: 363
Reputation: 108139
In Ruby, arrays grow automatically as needed. So change your array initialization from:
array = Array.new(arrayOfString.size**strength)
to
array = []
To enumerate over each character in a string, instead of
for i in arrayOfString do
do this:
arrayOfString.each_char do |i|
The final result:
#!/usr/bin/ruby1.8
def Variation (strength, arrayOfString)
array = []
if strength == 0
array << ""
else
a = Variation(strength - 1, arrayOfString)
arrayOfString.each_char do |i|
for j in a do
array << (i + j)
end
end
end
return array
end
p Variation(2, '01') # => ["00", "01", "10", "11"]
each_char is in Ruby >= 1.8.7, or you can get it from the backports gem.
Upvotes: 2