Skip to content

Instantly share code, notes, and snippets.

@tarnfeld
Created October 5, 2013 10:25
Show Gist options
  • Save tarnfeld/6839234 to your computer and use it in GitHub Desktop.
Save tarnfeld/6839234 to your computer and use it in GitHub Desktop.
"""
Test:
Given two strings, `a` and `b`. Sort the letters in `a` by the order of letters in `b`.
For example:
a = "ssttexeste"
b = "test"
result = "ttteeesssx"
"""
def a_by_b(a, b):
pass
a = "adlkfhxaxjxkxhxfwkhkjfhjkahjksedeheflhadslfkhdfjkadhjhdhskghdjdjkhskkhjokhkshakhlhfkjdshjfkshhkskskss"
b = "alskdjfhg"
assert a_by_b(a, b) == "aaaaaallllssssssssssskkkkkkkkkkkkkkkkkkkkdddddddddjjjjjjjjjjjffffffffhhhhhhhhhhhhhhhhhhhhhgxxxxxweeeo"
@DouweM
Copy link

DouweM commented Oct 5, 2013

In JS:

a.split('').map(function(c) { var i = b.indexOf(c); return i == -1 ? Infinity : i; }).sort().map(function(i) { return b[i]; }).join('');

In Ruby:

a.chars.map { |c| b.index(c) || Float::INFINITY }.sort.map { |i| i == Float::INFINITY ? nil : b[i] }.join

Letters in a but not in b are simply dropped.

The performance is way worse than https://gist.github.com/tomhennigan/32e0d6ec4e25311bfd11 because of the number of loops and nested loops, but you can't have everything :P

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