001package squidpony;
002
003import java.util.HashMap;
004import java.util.Map;
005
006/**
007 * The Damerau-Levenshtein Algorithm is an extension to the Levenshtein
008 * Algorithm which solves the edit distance problem between a source string and
009 * a target string with the following operations:
010 *
011 * <ul>
012 * <li>Character Insertion</li>
013 * <li>Character Deletion</li>
014 * <li>Character Replacement</li>
015 * <li>Adjacent Character Swap</li>
016 * </ul>
017 *
018 * Note that the adjacent character swap operation is an edit that may be
019 * applied when two adjacent characters in the source string match two adjacent
020 * characters in the target string, but in reverse order, rather than a general
021 * allowance for adjacent character swaps.
022 *
023 * This implementation allows the client to specify the costs of the various
024 * edit operations with the restriction that the cost of two swap operations
025 * must not be less than the cost of a delete operation followed by an insert
026 * operation. This restriction is required to preclude two swaps involving the
027 * same character being required for optimality which, in turn, enables a fast
028 * dynamic programming solution.
029 *
030 * The running time of the Damerau-Levenshtein algorithm is O(n*m) where n is
031 * the length of the source string and m is the length of the target string.
032 * This implementation consumes O(n*m) space, none of which is cached for
033 * future executions. Heavy usage may be taxing on the garbage collector.
034 * 
035* @author Kevin L. Stern
036 */
037public class DamerauLevenshteinAlgorithm {
038
039    private final int deleteCost, insertCost, replaceCost, swapCost;
040
041    /**
042     * Constructor.
043     *     
044* @param deleteCost the cost of deleting a character.
045     * @param insertCost the cost of inserting a character.
046     * @param replaceCost the cost of replacing a character.
047     * @param swapCost the cost of swapping two adjacent characters.
048     */
049    public DamerauLevenshteinAlgorithm(int deleteCost, int insertCost, int replaceCost, int swapCost) {
050        /*
051         * Required to facilitate the premise to the algorithm that two swaps of
052         * the same character are never required for optimality.
053         */
054        if (2 * swapCost < insertCost + deleteCost) {
055            throw new IllegalArgumentException("Unsupported cost assignment");
056        }
057        this.deleteCost = deleteCost;
058        this.insertCost = insertCost;
059        this.replaceCost = replaceCost;
060        this.swapCost = swapCost;
061    }
062
063    /**
064     * Compute the Damerau-Levenshtein distance between the specified source
065     * string and the specified target string.
066     */
067    public int execute(CharSequence source, CharSequence target) {
068        if (source.length() == 0) {
069            return target.length() * insertCost;
070        }
071
072        if (target.length() == 0) {
073            return source.length() * deleteCost;
074        }
075
076        int[][] table = new int[source.length()][target.length()];
077        Map<Character, Integer> sourceIndexByCharacter = new HashMap<>();
078
079        if (source.charAt(0) != target.charAt(0)) {
080            table[0][0] = Math.min(replaceCost, deleteCost + insertCost);
081        }
082
083        sourceIndexByCharacter.put(source.charAt(0), 0);
084
085        for (int i = 1; i < source.length(); i++) {
086            int deleteDistance = table[i - 1][0] + deleteCost;
087            int insertDistance = (i + 1) * deleteCost + insertCost;
088            int matchDistance = i * deleteCost
089                    + (source.charAt(i) == target.charAt(0) ? 0 : replaceCost);
090            table[i][0] = Math.min(Math.min(deleteDistance, insertDistance),
091                    matchDistance);
092        }
093
094        for (int j = 1; j < target.length(); j++) {
095            int deleteDistance = table[0][j - 1] + insertCost;
096            int insertDistance = (j + 1) * insertCost + deleteCost;
097            int matchDistance = j * insertCost
098                    + (source.charAt(0) == target.charAt(j) ? 0 : replaceCost);
099            table[0][j] = Math.min(Math.min(deleteDistance, insertDistance),
100                    matchDistance);
101        }
102
103        for (int i = 1; i < source.length(); i++) {
104            int maxSourceLetterMatchIndex = source.charAt(i) == target
105                    .charAt(0) ? 0 : -1;
106            for (int j = 1; j < target.length(); j++) {
107                Integer candidateSwapIndex = sourceIndexByCharacter.get(target
108                        .charAt(j));
109                int jSwap = maxSourceLetterMatchIndex;
110                int deleteDistance = table[i - 1][j] + deleteCost;
111                int insertDistance = table[i][j - 1] + insertCost;
112                int matchDistance = table[i - 1][j - 1];
113                if (source.charAt(i) != target.charAt(j)) {
114                    matchDistance += replaceCost;
115                } else {
116                    maxSourceLetterMatchIndex = j;
117                }
118                int swapDistance;
119                if (candidateSwapIndex != null && jSwap != -1) {
120                    int iSwap = candidateSwapIndex;
121                    int preSwapCost;
122                    if (iSwap == 0 && jSwap == 0) {
123                        preSwapCost = 0;
124                    } else {
125                        preSwapCost = table[Math.max(0, iSwap - 1)][Math.max(0,
126                                jSwap - 1)];
127                    }
128                    swapDistance = preSwapCost + (i - iSwap - 1) * deleteCost
129                            + (j - jSwap - 1) * insertCost + swapCost;
130                } else {
131                    swapDistance = Integer.MAX_VALUE;
132                }
133                table[i][j] = Math.min(
134                        Math.min(Math.min(deleteDistance, insertDistance),
135                                matchDistance), swapDistance);
136            }
137            sourceIndexByCharacter.put(source.charAt(i), i);
138        }
139        return table[source.length() - 1][target.length() - 1];
140    }
141}