Reversing an array without 'reverse' or duplicating an array

丶灬走出姿态 提交于 2019-11-28 01:50:03

问题


I'm trying to solve the following exercise:

Reverse an array without using the reverse method, without using a second array, and without duplicating any of the values.

I've thought about making the array an object and then updating the array from the end to the beginning but I figured you can just update it as well.

Tried something simple like:

function reverseArray(array) {
  for (var i = 0; i < array.length; i++) {
    // var elem = array.shift();
    var elem = array.shift()
    array.push(elem)
  }
  return array
}

array = ['a', 'b','c','d','e'];

reverseArray(array);

But that doesn't really change it. Any advice or explanation on how to do this?


回答1:


With ES6 syntax you don't need to copy a value into a temporary variable (is that what the last requirement is about?).

function reverse(arr) {
    for(let i = 0, j = arr.length-1; i < j; i++, j--)
        [arr[i], arr[j]] = [arr[j], arr[i]];
}

const arr = ['a','b','c','d','e'];
reverse(arr);
console.log(arr);

One may argue that arrays are created here (if engines don't optimise this away), just like splice also creates an array (as its return value).




回答2:


array = ['a', 'b', 'c', 'd', 'e'];
console.log(array);

for (var i = 0; i < Math.floor(array.length / 2); i++) {
  var item = array[i];
  array[i] = array[array.length - i - 1];
  array[array.length - i - 1] = item;
}
console.log(array);



回答3:


The following will work reverse an array without using the reverse method. It works by swapping the first and last elements, then the second and second-to-last elements, then the third and third-to-last elements, etc until the i is no longer less than (<) than j.

function reverse(arr) {
  for(var i = 0, j = arr.length-1; i < j; i++, j--) {
    var tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
  }
  return arr;
};

var reversed = reverse(['a','b','c','d','e']);
console.log(reversed);



回答4:


https://jsfiddle.net/pa2fqa8n/1/

a = ['a', 'b', 'c', 'd', 'e'];
for(var i = 0; i < a.length-1; i++){
  for(var j = 0; j < a.length-i-1; j++){
    var k = a[j];
    a[j] = a[j+1];
    a[j+1] = k;
  }
}

First iteration of inner loop moves the first element to the end, and the rest of the elements forward once. Each following iteration does the same thing, but 1 less than the previous iteration.




回答5:


I had to use a swap variable, does that violate "without duplicating any of the values"?

var test1 = [2, '5', 6, 'a', 'Z'];
var test2 = [2, '5', false, 'a', 'Z', {a: 'whatevs'}];

console.log('test1 before', JSON.stringify(test1));
console.log('test2 before', JSON.stringify(test2));

reversarooni(test1);
reversarooni(test2);

console.log('test1 after', JSON.stringify(test1));
console.log('test2 after', JSON.stringify(test2));

function reversarooni(inputArray) {
  var index = 0;
  var len = inputArray.length;
  
  for(; index < len / 2; index++) {
    var swap = inputArray[index];
    inputArray[index] = inputArray[(len - 1) - index];
    inputArray[(len - 1) - index] = swap;
  }
}



回答6:


Here is a minimal approach. Given var arr = [1,2,3,4], this loop will mutate arr to [4,3,2,1]:

for (var i = 0; i < arr.length - 1; i++) {
    arr.splice(i, 0, arr.pop());
}



回答7:


Here's how, without copies, temporary arrays or variables to hold values, or using Array.reverse().Modifying the array in place

function reverseArray(array) {
  var len = array.length;
  for (var i=len,j=-1; j++,i--;)  array.unshift( array[len-1-i+(j)] );
  array.length = len;
}

var array = ['a', 'b','c','d','e'];

reverseArray(array);
console.log(array);

It inserts the values backwards into the beginning of the array, pushing the old values to the end, and then slicing them of by resetting the arrays length after the iteration has completed.




回答8:


You could use a spread syntax ..., rest parameters ... and return the swapped items with a recursive and functional approach.

const
    _ = (...a) => a,
    rev = (a, ...rest) => rest.length ? _(...rev(...rest), a) : _(a),
    reverseArray = array => rev(...array);

console.log(reverseArray(['a', 'b', 'c', 'd', 'e']));
console.log(reverseArray(['a']));
console.log(reverseArray(['a', 'b']));
.as-console-wrapper { max-height: 100% !important; top: 0; }



回答9:


function printReverse(array) {
  for (i = array.length-1; i > -1; i--) {
    console.log(array[i]); //4,3,2,1
  }
}

printReverse([1, 2, 3, 4]);

This worked for me.



来源:https://stackoverflow.com/questions/45988670/reversing-an-array-without-reverse-or-duplicating-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!