Skip to content

Instantly share code, notes, and snippets.

@moserrya
Created April 19, 2013 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moserrya/5423914 to your computer and use it in GitHub Desktop.
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!
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)
@jfarmer
Copy link

jfarmer commented Apr 19, 2013

Alas, the space requirement makes this more functional solution a no-go:

def rearrange(characters, positions)
  positions.zip(characters).sort.map(&:last)
end

@enocom
Copy link

enocom commented Apr 20, 2013

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