Skip to content

Instantly share code, notes, and snippets.

@mentix02
Created March 30, 2020 09:45
Show Gist options
  • Save mentix02/af8578df8bc7f0e972bf31b07d179cb9 to your computer and use it in GitHub Desktop.
Save mentix02/af8578df8bc7f0e972bf31b07d179cb9 to your computer and use it in GitHub Desktop.
Go concurrent linear search with Python verification and test generation
import random
if __name__ == '__main__':
nums = [str(random.randint(0, 100000)) for _ in range(100)]
toFind = random.choice(nums)
ans = open('ans.txt', 'w+')
ans.write(str(nums.index(toFind)) + '\n')
ans.close()
print(toFind + ' ' + ' '.join(nums))
go run search.go `python genTests.py` && cat ans.txt
package main
import (
"fmt"
"os"
"strconv"
)
func simpleLinSearch(slice []int, num int, c chan int, start int) {
for index, item := range slice {
if item == num {
c <- index + start
return
}
}
c <- -1
}
func search(slice []int, num int) int {
c := make(chan int)
go simpleLinSearch(slice[:len(slice)/2], num, c, 0)
go simpleLinSearch(slice[len(slice)/2:], num, c, len(slice)/2)
x, y := <-c, <-c
if x == -1 {
return y
} else {
return x
}
}
func toNums(nums []string) []int {
res := make([]int, len(nums), len(nums))
for index, item := range nums {
n, _ := strconv.Atoi(item)
res[index] = n
}
return res
}
func main() {
nums := toNums(os.Args[1:])
fmt.Printf("%d\n", search(nums[1:], nums[0]))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment