百度golang开发实习生一面算法题

算法题:用协程交替打印1~8和"a"~"f"

package main

import (
	"fmt"
	"sync"
)

var wg sync.WaitGroup

func main() {
	arrChan := make(chan int, 8)
	strChan := make(chan rune, 6)
	wg.Add(1)
	go PrintArr(arrChan, &wg)
	wg.Add(1)
	go PrintStr(strChan, &wg)
	for i, j := 0, 0; i < 8 && j < 6; {
		x := <-arrChan
		fmt.Println(x)
		i++
		if j < 5 {
			y := <-strChan
			fmt.Println(string(y))
			j++
		}
	}
	wg.Wait()
	close(arrChan)
	close(strChan)
}

func PrintArr(arrChan chan int, wg *sync.WaitGroup) {
	defer wg.Done()
	for i := 1; i <= 8; i++ {
		arrChan <- i
	}
}

func PrintStr(strChan chan rune, wg *sync.WaitGroup) {
	defer wg.Done()
	for i := 'a'; i <= 'f'; i++ {
		strChan <- i
	}
}

你可能感兴趣的:(面试算法题,golang,算法,开发语言)