三個數的和在一個範圍裡,求3個數

來源:互聯網
上載者:User
3個數的和在一個範圍裡,求3個數
這3個數的取值範圍是1-6,必定是整數

第一種情況,3個數的和取值範圍4-10,隨機產生這3個數(分3個數可以全部重複和不可以全部重複兩種情況)

第二種情況,3個數的和取值範圍11-17,隨機產生這3個數(分3個數可以全部重複和不可以全部重複兩種情況)


舉例說明:
如果允許全部重複,那麼如果3個數的和是15,那麼3個數可能是5,5,5,而如果不允許全部重複,
3個數只可能是4,5,6或,6,6,3或3,6,6之類的組合

求一個函數,

//根據給出的和,和是否允許3個數完全相同3個數的數組,
//要求必須能否返回所有可能的組合,比如6,6,3和3,6,6都必須有可能返回。
//程式只要求隨機返回所有可能性組合之一即可。
function get3nums($第幾種情況,$是否允許全部重複)
//比如list($rand1,$rand2,$rand3) = get3nums(2,false);//第二種情況,且3個數字不允許全部相同
//得到$rand1=6,$rand2=6,$rand3=3

function get3nums($qingkuang,$ifxiangtong){

}

------解決思路----------------------
/**
* @$start 範圍下限
* @$end 範圍上限
* @$repeat 允許重複,預設不允許
**/
function get3nums($start, $end, $repeat=false) {
if(!$repeat){
$n =rand($start, $end); //取得指定範圍中的一個數
for($i=1;$i<7;$i++){
for($j=1;$j<7;$j++){
$k=$n-$i-$j;
if($k<7 &&$k>0){
if(($i==$j and $j==$k)){
continue;
}
echo $i.'-'.$j.'-'.$k."
";
}
}
}
}else{
$n =rand($start, $end);
$avg=$n/3;
if( $avg!=intval($avg)){
echo "no value"."
";
}else{
echo $avg.'-'.$avg.'-'.$avg."
";
}
}
}

print_r(get3nums(4, 10));
echo '
';
print_r(get3nums(4, 10, 1));
echo '
';
print_r(get3nums(11, 17));
echo '
';
print_r(get3nums(11, 17, 1));
?>

------解決思路----------------------
再檢查一下就是了
function get3nums($start, $end, $repeat=false) {
do {
do {
$r = array();
$n = rand($start, $end); //取得指定範圍中的一個數
$a = intval($n/3);
$r[] = rand(1, min($a, 6));
$r[] = rand(1, min($a, 6));
$r[] = $n - array_sum($r);
}while(max($r) > 6);
if($repeat) break;
}while(count(array_count_values($r)) == 1);
return $r;
}
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.