본문 바로가기
WEB Archive

[HTML] Javascript - 난수를 발생시켜 로또번호를 출력시키는 함수 만들기

by universedevelope 2024. 8. 21.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test027.html</title>
<style type="text/css">

	/* 나의 스타일.. 명령 프롬프트 */
	*
	{
		background-color: white;
		font-family: 나눔고딕코딩;
		font-size: 20pt;
		color: #ababab;
		font-weight: bold;
	}
	h1
	{
		font-size: 40pt;
		color: #ababab;
		margin: 0%;
	}
	hr
	{
		background-color: #ababab;
		height: 15px;
	}
	input.btn
	{
		background-color: black;
		width: 250px;
		text-align: center;
	}
	input.btn:hover
	{
			background-color: red;
			color: white;
	}
	input.txtbox
	{
		 width: 100px;
		 text-align: center;
	}
	input.txtbox:hover
	{
		background-color: blue;
		color: white;
	}
</style>

<script type="text/javascript">
	function createLotto()
	{
		//alert("아싸");
		var count = parseInt(document.getElementById("lotto").value);
		
		for (var i = 0; i < count; i++)
		{
			//로또 번호 1게임 실행();
			 document.getElementById("results").value += runLottoSingle() + "\n";
			// 
		}
		
		
		
	}
	
	// 로또 1게임 실행 메소드
	function runLottoSingle()
	{
		// 방 6개로 구성된 배열 생성
		var lottoArray = new Array(6);
		
		// 공 45개로 구성된 배열 생성
		var arr = new Array(45);
		
		// 1 ~ 45 까지의 로또 번호를 공에 채우기
		for (var i = 1; i <= arr.length; i++)
			arr[i-1] = i;
		
		// 확인
		//alert(arr[9]); --==>> 10
		
		// 뒤섞기
		for (var i = 0; i < arr.length; i++)	// 0 ~ 44
		{
			var j = parseInt(Math.random()*45);    // 0 ~ 44까지의 정수 형태의 난수 발생
			var temp = arr[i];	// ┓
			arr[i] = arr[j];	// ┃ 자리 바꾸기	
			arr[j] = temp;		// ┛	
		}
		
		// 확인
		// return arr; // 더미 반환~!
		// 배열의 요소 옮겨담기
		for (var i = 0; i < lottoArray.length; i++)
		{
			lottoArray[i] = arr[i];
		
		}
		
			               // left right
		lottoArray.sort(function(a, b)
		{
			return a - b;
		});
		// 확인
		
		// 구성된 배열(최종 결과값) 반환
		return lottoArray;
		
	}
</script>


</head>
<body>
<!--
	코딩테스트 
	로또 번호(1~45)를 중복되지 않은 정수 6개를 생성하여 출력해주는
	페이지를 구현한다.
	HTML, CSS, Javascript 를 활용한다.
	난수 발생 함수를 활용한다.
	번호순으로 (오름차순) 정렬하여 출력할 수 있도록 한다.
	주문한 장 수 만큼 출력할 수 있도록 한다.
	
	페이지 레이아웃
	--------------------------------------------
	로또  [  3  ]장       <주문하기>
	         └ text           └button
	         
	결과 ─ textarea
	--------------------------------------------
	1 2 6 10 35 2
	8 2 7 40 25 1
	3 25 32 42 7 9
	--------------------------------------------	         
 -->

<div>
	<h1>로또번호 생성기</h1>
	<hr>
</div>

<div>
	<form>
		로또
		<input type = "text" id = "lotto" style ="width: 50px">
		장
		<input type = "button" id = "makeNum" onclick = "createLotto()" value = "주문하기">
		<br><br><br>
		
		결과
		<br>

		
		
	</form>
</div>

<div>
	<form>
		<textarea cols = "20" rows = "5" id = "results" ></textarea>
	</form>
</div>

</body>
</html>
728x90

댓글