Created
March 30, 2020 09:45
-
-
Save mentix02/af8578df8bc7f0e972bf31b07d179cb9 to your computer and use it in GitHub Desktop.
Go concurrent linear search with Python verification and test generation
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
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)) |
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
go run search.go `python genTests.py` && cat ans.txt |
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
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