Commit | Line | Data |
---|---|---|
6dd70280 JL |
1 | package com.swabunga.spell.engine;\r\r |
2 | \r\r | |
3 | import java.io.BufferedReader;\r\r | |
4 | import java.io.InputStreamReader;\r\r | |
5 | \r\r | |
6 | /** JMH Again, there is no need to have a global class matrix variable\r\r | |
7 | * in this class. I have removed it and made the getDistance static final\r\r | |
8 | */\r\r | |
9 | public class EditDistance {\r\r | |
10 | \r\r | |
11 | public static Configuration config = Configuration.getConfiguration();\r\r | |
12 | \r\r | |
13 | public static final int getDistance(String word, String similar) {\r\r | |
14 | int a_size = word.length() + 1;\r\r | |
15 | int b_size = similar.length() + 1;\r\r | |
16 | int[][] matrix = new int[a_size][b_size];\r\r | |
17 | matrix[0][0] = 0;\r\r | |
18 | for (int j = 1; j != b_size; ++j)\r\r | |
19 | matrix[0][j] = matrix[0][j - 1] + config.getInteger(Configuration.EDIT_DEL1);\r\r | |
20 | word = " " + word;\r\r | |
21 | similar = " " + similar;\r\r | |
22 | int te;\r\r | |
23 | for (int i = 1; i != a_size; ++i) {\r\r | |
24 | matrix[i][0] = matrix[i - 1][0] + config.getInteger(Configuration.EDIT_DEL2);\r\r | |
25 | for (int j = 1; j != b_size; ++j) {\r\r | |
26 | if (word.charAt(i) == similar.charAt(j)) {\r\r | |
27 | matrix[i][j] = matrix[i - 1][j - 1];\r\r | |
28 | } else {\r\r | |
29 | matrix[i][j] = config.getInteger(Configuration.EDIT_SUB) + matrix[i - 1][j - 1];\r\r | |
30 | if (i != 1 && j != 1 &&\r\r | |
31 | word.charAt(i) == similar.charAt(j - 1) && word.charAt(i - 1) == similar.charAt(j)) {\r\r | |
32 | te = config.getInteger(Configuration.EDIT_SWAP) + matrix[i - 2][j - 2];\r\r | |
33 | if (te < matrix[i][j]) matrix[i][j] = te;\r\r | |
34 | }\r\r | |
35 | te = config.getInteger(Configuration.EDIT_DEL1) + matrix[i - 1][j];\r\r | |
36 | if (te < matrix[i][j]) matrix[i][j] = te;\r\r | |
37 | te = config.getInteger(Configuration.EDIT_DEL2) + matrix[i][j - 1];\r\r | |
38 | if (te < matrix[i][j]) matrix[i][j] = te;\r\r | |
39 | }\r\r | |
40 | }\r\r | |
41 | }\r\r | |
42 | return matrix[a_size - 1][b_size - 1];\r\r | |
43 | }\r\r | |
44 | \r\r | |
45 | public static void main(String[] args) throws Exception {\r\r | |
46 | EditDistance ed = new EditDistance();\r\r | |
47 | BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));\r\r | |
48 | String input = "";\r\r | |
49 | String input2 = "";\r\r | |
50 | while (input != null) {\r\r | |
51 | input = stdin.readLine();\r\r | |
52 | input2 = stdin.readLine();\r\r | |
53 | System.out.println(ed.getDistance(input, input2));\r\r | |
54 | }\r\r | |
55 | }\r\r | |
56 | }\r\r | |
57 | \r\r | |
58 | \r\r |