Diff 的全部源码如下:
import Java.io.*;
import java.util.*;
public class Diff {
protected enum Operation {
COPY(1), INSERT(1), DELETE(1);
/**
* 操作的代价
*/
private int price;
private Operation(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
}
/**
* 旧版本
*/
protected List<String> src;
/**
* 新版本
*/
protected List<String> dest;
/**
* 最小代价
*/
protected int[][] minPrice;
/**
* 获得最小代价所采取的操作
*/
protected Operation[][] ops;
/**
* 读文本文件为一行一行的字符串
*/
protected List<String> readLines(String path) {
List<String> ans = new ArrayList<String>();
try {
BufferedReader in = new BufferedReader(new FileReader(path));
String line;
while ((line = in.readLine()) != null)
ans.add(line);
in.close();
} catch (FileNotFoundException e) {
ans = null;
} catch (IOException e) {
ans = null;
}
return ans;
}
/**
* 把新旧版本读入
*/
public void readFiles(String srcPath, String destPath) {
src = this.readLines(srcPath);
dest = this.readLines(destPath);
}
/**
* 判断旧版本第i行和新版本第j行是否相等,<b>利用了哈希值减少不必要的字符串全比较</b>
*/
protected boolean lineEqual(int i, int j) {
String s = src.get(i);
String d = dest.get(j);
if (s.hashCode() != d.hashCode())
return false;
return s.equals(d);
}
/**
* 计算最小代价修改方案(动态规划)
*/
public void minModifyPrice() {
int n = src.size();
int m = dest.size();
int i, j;// 新旧版本下标
minPrice = new int[n + 1][m + 1];
ops = new Operation[n + 1][m + 1];
// 初始化全添加、全删除的行列
for (j = m; j >= 0; j--) {
ops[n][j] = Operation.INSERT;
minPrice[n][j] = (m - j) * Operation.INSERT.getPrice();
}
for (i = n - 1; i >= 0; i--) {
ops[i][m] = Operation.DELETE;
minPrice[i][m] = (n - i) * Operation.DELETE.getPrice();
}
for (i = n - 1; i >= 0; i--)
for (j = m - 1; j >= 0; j--) {
int insertPrice = Operation.INSERT.getPrice()
+ minPrice[i][j + 1];
int deletePrice = Operation.DELETE.getPrice()
+ minPrice[i + 1][j];
int copyPrice = Operation.COPY.getPrice()
+ minPrice[i + 1][j + 1];
int lower;
if (insertPrice < deletePrice) {
ops[i][j] = Operation.INSERT;
lower = minPrice[i][j] = insertPrice;
} else {
ops[i][j] = Operation.DELETE;
lower = minPrice[i][j] = deletePrice;
}
if (copyPrice < lower && this.lineEqual(i, j)) {
ops[i][j] = Operation.COPY;
minPrice[i][j] = copyPrice;
}
}
}
/**
* 打印结果
*/
public void printResult() {
int n = src.size();
int m = dest.size();
int i = 0, j = 0;// 新旧版本下标
while (i != n || j != m) {
switch (ops[i][j]) {
case INSERT:
System.out.printf(" %4d + %s\n", j + 1, dest.get(j));
j++;
break;
case DELETE:
System.out.printf("%4d - %s\n", i + 1, src.get(i));
i++;
break;
case COPY:
System.out.printf("%4d %4d %s\n", i + 1, j + 1, dest.get(j));
i++;
j++;
break;
}
}
}
/**
* @param args
* args[0] 是旧版本路径,<br>
* args[1] 是新版本路径
*/
public static void main(String[] args) {
Diff d = new Diff();
d.readFiles(args[0], args[1]);
d.minModifyPrice();
d.printResult();
}
}
采用动态规划后,求 minPrice 的复杂度为 O(n^2),一般源文件就几百行的样子,因此,几个毫秒就能算出步骤数最少的修改方案。
git 只要把最佳修改方案中的 insert、delete 操作存储起来,做为被管理的软件大夏的一块砖。但实际上git怎么存储各个版本的,还没研究过o(╯□╰)o
