2020-11-21 芯片测试golang实现

//思路:参考Mood  清华大学《算法与分析》汪小林 第三周:分支策略(2) 3.4芯片测试
//时间复杂度O(n)

https://www.icourse163.org/learn/PKU-1002525003?tid=1450408483#/learn/content?type=detail&id=1214976926&cid=1219230271

func main() {
    //true:好芯片,false:坏芯片
    //chips := []bool{true,false,true}
    chips := []chip{
   
   {
        good: false,
        num:  0,
    },{
        good: false,
        num:  1,
    },{
        good: false,
        num:  2,
    },{
        good: false,
        num:  3,
    },{
        good: true,
        num:  4,
    },{
        good: true,
        num:  5,
    },{
        good: true,
        num:  6,
    },{
        good: true,
        num:  7,
    },{
        good: true,
        num:  8,
    }}
    fmt.Println(getGoodChip(chips))
}

type chip struct {
    good bool
    num int
}

//return good chip index
func getGoodChip(chips []chip) int{

    if len(chips) == 3 {
        if judge(chips[0].good,chips[1].good){
            return chips[0].num
        }else {
            return chips[2].num
        }
    }

    if len(chips) <=2 {
        return chips[0].num
    }

    if len(chips) %2 == 0{
        return getGoodChip(evenChips(chips))
    }
    return getGoodChip(oddChips(chips))

}

func evenChips(theChips []chip) []chip {
    newChips := []chip{}
    for i:=0; i<len(theChips) ;i+=2 {
        if judge(theChips[i].good, theChips[i+1].good){
            newChips = append(newChips, theChips[i])
        }
    }
    return newChips
}

func oddChips(theChips []chip) []chip {
    candChip := theChips[0]
    n := len(theChips)
    goodNum := 0
    for i:=1;i<n ; i++  {
        if judge(candChip.good,theChips[i].good){
            goodNum++
        }
    }
    if goodNum >= (n-1)/2 {//find good chip ,return it.End.
        return []chip{candChip}
    }
    //else candChip is a bad chip ,abandon it
    return theChips[1:]
}
//1:芯片x判断芯片y为好芯片,否则为0
func judge(a,b bool)bool{
    if a && b {
        return true
    }
    if !a && !b {
        aRand := rand.Intn(2)
        bRand := rand.Intn(2)
        if aRand ==1 && bRand ==1{
            return true
        }else{
            return false
        }
    }
    return false
}

猜你喜欢

转载自blog.csdn.net/qq_21514303/article/details/109900049