Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve an evenly distributed number of elements from an array

I know how to extract every nth item in an array, but what I have difficulties with is the following:

How can I extract every nth item from an array of 1800 elements, always including the first and the last element, up to a total of 256 elements?

Example:

array = [1,2,3,4,5,6,7,8,9,10];

Extract 5 elements:

extract = [1,3,5,7,10];
like image 267
joker stream Avatar asked Sep 07 '15 13:09

joker stream


People also ask

How do you extract an even number from an array?

To find the even numbers in an array:Use the Array. filter() method to iterate over the array. Check if each number doesn't have a remainder when divided by 2. The filter method will return a new array containing only the even numbers.

How do you find the sum of all numbers in an array?

Approach to Find the Sum of All Elements in an ArrayInitialize a variable sum to store the total sum of all elements of the array. Traverse the array and add each element of the array with the sum variable. Finally, return the sum variable.


2 Answers

Like this?

/**
 * Retrieve a fixed number of elements from an array, evenly distributed but
 * always including the first and last elements.
 *
 * @param   {Array} items - The array to operate on.
 * @param   {number} n - The number of elements to extract.
 * @returns {Array}
 */
function distributedCopy(items, n) {
    var elements = [items[0]];
    var totalItems = items.length - 2;
    var interval = Math.floor(totalItems/(n - 2));
    for (var i = 1; i < n - 1; i++) {
        elements.push(items[i * interval]);
    }
    elements.push(items[items.length - 1]);
    return elements;
}

Example:

// Set up an array for testing purposes
var items = [];
for (var i=1; i<= 1800; i++) {
    items.push(i);
}

var extracted = distributedCopy(items, 256);

console.log(extracted);
like image 117
BadHorsie Avatar answered Sep 21 '22 12:09

BadHorsie


I slightly improved previous responses

function evenlyPickItemsFromArray<T>(allItems: T[], neededCount: number) {
  // if we want more items than avaliable, return all items
  if (neededCount >= allItems.length) {
      return [...allItems];
  }
  // buffer for collecting picked items
  const result: T[] = [];
  const totalItems = allItems.length;
  // default interval between items (might be float)
  const interval = totalItems/neededCount;

  for (let i = 0; i < neededCount; i++) {
    // always add half of interval, so 'picking area' is 'aligned' to the center
    // eg evenlyPickItemsFromArray([0...100], 1); // [50] instead of [0]
    const evenIndex = Math.floor(i * interval + interval / 2);

      result.push(allItems[evenIndex]);
  }
  return result;
}

// TESTING

// helper to create 0...n array
function createNLongArray(n: number) {
  return Array.from({length: n}).map((_, i) => i);
}

console.log(evenlyPickItemsFromArray(createNLongArray(100), 20)) // [2, 7, 12, 17, 22, 27, 32, 37, 42, 47, 52, 57, 62, 67, 72, 77, 82, 87, 92, 97]

console.log(evenlyPickItemsFromArray(createNLongArray(200), 3)) // [33, 100, 166]

note it's not picking first/last elements every time as it's actually quite complex - eg. if I'm picking 1 elem - should I pick first or last etc. It's just finding even distribution and pick them. 1st and last will be picked only when you want all or almost all elements from the input array

like image 36
Adam Pietrasiak Avatar answered Sep 24 '22 12:09

Adam Pietrasiak