How to get from string to anagram in fewest number of swaps?

I'm using Python for the backend of this project. I have a string l1 that is 19 characters long. I have a string l2 that is an anagram of l1 (l2 has the same characters as l1 but shuffled). I want to get from l1 to l2 in the fewest number of steps, the only move allowed is to swap any two letters (they don't have to be adjacent). l1 can have repeated letters. I'm trying to create a function that outputs the swaps the user needs to make to achieve the least possible number, represented as tuples with the indices of the letters the user needs to swap. For example,
l1 = "abc123456789abcdefg"
l2 = "cca123456789bbadefg"

# f(l1, l2) should return:
# [(0, 14), (1, 12), (1, 3)]
l1 = "abc123456789abcdefg"
l2 = "cca123456789bbadefg"

# f(l1, l2) should return:
# [(0, 14), (1, 12), (1, 3)]
I've tried BFS, but I couldn't figure out a way to make it work with repeated letters. It seems quite straightforward, but I can't figure out a way to ensure minimum swaps. Any help would be appreciated.
9 Replies
Chief
Chief4w ago
sorry but how is this backend related question? seems like a DSA one
dys 🐙
dys 🐙4w ago
Search "minimum edit distance".
ἔρως
ἔρως4w ago
can there be 2 places that have the same mistake? for example, you swapped "a" and "c" on 0 can there be more places where "a" and "c" are swapped in the same way?
Blanwhit
BlanwhitOP4w ago
Yes. The strings can have any combination of letters in any order, the only condition is that they’re anagrams of each other
ἔρως
ἔρως4w ago
that's a much harder problem then
Blanwhit
BlanwhitOP4w ago
I've looked at lots of edit distance algorithms but none of them were close enough to this that a small modification could solve the problem. However, I did figure out a way of handling it using the fact that each permutation of a group can be uniquely converted into transpositions. It's rather inefficient since I have to try all permutations of repeated letters but hey, it works. Either way, thanks for suggestions everyone
ἔρως
ἔρως4w ago
question: why do you even need this?
Blanwhit
BlanwhitOP4w ago
I'm making a solver for https://wafflegame.net
Waffle
Waffle
The waffle-shaped daily word game.
Blanwhit
BlanwhitOP4w ago
I'm done with the solver itself, but I want it to tell the user the least number of swaps to win, and how to do the swaps

Did you find this page helpful?