>>> def clockwise(r):
... return list(r[0]) + clockwise(list(reversed(zip(*r[1:])))) if r else []
...
>>> a = [
... [ 1, 2, 3],
... [ 5, 6, 7],
... [ 9, 10, 11]]
>>> clockwise(a)
[1, 2, 3, 7, 11, 10, 9, 5, 6]
我試圖將順時針變爲Javascript的功能,但似乎無法得到它的工作。Python到Javascript
我已經創造了一些方法具有類似功能:
function zip(masterArray){//zips 2 arrays
var innerLoop = masterArray.length; //inner loop
var outerLoop = 0;
//get length of shortest
for (var i = 0; i<masterArray.length;i++){
var a = masterArray[i].length;
if (outerLoop==0){outerLoop = a;}else if(a < outerLoop){outerLoop = a;}
}
var newOuterArray = new Array(outerLoop);
for (var x = 0; x<outerLoop;x++){
var newInnerArray = new Array(innerLoop);
for (var y = 0; y<innerLoop;y++){
newInnerArray[y] = masterArray[y][x];
}
newOuterArray[x] = newInnerArray;
}
return newOuterArray;
}
function reversed(arr){
var newArray = new Array(arr.length);
var n = 0;
for(var i=arr.length-1; i>=0; i--){
newArray[n++] = arr[i];
}
return newArray;
}
function clockwise(r){
if(r.length>0){
var a = reversed(zip(r.slice(1)));
a.splice(0,0,r[0]);
return clockwise(a);
}else{
return [];
}
}
這裏是我的進步。我被困在最後一部分:螢火蟲順時針錯誤是遞歸太多。
太感謝你了! – hamahama