Skip to content

Instantly share code, notes, and snippets.

@hanksudo
Created August 18, 2021 13:26
Show Gist options
  • Save hanksudo/d0fab5d00d7cb51f1374f9ecfe6ad7af to your computer and use it in GitHub Desktop.
Save hanksudo/d0fab5d00d7cb51f1374f9ecfe6ad7af to your computer and use it in GitHub Desktop.
(go) combine two array and keep order
package main
import "log"
func main() {
result := combineAndKeepOrder([]string{"a", "b", "c"}, []string{"c", "a", "d"})
log.Println(result, testEq(result, []string{"c", "b", "a", "d"}))
result = combineAndKeepOrder([]string{}, []string{"c", "a", "d"})
log.Println(result, testEq(result, []string{"c", "a", "d"}))
result = combineAndKeepOrder([]string{"a", "b", "c"}, []string{"d", "a", "c"})
log.Println(result, testEq(result, []string{"d", "b", "a", "c"}))
result = combineAndKeepOrder([]string{"a", "b", "c"}, []string{})
log.Println(result, testEq(result, []string{"a", "b", "c"}))
}
func combineAndKeepOrder(origins []string, new []string) []string {
position := 0
for idxO, k := range origins {
for _, v := range new {
if v == k {
origins[idxO] = new[position]
position++
break
}
}
}
if position < len(new) {
origins = append(origins, new[position:]...)
}
return origins
}
func testEq(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment