Skip to content

Instantly share code, notes, and snippets.

@kiro
Created January 24, 2018 14:08
Show Gist options
  • Save kiro/82ace45fb88e8aa0c415ca73c4972f0a to your computer and use it in GitHub Desktop.
Save kiro/82ace45fb88e8aa0c415ca73c4972f0a to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
func displayDiff(oldVersion string, newVersion string) string {
fmt.Println(oldVersion, newVersion)
var f = [35][35]int{}
var ni = [35][35]int{}
var nj = [35][35]int{}
var update = func(i, j, ii, jj, v int) {
f[i][j] = v
ni[i][j] = ii
nj[i][j] = jj
}
var calc func(i, j int, os, ns string) int
calc = func(i, j int, os, ns string) int {
if f[i][j] != 0 {
return f[i][j]
}
if i == len(os) && j == len(ns) {
f[i][j] = 0
} else if i == len(os) {
f[i][j] = len(ns) - j
} else if j == len(ns) {
f[i][j] = len(os) - i
} else if os[i] == ns[j] {
f[i][j] = calc(i+1, j+1, os, ns) + 1
} else {
v := calc(len(os), j, os, ns) + len(os) - i
update(i, j, len(os), j, v)
if x := calc(i, len(ns), os, ns) + len(ns) - j; x < f[i][j] {
update(i, j, i, len(ns), x)
}
for k := len(os); k > i; k-- {
pf := calc(k, j, os, ns) + k - i
if pf < f[i][j] {
update(i, j, k, j, pf)
}
}
for k := len(ns); k > j; k-- {
pf := calc(i, k, os, ns) + k - j
if pf < f[i][j] {
update(i, j, i, k, pf)
}
}
}
return f[i][j]
}
var solution func(i, j int, os, ns string) string
solution = func(i, j int, os, ns string) string {
if i == len(os) && j == len(ns) {
return ""
} else if i == len(os) {
return "[" + ns[j:] + "]"
} else if j == len(ns) {
return "(" + os[i:] + ")"
} else if os[i] == ns[j] {
return os[i:i+1] + solution(i+1, j+1, os, ns)
} else {
if ni[i][j] == i {
return "[" + ns[j:nj[i][j]] + "]" + solution(i, nj[i][j], os, ns)
} else {
return "(" + os[i:ni[i][j]] + ")" + solution(ni[i][j], j, os, ns)
}
}
}
calc(0, 0, oldVersion, newVersion)
return solution(0, 0, oldVersion, newVersion)
}
func main() {
fmt.Println(displayDiff("_1233", "231233"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment