的sooo我只是为你打造一个漂亮的小记录功能:
function randomRepeatSequence(sequences, times) {
// times has to be a multiple of sequences.length
if (times % sequences.length !== 0)
return console.log("times has to be a multiple of sequences.length");
// Remap our sequence-array so we can store the count it has been used
var seqmap = [];
for (var seqid = 0; seqid < sequences.length; seqid++)
// Push the current sequence n times; n = times/sequences.length
for (var idx = 0; idx < times/sequences.length; idx++)
seqmap.push(sequences[seqid]);
var resultmap = [];
// Now just select and remove a random sequence from our seqmap, until it is empty
while (!seqmap.length == 0) {
// Select a random element
var randomidx = Math.floor(Math.random()*seqmap.length);
var currentElement = seqmap[randomidx];
// remove the random element from seqmap...
seqmap.splice(randomidx, 1);
// .. and push it to the resultmap
resultmap.push(currentElement);
}
// now our resultmap looks like [[1],[2],[3]]... just flatten it!
var result = resultmap.reduce(function(a, b) {
return a.concat(b);
});
return result;
}
您可以使用它,就像
console.log(randomRepeatSequence([[1,0], [2,0]], 4));
或者,更好地理解:
var seqlist = [
[1, 0],
[2, 0]
]
randomRepeatSequence(seqlist, 4)
请护理,times
参数只需要使用的序列数量,而不是长度h的结果。但你只需要计算,在像
randomRepeatSequence(seqlist, 8/seqlist[0].length)
一个简单的步骤(给出4,因为seqlist [0]。长度= 2和8/2是4)
原始回答
你的结果是例如
vector = 2 0 1 0 2 0 1 0
我猜SEQ1和SEQ2应该包含相等的时间。 我决定用一种易于理解的方式,甚至通过我可以做短:
var trials = 8; // has to be even
var seq1 = [1, 0];
var seq2 = [2, 0];
// "Build" a sequence list
var seqlist = [
seq1, seq1,
seq2, seq2
]
var list = []
for (var n = 0; n < trials/2; n++) {
// search a random entry
var index = Math.floor(Math.random()*seqlist.length);
var toUseSeq = seqlist[index];
// delete the entry
seqlist.splice(index, 1);
list.push(toUseSeq);
}
// flatten result array
var result = list.reduce(function(a, b) {
return a.concat(b);
});
console.log(result);
执行此gaves我这些控制台输出中的一个:
[ 2, 0, 1, 0, 2, 0, 1, 0 ]
[ 2, 0, 1, 0, 2, 0, 1, 0 ]
[ 1, 0, 1, 0, 2, 0, 2, 0 ]
[ 1, 0, 2, 0, 1, 0, 2, 0 ]
好了,我们是不是Matlab开发人员。我明白你给了一个Matlab代码,你想将它转换为JavaScript。你能否也请解释一下Matlab代码的作用?所以我们可以尝试帮助您使用JavaScript的版本? –
当然! Matlab代码需要两个序列(1-0和2-0),将它们复制为我需要的总数(除以4,即1 + 0 + 2 + 0),并将这些序列随机化到向量中 – MManassi
谢谢。但上述情况仍不清楚。 ':('你能再请澄清一下......':)' –