亂數產生器

之前曾想用C語言寫一個比較公平的亂數產生器,沒想到光是語法就讓我頭昏腦轉了\(;゚Д゚)/

今天想說有點小空閒就來寫看看,幸好PHP很友善,沒兩三下子就搞定了

沒遇到什麼BUG,還順便處理了PHP可能會跳提示的語法,讓errorlog更乾淨ヽ(´ー`)ノ

程式的概念是:先跑一萬次函式,確定random seed已經改變了

然後就依照指示的數字範圍來做亂數,將數字出現的次數存入陣列,最後再利用比較陣列的方式獲得出現次數最多的數字~

<!DOCTYPE html>
<html dir="ltr" lang="zh-TW">
<head>
	<meta charset="utf-8">
	<title>亂數產生器</title>
</head>
<body>
<?php
if (isset($_POST['run'])) {
	$min = $_POST['min'];
	$max = $_POST['max'];
	/* Initial function */
	for ($index = 0; $index < 10000; $index++) {
		mt_rand();
	}
	
	/* Generate numbers */
	$array[] = 0;
	for ($index = 0; $index < 10000000; $index++) {
		$output = mt_rand($min, $max);
		if (isset($array[$output])) {
			$array[$output]++;
		} else {
			$array[$output] = 1;
		}
	}
	
	/* Find the greatest counter */
	$result = $array[$min];
	$biggest = $min;
	for ($index = $min+1; $index < $max+1; $index++) {
		if (isset($array[$index])) {
			if ($result = $array[$index]) {
				die('Duplicate counter found. Pls restart the generator.');
			} else if ($result < $array[$index]) {
				$result = $array[$index];
				$biggest = $index;
			}
		}
	}
?>
<h1>亂數結果:<?php echo $biggest; ?></h1>
<?php 
} else {
?>
	<form action="rand.php" method="post" accept-charset="utf-8">
		<label>請輸入最小數字</label>
		<input type="text" name="min">
		<label>請輸入最大數字</label>
		<input type="text" name="max">
		<button type="submit">送出</button>
		<input type="hidden" name="run" value="run">
	</form>
<?php
}
?>
</body>
</html>

留言

粗體斜體刪除線連結引用圖片程式碼

注意:您的電子信箱將不會被公開,且網站連結不會被搜尋引擎採計

{124} {123} {122} {121} {120} {119} {118} {117} {116} {115} {114} {113} {112} {111} {100} {025} {024} {023} {022} {021} {020} {019} {018} {017} {016} {015} {014} {013} {012} {011} {010} {009} {008} {007} {006} {005} {004} {003} {002} {001}