前言
前几天发现了一个shell的考试题,顺便做了会。在这里记录一下。
题目
一个shell脚本
#!/bin/bash points=(2 3 4 5 6 7 8 9 10 "J" "Q" "K" "A") #点数 spec=("红桃" "黑桃" "方块" "梅花") #花色 poker=() ## 将点数和花色组成一副扑克 function makepoker(){ v=0; for i in ${points[@]};do for j in ${spec[@]};do v=$(($v+1)); if [[ $j == "红桃" || $j == "方块" ]];then poker[$v]="\033[33m"$j"=>"$i"\033[0m"; else poker[$v]=$j"=>"$i; fi done; done; } ## 使用递归函数,生成随机扑克索引 function seed_random(){ if [[ ${#poker[@]} != 0 ]];then if [[ ${#porker[@]} == 1 ]];then return 0 else k=$(rand 0 52); #echo $k if [[ ${poker[$k]} == "" ]] ;then # 当随机数不再数组时在生成一个随机数,直到随机数为数组的索引,且值不为空 seed_random else echo $k; return; fi fi else return 0; fi } ## 生成0-52的随机数 function rand(){ min=$1 max=$(($2-$min+1)) num=$(date +%s%N) echo $(($num%$max+$min)) } ## 随机发牌 function deal_cards(){ echo "开始随机发牌......" for i in {1..4};do printf "玩家(${i})抓牌:\n\n" for j in {1..13};do kv=$(seed_random) printf "%10s${j} %s\033[03m"${poker[$kv]}"\033[0m\n" unset poker[$kv] #将发出的牌删除 done; printf "\n" done; } echo "正在洗牌......" makepoker deal_cards
执行结果:
......
闲的用js又写了一个
#!/usr/bin/node spec=["黑桃","\033[33m红桃\033[0m","\033[33m方块\033[0m","梅花"]; points=[2,3,4,5,6,7,8,9,10,"J","Q","K","A"]; poker=[] selected_i=[]; //组牌 function makepoker(){ poker=[]; for(var i=0;i<points.length;i++){ for(var j=0;j<spec.length;j++){ poker.push(spec[j]+":"+points[i]); } } } //生成随机数 function random(){ if(poker.length != 0){ var k =Math.round( 1+Math.random() * poker.length); if(poker.length == 1) return 0; if(poker[k] == undefined){ return random(); } return k; }else{ return; } } //发牌 function deal_card(){ makepoker(); console.log("正在洗牌......."); poker.sort((x,y)=>(1+Math.random() * 52)-(1+Math.random() * 52)); //洗牌 console.log("开始随机发牌......") for(var j=0;j<4;j++){ console.log("玩家"+(j+1)+" 抓牌:"); for(var i=0;i<13;i++){ var k=random(); console.log("\t "+(i+1)+"\t => ",poker[k]); poker.splice(k,1); //将发出的牌删除 } } } deal_card();原文链接:https://www.f2er.com/bash/389219.html