i有数据文件(PHP(,其中24个数据块,如下所示。
//ts1
$P[] = [0];
$S[] = [[1,95.8172406762736],[2,104.97526726371],[3,112.03839938973],[4,101.70457396977],];
$F[] = [];
$FB[] = [];
//ts2
$P[] = [0];
$S[] = [[1,103.190939795922],[2,105.297198378469],[3,105.829786652111]];
$F[] = [];
$FB[] = [];
//ts3
$P[] = [0];
$S[] = [[1,107.285278217373],[2,103.557795069809],[3,105.686758569246],[4,103.748341353355]];
$F[] = [];
$FB[] = [];
我需要洗牌前12个街区,然后将块13-24散步。我所拥有的代码似乎不起作用,因为它仍然一次将所有24个块洗牌。我不确定应该如何写。
// DATA INITIALISATION
// - Reads all data sets from server
// - Generates list of objects
// - Randomises list of objects
function DataInit1()
{
SeriesList = [];
CurrentGraph.Series = 0;
// load all the data sets from server
$.getJSON("datademo.php",
function(Data1)
{
for(var i=0; i<Data1.length; i+=4)
{
var P = Data1[i+0];
var S = Data1[i+1];
var F = Data1[i+2];
var FB = Data1[i+3];
var NewSeries = new SeriesClass(P,S,F,FB);
NewSeries.SeriesNumber = (i/4)+1;
SeriesList.push(NewSeries);
}
}
);
// shuffle each of the series lists to a random order
s1 = SeriesList.length/2;
s2 = SeriesList.length;
for(var i=0; i<s1; i++)
{
var j = Math.floor(Math.random() * (i+1));
var x = SeriesList[i];
SeriesList[i] = SeriesList[j];
SeriesList[j] = x;
}
for(var i=s1; i<s2; i++)
{
var j = Math.floor(Math.random() * (i+1));
var x = SeriesList[i];
SeriesList[i] = SeriesList[j];
SeriesList[j] = x;
}
}
编辑:我现在将其更改为以下内容(不是很漂亮,但我没有时间整理它(。现在它随机化系列1-12,但是序列13-24现在不是随机的。我不经常编码,我看不出为什么它会在第一个位置起作用,而不是第二位。
// shuffle the series list to a random order
for(var i=SeriesList.length-13; i>0; i--)
{
var j = Math.floor(Math.random() * (i+1));
var x = SeriesList[i];
SeriesList[i] = SeriesList[j];
SeriesList[j] = x;
}
for(var i={from: 12, to: 23}; i>0; i--)
{
var j = Math.floor(Math.random() * (i+1));
var x = SeriesList[i];
SeriesList[i] = SeriesList[j];
SeriesList[j] = x;
}
我认为最简单的方法是将其分成两个阵列,将它们分开洗牌,然后将它们推回在一起。我已经从这个问题中使用了混音方法:如何将数组洗牌?以及如何使用另一个数组扩展现有的JavaScript数组,而无需创建新数组?
请参阅https://jsfiddle.net/u25ta64x/1/
var SeriesList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26];
var firstHalf = SeriesList.slice(0,13);
var secondHalf = SeriesList.slice(13,26);
function shuffle(a) {
var j, x, i;
for (i = a.length; i; i--) {
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
}
}
shuffle(firstHalf);
shuffle(secondHalf)
var shuffledList = firstHalf;
Array.prototype.push.apply(shuffledList, secondHalf);
console.log(shuffledList);