当我需要以循环方式移动所有数组元素时,我遇到了一种情况。当我这么说时,我是说:
0 1 2 3
1 2 3 0
2 3 0 1
3 0 1 2数组:
var players = ["hash1","hash2","hash3","hash4"];Players是一个数组,它包含用户散列及其在表中的位置。桌子是圆的,所以数组必须以圆形的方式旋转。Step决定了它应该移动多少。我想出了下面的算法(如果你可以这么说的话,很可能不行),这个算法很好用。我只是想知道是否有更有效的方法。还是用更干净的方法来做同样的事?
offset变量的命名可能是错误的;我想不出更好的名称。
var step = 0 // 3,2,1,0
var offset = 0;
var players_new = [];
for (var i = 0; i <= players.length - 1; i++) {
if (i + step <= players.length - 1) {
players_new[i + step] = players[i];
offset++;
} else {
players_new[i - offset] = players[i];
}
};我测试了许多不同的版本,看上去vazha的版本是目前最快的版本,但Firefox除外。
由于我在使用Chrome的node.js中使用了这段代码,所以结果非常重要。
发布于 2014-02-05 21:40:59
您应该使用shift和push
function rotate( array , times ){
while( times-- ){
var temp = array.shift();
array.push( temp )
}
}
//Test
var players = ['Bob','John','Mack','Malachi'];
rotate( players ,2 )
console.log( players );shift移除第一个元素,push在末尾添加一个元素。我不确定您是在使用players_new,因为您不知道如何修改原始数组,或者因为您不想修改原始数组。如果不想修改原始数组,可以:
function rotate( array , times ){
array = array.slice();
while( times-- ){
var temp = array.shift();
array.push( temp )
}
return array;
}
//Test
var players = ['Bob','John','Mack','Malachi'];
console.log( rotate( players ,2 ) );最后,如果要声明数组,则应该使用var players_new = [];,而不是var players_new = {};。另外,players_new是一个不幸的名字。
黄金版:
while(times--)array.push(array.shift());发布于 2014-02-05 22:34:53
有时候抽象化这类问题是个好主意。在许多语言中,基于数组的轮班非常昂贵。
你需要旋转数组吗?为什么不直接“旋转”你的指针..。
for (int turn = 0; turn < 10; turn++) {
console.log("First player is " + players[(turn + 0) % players.length]);
console.log("Last player is " + players[(turn + players.length - 1) % players.length]);
}或者,如果出于其他原因需要创建完整的数组,请考虑切片和连接:
for (turn = 0; turn < 10; turn++) {
var offset = turn % players.length;
console.log(offset);
var playturn = players.slice(offset).concat(players.slice(0, offset));
console.log(playturn.join(", "));
}https://codereview.stackexchange.com/questions/41006
复制相似问题