面试题---乱序输出字符串、数组
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))