I would like to know if there is a better way (in the case my implementation is correct) to find a sub-sequence of integers in a given array. I have implemented the solution using golang (if this is an impediment for a review I could use a different language). If I am not mistaken the bellow implementation is close to O(b).
package main
import "fmt"
func main() {
a := []int{1, 2, 3}
b := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
r := match(a, b)
fmt.Println("Match found for case 1: ", r)
a = []int{1, 2, 3}
b = []int{4, 5, 6, 7, 8, 9}
r = match(a, b)
fmt.Println("Match found for case 2: ", r)
a = []int{1, 2, 3}
b = []int{1, 5, 3, 7, 8, 9}
r = match(a, b)
fmt.Println("Match found for case 3: ", r)
a = []int{1, 2, 3}
b = []int{4, 5, 1, 7, 3, 9}
r = match(a, b)
fmt.Println("Match found for case 4: ", r)
a = []int{1, 2, 3}
b = []int{4, 5, 6, 1, 2, 3}
r = match(a, b)
fmt.Println("Match found for case 5: ", r)
a = []int{1, 2, 3}
b = []int{1, 2, 1, 2, 3}
r = match(a, b)
fmt.Println("Match found for case 6: ", r)
a = []int{1, 2, 3, 4, 5}
b = []int{4, 1, 5, 3, 6, 1, 2, 4, 4, 5, 7, 8, 1, 2, 2, 4, 1, 3, 3, 4}
r = match(a, b)
fmt.Println("Match found for case 7: ", r)
a = []int{1, 2, 1, 2, 1}
b = []int{1, 1, 2, 2, 1, 2, 1}
r = match(a, b)
fmt.Println("Match found for case 8: ", r)
}
func match(a []int, b []int) bool {
if len(b) < len(a) {
return false
}
lb := len(b) - 1
la := len(a) - 1
i := 0
j := la
k := 0
counter := 0
for {
if i > lb || j > lb {
break
}
if b[i] != a[k] || b[j] != a[la] {
i++
j++
counter = 0
continue
} else {
i++
counter++
if k < la {
k++
} else {
k = 0
}
}
if counter >= la+1 {
return true
}
}
return counter >= la+1
}