Created
September 19, 2010 13:51
-
-
Save hawx/586773 to your computer and use it in GitHub Desktop.
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
# Matches an Array (of trues and falses) to a given Array. Fills itself | |
# with preference to fill where true first, then any spare items are put | |
# in place of false, then nils are used for remaining falses. | |
# | |
# input = ["a", "b", "c"] | |
# match = [true, false, false, true] | |
# | |
# match.optimise_fill(input) | |
# #=> ["a", "b", nil, "c"] | |
# | |
class Array | |
def optimise_fill(input) | |
match = self | |
diff = input.size - match.reject{|i| i == false}.size | |
result = [] | |
match.each_index do |i| | |
curr_item = match[i] | |
if curr_item == true | |
result << input.shift | |
else | |
if diff > 0 | |
result << input.shift | |
diff -= 1 | |
else | |
result << nil | |
end | |
end | |
end | |
result | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment