mc_transformArray1K(n=2)

Benchmark created on


Description

https://t.me/web_overflow/1302

#todo написати функцію на будь-якій мові програмування, яка приймає масив чисел arr та число N. Функція має повернути масив, кожен елемент якого є підмасивом розміром N. Винятком є останній підмасив, який може мати розмір [1, N]. Порядок усіх чисел має зберігатись.

Наприклад: [1, 2, 3, 4, 5, 6, 7, 8, 9], 3 => [[1, 2, 3], [4, 5, 6], [7, 8, 9]] [1, 2, 3, 4, 5, 6, 7, 8, 9], 2 => [[1, 2], [3, 4], [5, 6], [7, 8], [9]]

Setup

const size = 1_000;
const arrayNumbers1K = Array(size).fill(0);
for (let i = 0; i < size; ++i)
	arrayNumbers1K[i] = Math.random() * 1000;

Test runner

Ready to run.

Testing in
TestOps/sec
Kirill
const getNewArray = (arr, N) =>
  new Array(Math.ceil(arr.length / N)).fill(0).map((_, j) => arr.slice(j * N, (j + 1) * N));
getNewArray(arrayNumbers1K, 2);
ready
Volodymyr
const getNewArray = (arr, n) => {
  let res= [];
  for (let i = 0; i < arr.length / n; ++i) {
    res.push(arr.slice(i * n, (i + 1) * n));
  }
  return res;
}
getNewArray(arrayNumbers1K, 2);
ready
mc1
const getNewArray = (arr, n) => {
  const arrResult = [];
  let i = 0;
  while (i < arr.length) {
    arrResult.push(arr.slice(i, i + n));
    i += n;
  }
  return arrResult;
};
getNewArray(arrayNumbers1K, 2);
ready
mc2
const getNewArray = (arr, n) => {
  let newLen = (arr.length % n=== 0) ? 0 : 1;
  newLen += (arr.length - arr.length % n) / n;
  const arrResult = new Array(newLen).fill();
  arrResult.forEach((_, ind) => {
    arrResult[ind] = arr.slice(ind * n, (ind + 1) * n);
  });
  return arrResult;
};
getNewArray(arrayNumbers1K, 2);
ready
mc3
const getNewArray = (arr, n) => {
  let lenLastShortSubarr = arr.length % n;
  let numberFullSubarr = (arr.length - lenLastShortSubarr) / n;
  //let numberFullSubarr = Math.trunc(arr.length / n);
  const arrResult = new Array(numberFullSubarr).fill();
  for (let i = 0; i < arrResult.length; i++) {
    arrResult[i] = new Array(n).fill();
  }
  if (lenLastShortSubarr > 0) {
    arrResult.push(new Array(lenLastShortSubarr).fill());
  }
  let index1 = 0;
  let index2 = 0;
  for (let i = 0; i < arr.length; i++) {
    arrResult[index1][index2] = arr[i];
    index2++;
    if (index2 === n) {
      index2 = 0;
      index1++;
    }
  }
  return arrResult;
};
getNewArray(arrayNumbers1K, 2);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.