Trang chủ / Javascript / Sắp xếp hoặc trộn ngẫu nhiên một mảng

Sắp xếp hoặc trộn ngẫu nhiên một mảng

Mã nguồn:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Shuffle an array</title>
 <script>
function shuffle(arra1) {
		var ctr = arra1.length, temp, index;

	// While there are elements in the array
		while (ctr > 0) {
	// Pick a random index
			index = Math.floor(Math.random() * ctr);
	// Decrease ctr by 1
			ctr--;
	// And swap the last element with it
			temp = arra1[ctr];
			arra1[ctr] = arra1[index];
			arra1[index] = temp;
		}
		return arra1;
	}
	var myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
	document.write(shuffle(myArray));
 </script>
</head>
<body>
</body>
</html>

Xem ví dụ

 

Lưu đồ thuật toán:

Flowchart: JavaScript: Randomly arrange or shuffle an array

Thấy bài viết hữu ích?

Ủng hộ tác giả để có thêm nhiều bài viết chất lượng nhé!

Tư vấn lộ trình CNTT 🤖