From 75f80ae39ff975fa46721a925d0a8d41fab95245 Mon Sep 17 00:00:00 2001 From: stephen mcquay Date: Fri, 4 May 2018 21:45:21 -0700 Subject: [PATCH] init --- LICENSE | 20 ++++++++++++++++++++ README.md | 3 +++ main.go | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+) create mode 100644 LICENSE create mode 100644 README.md create mode 100644 main.go diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5996d0b --- /dev/null +++ b/LICENSE @@ -0,0 +1,20 @@ +MIT License +Copyright (c) 2018 Stephen McQuay + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..1583f42 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# smerge + +This answers an interview question diff --git a/main.go b/main.go new file mode 100644 index 0000000..7682e49 --- /dev/null +++ b/main.go @@ -0,0 +1,56 @@ +package main + +import ( + "fmt" + "math/rand" + "sort" + "sync" + "time" +) + +func main() { + for i := range merge(source(5), source(10), source(20)) { + fmt.Printf("%20d\n", i) + } +} + +func source(c int) <-chan int { + out := make(chan int) + go func() { + vals := make([]int, c) + src := rand.New(rand.NewSource(time.Now().UnixNano())) + for i := 0; i < c; i++ { + vals[i] = src.Int() + } + + sort.Ints(vals) + + for _, i := range vals { + out <- i + } + close(out) + }() + return out +} + +func merge(cs ...<-chan int) <-chan int { + wg := sync.WaitGroup{} + out := make(chan int) + + output := func(c <-chan int) { + for n := range c { + out <- n + } + wg.Done() + } + + wg.Add(len(cs)) + for _, c := range cs { + go output(c) + } + go func() { + wg.Wait() + close(out) + }() + return out +}