Created
April 19, 2013 23:19
-
-
Save moserrya/5423914 to your computer and use it in GitHub Desktop.
Rearrange the elements of one array according to an index in another array without using additional space in memory.
Note: This solution works but destroys the positions array in the process!
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
characters = [ 'o', 'h', 'e', 'd', 'n', 'r', 'y', 'g', 'a', 'b', 'e' ] | |
positions = [ 1, 0, 4, 2, 6, 9, 8, 3, 7, 10, 5] | |
def rearrange(characters, positions) | |
positions.length.times do |i| | |
positions[i] = characters[positions[i]] | |
end | |
positions.each_with_index {|e, i| characters[i] = e} | |
end | |
rearrange(characters, positions) |
Positions array be damned!
def rearrange(characters, positions)
positions.each_with_index do |obj, index|
positions[index] = characters[obj]
end
positions
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alas, the space requirement makes this more functional solution a no-go: