I've been building an intelligent Mastermind game in Ruby. In my game, if you select the option of having the computer play the role of code breaker, the computer makes educated guesses at what the code maker's code is.
As part of my algorithm, the computer first looks at the entire list of ALL POSSIBLE CODES.
For example, if there are 6 colors to choose from (red orange blue green purple yellow) and the code is made up of 4 colors (repeats are allowed), then to view all possible codes, you can do this:
valid_colors = %w(red orange blue green purple yellow)
all_possible_codes = valid_colors.repeated_permutation(4).to_a
And all_possible_codes
will be an array filled with arrays representing every possible code. The computer then eliminates codes from this list as it gets feedback from each of its guesses.
The next thing I'm working on, however, requires me to use JRuby 1.6.6, which uses Ruby 1.8.7, which does NOT have a repeated_permutation
method. I need to write my own method with the same functionality.
So I went to the source code found here: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-repeated_permutation
Unfortunately, I don't understand what they're doing or how I could go about solving this by writing a method of my own. I'm fairly new to programming and haven't been able to figure this out. Any help with understanding that source code would be greatly appreciated!
Thanks yngum!
Just to expand on your answer, I renamed some variables to make it more Ruby-esque, more clear, descriptive, and explicit. I also changed a few things so the return value of the method would be the answer, an array that contains each of the possible permutations.
I don't love naming it
index_positions
, but couldn't think of a better name. The above method will return an array filled with arrays of all possible permutations with repetition allowed.To implement:
valid_colors = %w(red orange blue green purple yellow)
repeated_permutations(valid_colors, 4, [], [], 0)
The code you linked calls rpermute0 which does most the work, source code for rpermute0 in Array.c is
Basially a brute force, starting from 0 returning one permutation each iteration. ruby version is something like
I tested above code and it prints out all permutation of length 4, u might want to put them into array.