Function that prints indexes of an array incrementally

Asked

Viewed 65 times

-2

I’m trying to implement a function that can be in PHP or Js that takes the values of an array and displays them, only skipping indexes incrementally.

For example, I have the following array

numeros = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"];

Which should display the following numbers 0, 2, 5, 9, 14... As you can see, it starts by displaying the index value 0, skips an index of the current position and displays the value 2, skips two indexes of the current position and displays the value 5, and so on.

In this example the output should be the values 0, 2, 5, 9, 14, 20

2 answers

3


<?php

   $numeros = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"];
   $indice = 0;
   $incremento = 0;
   do{
    echo $numeros[$indice+$incremento]."<br/>";
    $indice++;
    $incremento += $indice;
   }while($indice+$incremento < count($numeros));

Explanations: You will need two variables: one to traverse the array ($Indice) and one to increment the jumps ($increment), they must be interconnected so that the advance of one influences the advance of the other to the end of the array, I used the loop structure do while, for the first interaction to be carried out.

Understanding the loop

     $indice|$incremento|Posição do elemento| Número

  1ª:   0   |     0     |         0         |  "0"
  2ª:   1   |     1     |         2         |  "2"
  3ª:   2   |     3     |         5         |  "4"
  4ª:   3   |     7     |         10        |  "9"
  5ª:   4   |     11    |         15        |  "14"
  6ª:   5   |     16    |         21        |  "20"

And the loop is closed because the sum of the $Indice + $increment has to be less than the number of elements in the array $indice+$incremento < count($numeros).

I hope I contributed;

0

Javascript:

function skipIndex(arr){
  let newArr = []
  for (let i = 0, jump = 2; i < arr.length; i+=jump, jump++){
    newArr.push(arr[i])
  }
  return newArr
} 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.