Linux与Shell实战(二)

抽奖基本原理
抽奖实现1:有空白
抽奖实现2:无空白
抽奖实现3:去重
抽象实现4:参数化

第一个版本:有空

rand() {
    local seeds=`while read line; do echo ${line// /..}; done <lagou2.txt`
    local count=0
    #缩小范围
    while [[ $count != 1 ]]; do
        seeds=`for seed in $seeds; do (( $RANDOM % 2 )) && echo $seed; done`
        count=`echo "$seeds"|wc -l`
    done 
    echo $seeds
}
rand

第二个版本:去掉空

rand() {
    local seeds=`while read line; do echo ${line// /..}; done <lagou2.txt`
    local count=0
    #缩小范围
    while [[ $count != 1 ]]; do
        seeds=`for seed in $seeds; do (( $RANDOM % 2 )) && echo $seed; done`
        count=`echo "$seeds"|wc -l`
    done 
    if [[  $seeds == "" ]]; then
        rand
    else
        echo $seeds
    fi
}
rand

第三个版本: 多同学

rand() {
    local seeds=`while read line; do echo ${line// /..}; done <lagou2.txt`
    local count=0
    #缩小范围
    while [[ $count != 1 ]]; do
        seeds=`for seed in $seeds; do (( $RANDOM % 2 )) && echo $seed; done`
        count=`echo "$seeds"|wc -l`
    done 
    if [[  $seeds == "" ]]; then
        rand
    else
        echo $seeds
    fi
}

function res() {
    for((i=0;i<10;i++)); do
        tmp=`rand`
        while [[ `is_repeat $tmp` == 0 ]]; do
          tmp=`rand`
        done
        arrs[i]=$tmp
    done
    echo ${arrs[@]}
}

function is_repeat() {
    for arr in ${arrs[@]}; do
      if [[ $arr == $1 ]]; then
        echo 0
        return 0
      fi
    done
    echo 1
}

res

第四个版本:参数化

rand() {
    local seeds=`while read line; do echo ${line// /..}; done <lagou2.txt`
    local count=0
    #缩小范围
    while [[ $count != 1 ]]; do
        seeds=`for seed in $seeds; do (( $RANDOM % 2 )) && echo $seed; done`
        count=`echo "$seeds"|wc -l`
    done 
    if [[  $seeds == "" ]]; then
        rand
    else
        echo $seeds
    fi
}

function res() {
    for((i=0;i<$1;i++)); do
        tmp=`rand`
        while [[ `is_repeat $tmp` == 0 ]]; do
          tmp=`rand`
        done
        arrs[i]=$tmp
    done
    echo ${arrs[@]}
}

function is_repeat() {
    for arr in ${arrs[@]}; do
      if [[ $arr == $1 ]]; then
        echo 0
        return 0
      fi
    done
    echo 1
}

res $1

中奖同学名单15元:
leo
_
随风而去
大脸猫cedhi
zhenzhen

关闭