最近,项目组在组织学习算法,算法中经常要用到数组做测试,为了方便使用,就随便写了一个产生随机数组的函数。This is the javascript file functions.js
/**/ /*** @author mmcgzs**/ /**/ /**this function to return a object by the objectname*/ function $(objectName) ... { return document.getElementById(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" "http://www.w3.org/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").value=arr.toString().substring(1); } </ script > < table > < 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 >