Last active
August 29, 2015 14:06
-
-
Save margusmartsepp/bf9b258edc4bca442cc9 to your computer and use it in GitHub Desktop.
String extension Diff
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static class Extensions | |
| { | |
| public static string Diff(this string first, string second) | |
| { | |
| var s1 = first.ToCharArray(); | |
| var s2 = second.ToCharArray(); | |
| int s1P = s1.Length, s2P = s2.Length; | |
| var num = new int[s1P + 1, s2P + 1]; | |
| // fill array | |
| for (var i = 1; i <= s1P; i++) | |
| for (var j = 1; j <= s2P; j++) | |
| num[i, j] = (s1[i - 1] == (s2[j - 1]) ? 1 + num[i - 1, j - 1] | |
| : Math.Max(num[i - 1, j], num[i, j - 1])); | |
| // trace | |
| var c2 = new List<char>(); | |
| var c3 = new List<char>(); | |
| int eq = 0, eqc = 0; | |
| while (s1P != 0 && s2P != 0) | |
| { | |
| if (s1[s1P - 1] == (s2[s2P - 1])) | |
| { | |
| s1P--; | |
| s2P--; | |
| eq++; | |
| c2.Insert(0, '='); | |
| c3.Insert(0, s1[s1P]); | |
| } | |
| else if (num[s1P, s2P - 1] >= num[s1P - 1, s2P]) | |
| { | |
| s2P--; | |
| c2.Insert(0, '+'); | |
| c3.Insert(0, s2[s2P]); | |
| } | |
| else | |
| { | |
| eq++; | |
| s1P--; | |
| c2.Insert(0, '-'); | |
| c3.Insert(0, s1[s1P]); | |
| } | |
| } | |
| while (s2P-- > 0) | |
| { | |
| c2.Insert(0, '+'); | |
| c3.Insert(0, s2[s2P]); | |
| } | |
| while (eq++ < s1.Length) | |
| { | |
| c2.Insert(0, '-'); | |
| c3.Insert(eqc, s1[eqc++]); | |
| } | |
| var sb = new StringBuilder(); | |
| foreach (var t in c2) | |
| sb.Append(t); | |
| sb.Append('\n'); | |
| foreach (var t in c3) | |
| sb.Append(t); | |
| sb.Append('\n'); | |
| return sb.ToString(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment