1. 程式人生 > >JavaScript 遞歸法排列組合二維數組2

JavaScript 遞歸法排列組合二維數組2

ble func turn owin r++ ear ons javascrip 二維數組

<html>
	  
	<head>
		<title>二維數組排列組合</title>
	</head>

	<body>
		<div id="showDiv"></div>
	</body>

	<script type="text/javascript">
		var arrays = [ 
			[ 
				‘1-1-雨塵‘, ‘1-2-蕓蕓‘, ‘1-3-簡一‘, ‘1-4-樂樂‘
			]
			, [ 
				‘2-5-小明‘, ‘2-6-花花‘, ‘2-7-數數‘
			]
			, [ 
				‘3-8-靜靜‘, ‘3-9-點點‘, ‘3-10-hapday‘, ‘3-11-歡歡‘, ‘3-12-yuchen‘
			] 
		];
//		debugger;

		/**
		 * 遞歸法排列組合二維數組
		*/
		function doExchange(doubleArrays){
			var len=doubleArrays.length;

			if (len >= 2) {
				var len1 = doubleArrays[0].length;
				var len2 = doubleArrays[1].length;
				var newlen = len1 * len2;
				var temp = new Array(newlen);
				var rowIndex=0;

				for(var index = 0; index < len1; index++){
					for(var cursor = 0; cursor < len2; cursor++){
						temp[rowIndex] = doubleArrays[0][index] + ‘#‘ + doubleArrays[1][cursor];

						rowIndex++;
					}
				}

				var newArray = new Array(len-1);
				
				for (var index = 2; index < len; index++) {
					newArray[index - 1] = doubleArrays[index];
				}

				newArray[0] = temp;

				var result = doExchange(newArray);
				console.log(result);
				return result;
			} else {
				var result = doubleArrays[0];
				console.log(‘只有一個內層數組:\n‘ + result + ‘\n‘);
				console.log(‘===================================‘);
				return result;
			}
		}

	var ret = doExchange(arrays);

	window.document.getElementById(‘showDiv‘).innerHTML += ‘共有 ‘ + ret.length + ‘ 種組合。<br /><br />‘;

	for (var index = 0; index < ret.length; index++) {
		var row = ret[index];
		var rows = row.split(‘#‘);
//		debugger;
		for (var cursor = 0; cursor < rows.length; cursor++) {
			var cell = rows[cursor];
			var cells = cell.split(‘-‘);

			for (var kk = 0; kk < cells.length; kk++) {
				window.document.getElementById(‘showDiv‘).innerHTML += cells[kk] + ‘    ‘; 
			}

			window.document.getElementById(‘showDiv‘).innerHTML += ‘                                ‘;
		}
		window.document.getElementById(‘showDiv‘).innerHTML += ‘<br />‘;
	}

	</script>

</html>

  

JavaScript 遞歸法排列組合二維數組2