编程基础:随机且不重复的算法
问题描述:有A到L的一组字母,需要每次都随机排序输出,并且不能有重复。
程序算法分析:
首先解决数组 0 到 11(即该数组的长度-1)的随机且不重复的问题。
接下来把数组的值按下标索引去取这一组字母。
最后把结果输出出来。
代码如下:
var containerSet = function(count) { var tempArr = []; for (var i=0; i < count; i++){ tempArr[i]=i; } tempArr.sort(function() { return 0.5 - Math.random(); }); return tempArr; } var containers = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']; var l = containers.length; var countSet = containerSet(l); var resultSet = []; while(l--) { resultSet.push(containers[countSet[l]]); } console.log(resultSet);
程序的精妙之处在:
tempArr.sort(function() { return 0.5 - Math.random(); });
这是利用了Array的sort(compareFunction)方法中的compareFunction参数。具体请参考:
If
compareFunction
is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:
- If
compareFunction(a, b)
is less than 0, sort a to a lower index than b.- If
compareFunction(a, b)
returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.- If
compareFunction(a, b)
is greater than 0, sort b to a lower index than a.compareFunction(a, b)
must always returns the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined
来源于: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort