Last active
December 22, 2015 01:39
-
-
Save JonathonMA/6398082 to your computer and use it in GitHub Desktop.
Cross product of an array against itself n times
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def cross values, n = 3 | |
Array.new(n, values).inject do |acc, i| | |
acc.product(i).map(&:flatten) | |
end | |
end | |
require 'set' | |
describe do | |
it "should cross itself" do | |
arr = [0, 128] | |
out = [ | |
[0, 0, 0], | |
[0, 0, 128], | |
[0, 128, 0], | |
[0, 128, 128], | |
[128, 0, 0], | |
[128, 0, 128], | |
[128, 128, 0], | |
[128, 128, 128], | |
] | |
cross(arr).to_set.should eq out.to_set | |
end | |
end |
Author
JonathonMA
commented
Aug 31, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment