Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

面试汇总 #40

Open
jinhailang opened this issue Oct 10, 2018 · 0 comments
Open

面试汇总 #40

jinhailang opened this issue Oct 10, 2018 · 0 comments

Comments

@jinhailang
Copy link
Owner

jinhailang commented Oct 10, 2018

面试汇总

这几年经历过不少面试,记录下来,偶尔看看,每次体验应该都会不一样吧。

某电商/平台容器调度

在线编程题

由于时间有限,写的比较仓促,基本满足要求。

  • 请实现两个线程,使之交替打印1-100,如:两个线程分别为:Printer1+和+Printer2,最后输出结果为:

Printer1--1
Printer2--2
Printer1--3
Printer2--4

package main

import (
	"fmt"
	"time"
)

const (
	total = 100
)

//Printer1

func Printer1(a, b chan int) {
	for i := range a {
		if i > 100 {
			return
		}

		fmt.Printf("Printer1--%d\r\n", i)
		b <- i + 1
	}
}

func Printer2(a, b chan int) {
	for i := range a {
		if i > 100 {
			return
		}

		fmt.Printf("Printer2--%d\r\n", i)
		b <- i + 1
	}
}

func main() {
	a := make(chan int)
	b := make(chan int)

	go Printer1(a, b)
	go Printer2(b, a)

	a <- 0

	time.Sleep(time.Millisecond * 10) //阻塞

	close(a)
	close(b)

	fmt.Printf("exit\n")
}
  • 设计并实现一个程序,达到和下面的 shell 命令相同的效果:
    cat /home/admin/logs/data.log | grep alibaba | sort | uniq -c | sort -nr
package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"sort"
	"strings"
)

const (
	LOG = "/Users/jinhailang/Desktop/test.txt" //"/home/admin/logs/data.log"
)

func cat(path, key string) ([]string, error) {
	var ss []string

	fi, err := os.Open(LOG)
	if err != nil {
		fmt.Printf("Open error: %v\n", err)
		return nil, err
	}

	defer fi.Close()

	br := bufio.NewReader(fi)
	for {
		a, _, c := br.ReadLine()
		if c == io.EOF {
			break
		}

		s := string(a)
		if strings.Contains(s, key) {
			ss = append(ss, s)
		}
	}

	fmt.Println("ss: ", ss)

	return ss, nil
}

func uniq(ss []string) map[string]int {
	mp := make(map[string]int)

	for _, s := range ss {
		count, ok := mp[s]
		if ok {
			count++
			mp[s] = count
		} else {
			mp[s] = 1
		}
	}

	return mp
}

type kv struct {
	K string
	V int
}

type kvs []kv

func (p kvs) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p kvs) Len() int           { return len(p) }
func (p kvs) Less(i, j int) bool { return p[i].V < p[j].V }

func sort_nr(mp map[string]int) []kv {
	p := make(kvs, len(mp))
	i := 0
	for k, v := range mp {
		p[i] = kv{k, v}
		i = i + 1
	}

	sort.Sort(p)

	return p
}

func main() {
	ss, _ := cat(LOG, "alibaba")

	sort.Strings(ss)
	fmt.Println("sort after ss: ", ss)

	mp := uniq(ss)
	fmt.Println("uniq after mp: ", mp)

	kk := sort_nr(mp)
	fmt.Println("sort_nr after kk: ", kk)

	fmt.Println("exit.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant