抽奖基本原理
seeds=`cat wx.txt`
seeds=`for seed in $seeds;do (($RANDOM%2==0)) && echo $seed; done`
a && b
- 如果a或者b有一个是false,那么结果就是false
- 如果a或者b都是true,那么结果就是true
true && b
false && b :短路
vim
vim ~/.vimrc
set nu
抽奖实现1:有空白
#!/bin/bash
rand() {
#bug 1
seeds=`while read line; do echo ${line// /..}; done < wx.txt`
while [[ $count != 1 ]];do
seeds=`for seed in $seeds;do (($RANDOM%2==0)) && echo $seed; done`
count=`echo "$seeds" | wc -l`
done
#bug3
echo $seeds
}
rand
抽奖实现2:无空白
#!/bin/bash
rand() {
local count
local seeds
count=0
seeds=`while read line; do echo ${line// /..}; done < wx.txt`
while [[ $count != 1 ]];do
seeds=`for seed in $seeds;do (($RANDOM%2==0)) && echo $seed; done`
count=`echo "$seeds" | wc -l`
done
if [[ $seeds == "" ]];then
rand
fi
if [[ $seeds != "" ]];then
echo $seeds
fi
}
抽奖实现3:去重
此处代码跟课上不一样,课上的代码在is_repeat函数有一些错误!!跟同学们说声抱歉,是我失误了
rand() {
local seeds
local count
count=0
seeds=`while read line;do echo ${line// /..}; done<test.txt`
while [[ $count != 1 ]];do
seeds=`for seed in $seeds;do (($RANDOM%2==0)) && echo $seed;done`
count=`echo "$seeds" | wc -l`
done
if [[ $seeds == "" ]];then
rand
fi
if [[ $seeds != "" ]];then
echo $seeds
fi
}
res() {
for i in `eval echo {1..$1}`;do
tmp=`rand`
while [[ `is_repeat $tmp` == 0 ]];do
tmp=`rand`
done
arrs[$i]=$tmp
done
echo ${arrs[@]}
}
is_repeat() {
for arr in ${arrs[@]};do
if [[ $arr == $1 ]];then
#此处需要有echo,因为子进程只能捕获echo的输出,不能捕获return的值
echo 0
return 0
fi
done
#输出1的逻辑在这里,因为需要遍历完整的数组后,才能输出1
echo 1
}
res $1
抽象实现4:参数化
res() {
for((i=0;i<$1;i++));do
tmp=`rand`
while [[ `is_repeat $tmp` ]];do
tmp=`rand`
done
arrs[$i]=$tmp
done
echo ${arrs[@]}
}
res $1
结果
- 通通 :5
- 平庸与浩荡:10
- 安灵:15
- 沨晴: 20
- 唐嘻嘻: 25
- 提摩太: 30