Wasiu
Wasiu

Reputation: 419

How can I displace and rearrange array element at the same time

I am working on a function that accepts a positive integer n, e.g 5 should produce an array // [1,2,3,4,5] then each element should displace the next while the last element has nothing to display so it becomes the first element until 1 element is remaining

[1,2,3,4,5] => [1,3,5] => [5,1,3] => [5,3] => [3,5] = > [3]

I approached it like this but I couldn't figure out the source of error.

function displaceMent(n){
  let arr = [];
  for(let i = 1; i <= n; i++) arr.push(i);
    let j = 0;
    while(arr.length > 1){
      arr =  arr[j + 1] === arr.slice(-1) ?  arr.splice(-1).concat(arr) : arr.splice(j + 1, 1);
      j++;
    }
return arr;
}

console.log(displaceMent(5))
<!DOCTYPE html>
<html>
<head>
    <title>Beating Game</title>
    
</head>
<body>
<script src="game.js"></script>
</body>
</html>

Upvotes: 0

Views: 253

Answers (2)

user12137152
user12137152

Reputation: 697

Is this what you want?

function displacement(n) { 

  var arr = [];
  for(let i = 1; i <= n; i++) arr.push(i);
  var i, j = 0;
  var times;

  while (arr.length != 1) {
    document.body.innerHTML += arr +"<br>";
  
    times =  Math.floor(arr.length/2);
  
    for (i = 0; i < times; i++)
        arr.splice(i + 1, 1);

    document.body.innerHTML += arr +"<br>";
    arr.unshift(arr.pop());
  }
}

displacement(5);
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
</body>
</html>

Now, coming to your original question. A soon as you run arr = arr[j + 1] === arr.slice(-1) ? arr.splice(-1).concat(arr) : arr.splice(j + 1, 1);, what happens is as followed.

  1. Since arr[j + 1] === arr.slice(-1) is false, j + 1th element is removed from arr by splice.

  2. The value returned by splice() is the value removed by it from arr. In this case it is 2.

  3. arr gets assigned 2.

  4. arr.length > 1 condition becomes false.

  5. The loop stops.

Upvotes: 1

Will
Will

Reputation: 3241

My answer is slightly different as it doesn't swap the last with the first if it has been displaced, which will give a different answer than above if n is set to, say, 7.

const displace = (n) => {
  let a = Array.from(Array(n)).map((_, i) => i + 1);
  while (a.length > 1) {
    console.log(a);
    a = a.reduce((p, c, i, a) => {
      i % 2 === 0 && p.push(c);
      a.length % 2 !== 0 && p.unshift(p.pop());
      return p;
    }, []);
  }
  return a;
};

console.log(displace(5));

Upvotes: 0

Related Questions