Skip to content

Instantly share code, notes, and snippets.

@bparanj
Created August 18, 2020 20:34
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 bparanj/fffeb0ceddd9c07fec7f24ff249a0acd to your computer and use it in GitHub Desktop.
Save bparanj/fffeb0ceddd9c07fec7f24ff249a0acd to your computer and use it in GitHub Desktop.
# @param {String} s
# @param {Integer[]} indices
# @return {String}
def restore_string(s, indices)
result = '' * indices.size
indices.each_with_index do |item, index|
result[item] = s[index]
end
result
end
@bparanj
Copy link
Author

bparanj commented Aug 18, 2020

Without creating a string of the required size, you will get an error.

@bparanj
Copy link
Author

bparanj commented Aug 20, 2020

A bit confusing, cleanup:

def restore_string(s, indices)
  result = '0' * (s.size)
  indices.each_with_index do |target_index, index|
    result[target_index] = s[index]
  end
  result
end

@bparanj
Copy link
Author

bparanj commented Aug 20, 2020

It's easy to get confused. The indices where the string needs to be copied is provided, but the index where we need to copy the character from the given string is different.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment