1. 程式人生 > >從一副撲克中隨機抽5張,並輸出結果是不是順子?(時間60分鐘)

從一副撲克中隨機抽5張,並輸出結果是不是順子?(時間60分鐘)


    剛看到這題目時我心理活動是,這太特麼簡單了好嗎 這題拿來考人?
    結果後面做的亂七八糟的,有些問題也沒考慮到。回家之後重新想了下,總算輸出正常了。
    用最土的辦法,過程如下: 先把牌拼出來,隨機生成5張,再讓正序排列,
    使用字串函式檢查是否存在於2345678910JQKA,然後輸出。

<?php


/*拼出52張牌*/
$pk = [
"紅"=>[2,3,4,5,6,7,8,9,10,'J','Q','K','A'],
"黑"=>[2,3,4,5,6,7,8,9,10,'J','Q','K','A'],
"方"=>[2,3,4,5,6,7,8,9,10,'J','Q','K','A'],
"梅"=>[2,3,4,5,6,7,8,9,10,'J','Q','K','A'],
];

foreach ($pk as $key => $value) {
	foreach ($value as $k => $v) {
		$array[]= $key.'-'.$v;
	}
}

/*抽出五張*/
for($i=0;$i<5;$i++){
	$rand_number2[] = $array[array_rand($array)];
}

// $rand_number2=["黑-K","紅-J","梅-9","紅-10","方-Q"]; //順子測試案例
foreach ($rand_number2 as $key => $value) {
	$string = explode('-', $value);
	$str_color[] =$string[0];
	$str_num[] = $string[1];
	$color_num .= $string[0].' '.$string[1].'  ,   '; 
}

/*判斷撲克數量*/
if(count($str_num)!=5){
	echo '發牌數量錯誤';
	die;
}

/*檢查是否順子*/
sort($str_num);
$arr_to_str2 = intval(implode('', $str_num));
$sort_pk = ["J"=>"","Q"=>"","K"=>"","A"=>""];

foreach ($str_num as $value) {
	if($value=='J' || $value=='Q' || $value=='K' || $value=='A' ){
		$sort_pk[$value]=$value;
	}
}
foreach ($sort_pk as $value) {
	$arr_to_str2 .= $value;
}
print_r($arr_to_str2);

$pk = '2345678910JQKA';
$pos = strpos($pk,$arr_to_str2);

print_r($color_num);
echo "<br>";
if($pos===false && $arr_to_str2!='2345A'){
	echo "不是順子";
}else{
	echo '是順子';
}

輸出結果:

紅 6 , 紅 Q , 梅 1 , 梅 J , 黑 5 ,

不是順子