问题描述
我想随机排序一个数组。一个好方法?
I''d like to randomly sort an array. A good method?
推荐答案
未经测试(但从工作脚本修改):
函数随机(低,高)
{
(数学)
{
返回楼层(随机()*(1 +高 - 低) )+低);
}
}
var unSorted = new Array(5);
var Sorted = new Array(5);
var used = new Array(5);
unSorted [1] =''< a href =" one.html">一个< / a>'';
unSorted [2] =''< a href =" two.html">两个< / a> ;';;
unSorted [3] =''< a href =" three.html"> Three< / a>'';
unSorted [ 4] =''< a href =" four.html">四< / a>'';
unSorted [5] =''< a href ="五。 html"> Five< / a>'';
for(ii = 1; ii< = 5; ii ++)
{
使用[ii] = false;
}
for(ii = 1; ii < = 5; ii ++)
{
randomNumber = Random(1,5);
while(used [randomNumber])
{
randomNumber = Random(1,5);
}
sorted [ii] = inSorted [randomNumber] ;
使用[randomNumber] = true;
}
Untested (but modified from a working script):
function Random( low, high )
{
with( Math )
{
return floor(random() * ( 1 + high - low ) + low );
}
}
var unSorted = new Array( 5 );
var Sorted = new Array( 5 );
var used = new Array( 5 );
unSorted[ 1 ] = ''<a href="one.html">One</a>'';
unSorted[ 2 ] = ''<a href="two.html">Two</a>'';
unSorted[ 3 ] = ''<a href="three.html">Three</a>'';
unSorted[ 4 ] = ''<a href="four.html">Four</a>'';
unSorted[ 5 ] = ''<a href="five.html">Five</a>'';
for( ii=1; ii<=5; ii++ )
{
Used[ ii ] = false;
}
for( ii=1; ii<=5; ii++ )
{
randomNumber = Random( 1, 5 );
while( used[ randomNumber ] )
{
randomNumber = Random( 1, 5 );
}
sorted[ ii ] = inSorted[ randomNumber ];
used[ randomNumber ] = true;
}
以上行应为:
排序[ii] = unSorted [randomNumber];
使用[randomNumber] = true;
}
Above line should read:
sorted[ ii ] = unSorted[ randomNumber ];
used[ randomNumber ] = true;
}
对不起,没有错字。应该是:
使用[ii] = false;
}
for(ii = 1; ii< = 5; ii ++)
{
randomNumber = Random(1,5);
while(used [randomNumber])
{
randomNumber = Random(1,5);
}
排序[ii] = inSorted [randomNumber];
使用[randomNumber] = true;
}
Sorry, another typo. Should be:
used[ ii ] = false;
}
for( ii=1; ii<=5; ii++ )
{
randomNumber = Random( 1, 5 );
while( used[ randomNumber ] )
{
randomNumber = Random( 1, 5 );
}
sorted[ ii ] = inSorted[ randomNumber ];
used[ randomNumber ] = true;
}
这篇关于随机化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!