Monday Mini-Golf: A series of short code-golf challenges, posted (hopefully!) every Monday.
(Sorry this one's a little late.)
I'm sure most of you folks have heard of Levenshtein distance, an algorithm for calculating the distance between two strings. Well, this challenge is about implementing a similar algorithm of my own invention*, called anagram distance. The main difference is that the order of the characters doesn't matter; instead, only the characters that are unique to one string or the other are measured.
Challenge
The goal of the challenge is to write a program or function that takes in two strings and returns the anagram distance between them. The main way to do this is to use the following logic:
- Convert both strings to lowercase and (optionally) sort each one's characters alphabetically.
- While the strings contain at least one equal character, remove the first instance of this character from each string.
- Add the lengths of the remaining strings and return/output the result.
Example
If the inputs are:
Hello, world!
Code golf!
Then, lowercased and sorted, these become: (by JS's default sort; note the leading spaces)
!,dehllloorw
!cdefgloo
Removing all of the characters that are in both strings, we end up with:
,hllrw
cfg
Thus, the anagram distance between the original two strings = 6 + 3 = 9.
Details
- The strings may be taken in any sensible format.
- The strings will consist only of printable ASCII.
- The strings themselves will not contain any whitespace other than regular spaces. (No tabs, newlines, etc.)
- You need not use this exact algorithm, as long as the results are the same.
Test-cases
Input 1:
Hello, world!
Code golf!
Output 1:
9
Input 2:
12345 This is some text.
.txet emos si sihT 54321
Output 2:
0
Input 3:
All unique characters here!
Bdfgjkmopvwxyz?
Output 3:
42
Input 4:
This is not exactly like Levenshtein distance,
but you'll notice it is quite similar.
Output 4:
30
Input 5:
all lowercase.
ALL UPPERCASE!
Output 5:
8
Scoring
This is code-golf, so shortest valid code in bytes wins. Tiebreaker goes to submission that reached its final byte count first. The winner will be chosen next Monday, Oct 12. Good luck!
Edit: Congrats to the winner, @isaacg, using Pyth (again) for an astounding 12 bytes!
*If this algorithm has been used elsewhere and/or given another name, please let me know! I wasn't able to find it with a 20-minute search.