⽤脚本创建⼀个不重复的随机数数组
最近,项⽬组在组织学习算法,算法中经常要⽤到数组做测试,为了⽅便使⽤,就随便写了⼀个产⽣随机数组的函数。This is the javascript file functions.js
/**
* @author mmcgzs
**/
/*
*this function to return a object by the objectname
*/
function $(objectName)
{
ElementById(objectName);
}
/*
* this function to return a randomize number array
* arguments
* l:The array's length
* s:The minimum number
* e:The maximum number
* noRepeat:The number will be not repeat when this argument means true;
*/
function getRandomizeArr(l,s,e,noRepeat)
{
if (typeof(s)=="undefined") var s=1;
if (typeof(e)=="undefined") var e=100;
if (typeof(noRepeat)=="undefined") var noRepeat=true;
var range=e-s+1;
var arr=new Array();
if (l>range || l<1) return arr;
for (var i=1;i<=range;i++)
{
arr[i]=i;
}
var retArr = new Array();
for (var i=1;i<=l;i++)
{
var r=parseInt(Math.random()*range+s,10);
if (noRepeat)
{
retArr[i]=arr[r];
arr[r]=arr[e];
arr[e]=retArr[i];
e--;
range--;
}
else
{
retArr[i]=r;
}
}
return retArr;
}
This is the html file "RandomizeArrayTest.htm"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>Untitled Document</title>
</head>
<body>
<script language=JavaScript src=functions.js></script>
<script language=JavaScript>
function getArray()
{
var arr=new Array();
arr=getRandomizeArr($("lengText").value,$("startText").value,$("endText").value,$("chkRepeat").checked);
$("arrayView").String().substring(1);
}
</script>
<table>
typeof array<tr>
<td>
Length:<input type=text id=lengText />
<input type=checkbox id=chkRepeat checked> <label for=chkRepeat>NoRepeat</label>
<input type=button value=" g e t " onclick=getArray()><br>
MinValue:<input type=text id=startText value=1 />
MaxValue:<input type=text id=endText value=100 />
</td>
</tr>
<tr>
<td>
<textarea rows=10 cols=70 id=arrayView></textarea>
</td>
</tr>
</table>
</body>
</html>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论