刚才在51js看到有网友问,"1到100一百个数,怎么用JS来随机打乱它们的顺序呢?"。他说的这个不就是洗牌问题嘛,想起原来自己在做一个扑克游戏的时候设计过一个高效的洗牌算法,n个自然数通过n次循环搞定(当时是54个,扑克嘛)。
只是那个扑克牌程序是用C语言写的,不过用什么语言有什么区别呢?显然没有了,那今天就用JavaScript再实现一下。简单说明一下,洗牌算法虽然是用随机函数来排序,不过和获得随即序列大不一样。随即序列里可以有重复,不过洗牌要求处理后的随即序列元素是unique的,扑克牌能有相同的吗?所以需要先生成被排序序列来保证唯一性,假如是一个1-100的自然数数组。排序代码如下:
<
html
>
< head >
< title >JavaScript Shuffle Arithmetic </ title >
< meta name ="author" content ="birdshome@cnblogs" />
</ head >
< body >
< script language ="javascript" >
var sequence = new Array( 100 );
for ( var i = 0 ; i < 100 ; i ++ )
{
sequence[i] = i + 1 ;
}
alert(Shuffle(sequence));
function Shuffle(ary)
{
for ( var i = ary.length - 1 ; i >= 0 ; i -- )
{
var v = parseInt(Math.random() * (i + 1 ));
var tmp = ary[v];
ary[v] = ary[i];
ary[i] = tmp;
}
return ary;
}
</ script >
</ body >
</ html >
< head >
< title >JavaScript Shuffle Arithmetic </ title >
< meta name ="author" content ="birdshome@cnblogs" />
</ head >
< body >
< script language ="javascript" >
var sequence = new Array( 100 );
for ( var i = 0 ; i < 100 ; i ++ )
{
sequence[i] = i + 1 ;
}
alert(Shuffle(sequence));
function Shuffle(ary)
{
for ( var i = ary.length - 1 ; i >= 0 ; i -- )
{
var v = parseInt(Math.random() * (i + 1 ));
var tmp = ary[v];
ary[v] = ary[i];
ary[i] = tmp;
}
return ary;
}
</ script >
</ body >
</ html >
某一次排序结果为:60, 88, 2, 6, 52, 45, 37, 12, 49, 41, 68, 27, 80, 86, 100, 53, 99, 33, 57, 91, 10, 63, 50, 54, 97, 93, 30, 56, 13, 11, 23, 36, 32, 58, 72, 21, 95, 17, 18, 26, 59, 35, 90, 87, 78, 73, 77, 75, 89, 47, 28, 70, 1, 15, 66, 84, 98, 44, 4, 20, 74, 25, 76, 61, 65, 29, 38, 42, 85, 96, 34, 7, 24, 92, 22, 62, 79, 48, 14, 43, 69, 46, 94, 55, 81, 71, 82, 39, 40, 31, 8, 19, 3, 9, 83, 51, 5, 67, 16, 64。
五行代码的算法,就不解释了。您还有更优的吗?
本文转自博客园鸟食轩的博客,原文链接:http://www.cnblogs.com/birdshome/,如需转载请自行联系原博主。