1. 程式人生 > >亂序輸出字串-完全打亂順序

亂序輸出字串-完全打亂順序

  面試題---亂序輸出字串、陣列

Array.prototype.shuffle = function() {
  var array = this;
  var m = array.length,
    t, i;
  while (m) {
    i = Math.floor(Math.random() * m--);
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }
  return array;
}


var x = [1, 2, 3, 4, 5];
function shuffle(arr) {
  var length = arr.length,
    randomIndex,
    temp;
  while (length) {
    randomIndex = Math.floor(Math.random() * (length--));
    temp = arr[randomIndex];
    arr[randomIndex] = arr[length];
    arr[length] = temp
  }
  return arr;
}
console.log(shuffle(x))

自己的想法

function outOfOrder(str) {
    //str.split("");
	//var retArr=[];
	var len = str.length;
	var tmp;
	for (var i = len - 1; i > 0; i--) {
		var index = Math.floor(len * Math.random());//隨機數的產生範圍不變
		//每次與最後一位交換順序
		tmp = str[index];
		str[index] = str[i];
		str[i] = tmp;
		//console.log(str[index] + str[i] + tmp)
	}
	return str;
}
var x = [1, 2, 3, 4, 5];
console.log(outOfOrder(x));


//正確
function shuffile(arr){
var len=arr.length;
var randindex,tmp;
for(var i=len;i>0;i--){
    randindex=Math.floor(Math.random()*i);//隨機數的產生範圍每次都變化
    tmp=arr[randindex];
    arr[randindex]=arr[i-1];
    arr[i-1]=tmp;
}
return arr;
}
var x = [1, 2, 3, 4, 5];
console.log(shuffile(x))