Original post

Hi, everybody I have a problem with merging channels, I am trying to solve a multithreading task, but testing system always gives Wrong Answer on any of my attempts. So I have code which should read values from both channels and put f(a) + f(b) to the output, n times. My basic idea presented below. It seems to work for my tests but can’t pass even the first in test system. May someone please point out mistake in my logic or give any ideas on possible solutions. Thanks!

func merge(f func(int) int, ch1 <-chan int, ch2 <-chan int, out chan int, n int)  {
         func() {
                defer close(out)
                for i := 0; i < n; i++ {
                        select {
                        case v := <-ch1:
                                out <- (f(v) + f(<-ch2))
                        case v := <-ch2:
                                out <- (f(v) + f(<-ch1))
                        }
                }
        }()
}

Is it guaranteed that both channels will always have the same number of items put in? Why not just read them in sequence?

a :=<- ch1
b :=<- ch2
out <- f(a) + f(b)

I’ ve tried this but it didn’t work:( The task description only constraint is that merge function should be non-blocking, it doesn’t mention if the channels would be the same size or not. So I am struggling with it 2 days, trying to realise which corner-cases could break my code

I don’t know the full description, though if channels don’t have at least both n items, your merge can’t work. Also, what exactly is meant by “non blocking”? Unless you use a select with a default branch, reading a channel always blocks.