|
Last change
on this file was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago |
|
Added visualizations
|
-
Property mode
set to
100644
|
|
File size:
728 bytes
|
| Line | |
|---|
| 1 | 'use strict';
|
|---|
| 2 |
|
|---|
| 3 | Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|---|
| 4 |
|
|---|
| 5 | const randomInt = require('../math/randomInt.js');
|
|---|
| 6 |
|
|---|
| 7 | function sampleSize(array, size) {
|
|---|
| 8 | if (size > array.length) {
|
|---|
| 9 | throw new Error('Size must be less than or equal to the length of array.');
|
|---|
| 10 | }
|
|---|
| 11 | const result = new Array(size);
|
|---|
| 12 | const selected = new Set();
|
|---|
| 13 | for (let step = array.length - size, resultIndex = 0; step < array.length; step++, resultIndex++) {
|
|---|
| 14 | let index = randomInt.randomInt(0, step + 1);
|
|---|
| 15 | if (selected.has(index)) {
|
|---|
| 16 | index = step;
|
|---|
| 17 | }
|
|---|
| 18 | selected.add(index);
|
|---|
| 19 | result[resultIndex] = array[index];
|
|---|
| 20 | }
|
|---|
| 21 | return result;
|
|---|
| 22 | }
|
|---|
| 23 |
|
|---|
| 24 | exports.sampleSize = sampleSize;
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.