开发者

How to operate the elements of an array

开发者 https://www.devze.com 2022-12-18 23:19 出处:网络
I have to operate a 4 elements array, calculating the difference between the adjacent elements and creating a new array with the resulting differnece. The last element should be colindant with the fir

I have to operate a 4 elements array, calculating the difference between the adjacent elements and creating a new array with the resulting differnece. The last element should be colindant with the first one.

example:

firstArray=[0,1,2,3];
secondArray = newArray();

The second array will be:

secondArray[0]: 1-0 = 1
secondArray[1]: 2-1 = 1
secondArray[2]: 3-2 = 1
secondArray[3]: 3-0 = 3

So the new Array should be secondArray=[1,1,1,3]

I tried to do it with a for loop but when the third array is going to be operate it always operate the firstArray[3] - secondArray[0]... when it should be fistArray[3] - firstArray[0]

How can operate the firstArray to differentiate it from the new created s开发者_开发百科econdArray?

Thank you!


You never said anythign about a 3rd array in your example.

Is this what you're trying to do?

secondArray[0] = firstArray[1]-firstArray[0];
secondArray[1] = firstArray[2]-firstArray[1];
secondArray[2] = firstArray[3]-firstArray[2];
secondArray[3] = firstArray[0]-firstArray[3];

If you are in a loop, the expression could be

secondArray[i] = firstArray[(i+1)%arrayLength]-firstArray[i];

UPDATE:

secondArray[i] = Max(firstArray[(i+1)%arrayLength],firstArray[i]) - Min(firstArray[(i+1)%arrayLength],firstArray[i]);

Using Max and Min will get the larger and smaller of the two elements in question. Does that help?


in your loop:

if (i == 3)
firstArray[i] - firstArray[0];


Try this:

var firstArray = [0,1,2,3],
    secondArray = [];
firstArray.forEach(function(val, i, arr) {
    secondArray[i] = arr[(i+1)%arr.length] - val;
});

Edit    A solution without forEach:

for (var i=0; i<firstArray.length; ++i) {
    secondArray[i] = firstArray[(i+1)%firstArray.length] - firstArray[i];
}


input = [1, 4, 19, -55, 20];

function f(a) {
   function next(a) {
     var t = [], l = a.length;
     for (var i = 1; i < l; ++ i)
       t.push(Math.abs(a[i] - a[i-1]));
     t.push(Math.abs(a[l-1] - a[0]));
     return t;
   }

   var l = a.length;
   var result = [a];
   for (var i = 0; i < l-1; ++ i)
     result.push(next(result[i]));
   return result;
}

f(input);
// [[1, 4, 19, -55, 20], [3, 15, 74, 75, 19], [12, 59, 1, 56, 16], [47, 58, 55, 40, 4], [11, 3, 15, 36, 43]]
0

精彩评论

暂无评论...
验证码 换一张
取 消