jinhailang / blog

技术博客:知其然,知其所以然
https://github.com/jinhailang/blog/issues
60 stars 6 forks source link

面试汇总 #40

Open jinhailang opened 6 years ago

jinhailang commented 6 years ago

面试汇总

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

某电商/平台容器调度

在线编程题

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

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")
}
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.")
}