{"id":26119179,"url":"https://github.com/stdlib-js/random-sample","last_synced_at":"2025-04-13T10:21:33.366Z","repository":{"id":57162713,"uuid":"377255311","full_name":"stdlib-js/random-sample","owner":"stdlib-js","description":"Sample elements from an array-like object.","archived":false,"fork":false,"pushed_at":"2025-03-17T03:21:52.000Z","size":2196,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-04-13T00:17:06.406Z","etag":null,"topics":["choice","choose","discrete","distribution","draw","javascript","math","mathematics","node","node-js","nodejs","rand","random","replacement","sampling","statistics","stats","stdlib","urn","with-replacement"],"latest_commit_sha":null,"homepage":"https://github.com/stdlib-js/stdlib","language":"JavaScript","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/stdlib-js.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":"CITATION.cff","codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["stdlib-js"],"open_collective":"stdlib","tidelift":"npm/@stdlib/stdlib"}},"created_at":"2021-06-15T18:12:41.000Z","updated_at":"2025-03-17T01:44:48.000Z","dependencies_parsed_at":"2024-01-23T21:38:14.464Z","dependency_job_id":"69255023-c98e-425e-b92b-6ebbb9b2cdca","html_url":"https://github.com/stdlib-js/random-sample","commit_stats":{"total_commits":45,"total_committers":1,"mean_commits":45.0,"dds":0.0,"last_synced_commit":"86b99b336cb063c8f515969b571b69ee86fce9ba"},"previous_names":[],"tags_count":19,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stdlib-js%2Frandom-sample","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stdlib-js%2Frandom-sample/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stdlib-js%2Frandom-sample/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stdlib-js%2Frandom-sample/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/stdlib-js","download_url":"https://codeload.github.com/stdlib-js/random-sample/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248696229,"owners_count":21147093,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["choice","choose","discrete","distribution","draw","javascript","math","mathematics","node","node-js","nodejs","rand","random","replacement","sampling","statistics","stats","stdlib","urn","with-replacement"],"created_at":"2025-03-10T12:16:33.239Z","updated_at":"2025-04-13T10:21:33.344Z","avatar_url":"https://github.com/stdlib-js.png","language":"JavaScript","funding_links":["https://github.com/sponsors/stdlib-js","https://opencollective.com/stdlib","https://tidelift.com/funding/github/npm/@stdlib/stdlib"],"categories":[],"sub_categories":[],"readme":"\u003c!--\n\n@license Apache-2.0\n\nCopyright (c) 2018 The Stdlib Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n--\u003e\n\n\n\u003cdetails\u003e\n  \u003csummary\u003e\n    About stdlib...\n  \u003c/summary\u003e\n  \u003cp\u003eWe believe in a future in which the web is a preferred environment for numerical computation. To help realize this future, we've built stdlib. stdlib is a standard library, with an emphasis on numerical and scientific computation, written in JavaScript (and C) for execution in browsers and in Node.js.\u003c/p\u003e\n  \u003cp\u003eThe library is fully decomposable, being architected in such a way that you can swap out and mix and match APIs and functionality to cater to your exact preferences and use cases.\u003c/p\u003e\n  \u003cp\u003eWhen you use stdlib, you can be absolutely certain that you are using the most thorough, rigorous, well-written, studied, documented, tested, measured, and high-quality code out there.\u003c/p\u003e\n  \u003cp\u003eTo join us in bringing numerical computing to the web, get started by checking us out on \u003ca href=\"https://github.com/stdlib-js/stdlib\"\u003eGitHub\u003c/a\u003e, and please consider \u003ca href=\"https://opencollective.com/stdlib\"\u003efinancially supporting stdlib\u003c/a\u003e. We greatly appreciate your continued support!\u003c/p\u003e\n\u003c/details\u003e\n\n# Sample\n\n[![NPM version][npm-image]][npm-url] [![Build Status][test-image]][test-url] [![Coverage Status][coverage-image]][coverage-url] \u003c!-- [![dependencies][dependencies-image]][dependencies-url] --\u003e\n\n\u003e Sample elements from an array-like object.\n\n\u003csection class=\"intro\"\u003e\n\n\u003c/section\u003e\n\n\u003c!-- /.intro --\u003e\n\n\u003csection class=\"installation\"\u003e\n\n## Installation\n\n```bash\nnpm install @stdlib/random-sample\n```\n\nAlternatively,\n\n-   To load the package in a website via a `script` tag without installation and bundlers, use the [ES Module][es-module] available on the [`esm`][esm-url] branch (see [README][esm-readme]).\n-   If you are using Deno, visit the [`deno`][deno-url] branch (see [README][deno-readme] for usage intructions).\n-   For use in Observable, or in browser/node environments, use the [Universal Module Definition (UMD)][umd] build available on the [`umd`][umd-url] branch (see [README][umd-readme]).\n\nThe [branches.md][branches-url] file summarizes the available branches and displays a diagram illustrating their relationships.\n\nTo view installation and usage instructions specific to each branch build, be sure to explicitly navigate to the respective README files on each branch, as linked to above.\n\n\u003c/section\u003e\n\n\u003csection class=\"usage\"\u003e\n\n## Usage\n\n```javascript\nvar sample = require( '@stdlib/random-sample' );\n```\n\n#### sample( x\\[, options] )\n\nSamples elements from an `array`-like object. By default, elements are drawn with replacement from `x` to create an output `array` having the same length as `x`.\n\n```javascript\nvar out = sample( [ 'a', 'b', 'c' ] );\n// e.g., returns [ 'a', 'a', 'b' ]\n\nout = sample( [ 3, 6, 9 ] );\n// e.g., returns [ 3, 9, 6 ]\n\nvar bool = ( out.length === 3 );\n// returns true\n```\n\nThe function accepts the following `options`:\n\n-   **size**: sample size. Default: `N = x.length`.\n-   **probs**: a probability `array`. Default: `[1/N,...,1/N]`.\n-   **replace**: `boolean` indicating whether to sample from `x` with replacement. Default: `true`.\n\nBy default, the function returns an `array` having the same length as `x`. To generate a sample of a different size, set the `size` option.\n\n```javascript\nvar out = sample( [ 3, 6, 9 ], {\n    'size': 10\n});\n// e.g., returns [ 6, 3, 9, 9, 9, 6, 9, 6, 9, 3 ]\n\nout = sample( [ 0, 1 ], {\n    'size': 20\n});\n// e.g., returns [ 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0 ]\n```\n\nTo draw a sample _without_ replacement, set the `replace` option to `false`. In this case, the `size` option cannot be an integer larger than the number of elements in `x`.\n\n```javascript\nvar out = sample( [ 1, 2, 3, 4, 5, 6 ], {\n    'replace': false,\n    'size': 3\n});\n// e.g., returns [ 6, 1, 5 ]\n\nout = sample( [ 0, 1 ], {\n    'replace': false\n});\n// e.g., returns [ 0, 1 ]\n```\n\nBy default, the probability of sampling an element is the same for all elements. To assign elements different probabilities, set the `probs` option.\n\n```javascript\nvar x = [ 1, 2, 3, 4, 5, 6 ];\nvar out = sample( x, {\n    'probs': [ 0.1, 0.1, 0.1, 0.1, 0.1, 0.5 ]\n});\n// e.g., returns [ 5, 6, 6, 5, 6, 4 ]\n\nx = [ 1, 2, 3, 4, 5, 6 ];\nout = sample( x, {\n    'probs': [ 0.1, 0.1, 0.1, 0.1, 0.1, 0.5 ],\n    'size': 3,\n    'replace': false\n});\n// e.g., returns [ 6, 4, 1 ]\n```\n\nThe `probs` option **must** be a numeric array consisting of nonnegative values which sum to one. When sampling _without_ replacement, note that the `probs` option denotes the initial element probabilities which are then updated after each draw.\n\n#### sample.factory( \\[pool, ]\\[options] )\n\nReturns a `function` to sample elements from an `array`-like object. \n\n```javascript\nvar mysample = sample.factory();\n\nvar out = mysample( [ 0, 1, 2, 3, 4 ] );\n// e.g., returns [ 4, 3, 4, 4 ]\n```\n\nIf provided an array-like object `pool`, the returned function will always sample from the supplied object.\n\n```javascript\nvar mysample = sample.factory( [ 1, 2, 3, 4, 5, 6 ] );\n\nvar out = mysample();\n// e.g., returns [ 2, 4, 1, 6, 5, 1 ]\n\nout = mysample();\n// e.g., returns [ 5, 2, 3, 6, 1, 4 ]\n```\n\nThe function accepts the following `options`:\n\n-   **seed**: pseudorandom number generator seed.\n-   **size**: sample size.\n-   **mutate**: `boolean` indicating whether to mutate the `pool` when sampling without replacement. Default: `false`.\n-   **replace**: `boolean` indicating whether to sample with replacement. Default: `true`.\n\nTo seed the pseudorandom number generator, set the `seed` option.\n\n```javascript\nvar mysample = sample.factory({\n    'seed': 430\n});\n\nvar out = mysample( [ 1, 2, 3, 4, 5, 6 ] );\n// e.g., returns [ 1, 1, 1, 5, 4, 4 ]\n\nmysample = sample.factory( [ 1, 2, 3, 4, 5, 6 ], {\n    'seed': 430\n});\n\nout = mysample();\n// e.g., returns [ 1, 1, 1, 5, 4, 4 ]\n```\n\nTo specify a sample size and/or override the default sample size, set the `size` option.\n\n```javascript\nvar mysample = sample.factory({\n    'size': 4\n});\n\nvar out = mysample( [ 0, 1 ] );\n// e.g., returns [ 0, 0, 0, 1 ]\n\n// Override the size option...\nout = mysample( [ 0, 1 ], {\n    'size': 1\n});\n// e.g., returns [ 1 ]\n```\n\nBy default, the returned function draws samples _with_ replacement. To override the default `replace` strategy, set the `replace` option.\n\n```javascript\nvar mysample = sample.factory({\n    'replace': false\n});\n\nvar out = mysample( [ 1, 2, 3 ] );\n// e.g., returns [ 3, 1, 2 ]\n```\n\nIf a population from which to sample is provided, the underlying `pool` remains constant for each function invocation. To mutate the `pool` by permanently removing observations when sampling _without_ replacement, set the `mutate` option.\n\n```javascript\nvar mysample = sample.factory( [ 1, 2, 3, 4, 5, 6 ], {\n    'mutate': true,\n    'replace': false,\n    'size': 3,\n    'seed': 342\n});\n\nvar out = mysample();\n// e.g., returns [ 6, 5, 3 ]\n\n// Override the mutate option...\nout = mysample({\n    'mutate': false\n});\n// e.g., returns [ 1, 2, 4 ]\n\nout = mysample();\n// e.g., returns [ 1, 2, 4 ]\n```\n\nThe returned function returns `null` after all population units are exhausted.\n\n```javascript\nvar mysample = sample.factory( [ 1, 2, 3, 4, 5, 6 ], {\n    'mutate': true,\n    'replace': false\n});\n\nvar out = mysample();\n// e.g., returns [ 3, 2, 1, 6, 5, 4 ]\n\nout = mysample();\n// returns null\n```\n\n\u003c/section\u003e\n\n\u003c!-- /.usage --\u003e\n\n\u003csection class=\"examples\"\u003e\n\n## Examples\n\n\u003c!-- eslint no-undef: \"error\" --\u003e\n\n```javascript\nvar sample = require( '@stdlib/random-sample' );\n\n// By default, sample uniformly with replacement:\nvar x = [ 'a', 'b', 'c', 'd' ];\nvar out = sample( x, {\n    'size': 10\n});\n// e.g., returns [ 'd', 'c', 'b', 'b', 'b', 'd', 'c', 'c', 'b', 'd' ]\n\n// Sample with replacement with custom probabilities:\nx = [ 'a', 'b', 'c', 'd' ];\nout = sample( x, {\n    'probs': [ 0.1, 0.1, 0.2, 0.6 ],\n    'size': 10\n});\n// e.g., returns [ 'b', 'a', 'c', 'd', 'd', 'd', 'd', 'c', 'd', 'd' ]\n\n// Sample without replacement:\nx = [ 'a', 'b', 'c', 'd' ];\nout = sample( x, {\n    'size': 3,\n    'replace': false\n});\n// e.g., returns [ 'd', 'c', 'a' ]\n\n// Sample without replacement when (initial) probabilities are nonuniform:\nx = [ 1, 2, 3, 4, 5, 6 ];\nout = sample( x, {\n    'probs': [ 0.1, 0.1, 0.1, 0.1, 0.1, 0.5 ],\n    'size': 3,\n    'replace': false\n});\n// e.g., returns [ 2, 3, 6 ]\n```\n\n\u003c/section\u003e\n\n\u003c!-- /.examples --\u003e\n\n\u003c!-- Section to include cited references. Make sure to keep an empty line after the `section` element and another before the `/section` close. --\u003e\n\n\u003csection class=\"references\"\u003e\n\n### References\n\n-   Knuth, Donald E. 1997. _The Art of Computer Programming, Volume 2 (3rd Ed.): Seminumerical Algorithms_. Boston, MA, USA: Addison-Wesley Longman Publishing Co., Inc.\n-   Vose, Michael D. 1991. \"A linear algorithm for generating random numbers with a given distribution.\" _IEEE Transactions on Software Engineering_ 17 (9): 972–75. doi:[10.1109/32.92917][@vose:1991].\n\n\u003c/section\u003e\n\n\u003c!-- /.references --\u003e\n\n\u003c!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. --\u003e\n\n\u003csection class=\"related\"\u003e\n\n\u003c/section\u003e\n\n\u003c!-- /.related --\u003e\n\n\u003c!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. --\u003e\n\n\n\u003csection class=\"main-repo\" \u003e\n\n* * *\n\n## Notice\n\nThis package is part of [stdlib][stdlib], a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing. The library provides a collection of robust, high performance libraries for mathematics, statistics, streams, utilities, and more.\n\nFor more information on the project, filing bug reports and feature requests, and guidance on how to develop [stdlib][stdlib], see the main project [repository][stdlib].\n\n#### Community\n\n[![Chat][chat-image]][chat-url]\n\n---\n\n## License\n\nSee [LICENSE][stdlib-license].\n\n\n## Copyright\n\nCopyright \u0026copy; 2016-2025. The Stdlib [Authors][stdlib-authors].\n\n\u003c/section\u003e\n\n\u003c!-- /.stdlib --\u003e\n\n\u003c!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. --\u003e\n\n\u003csection class=\"links\"\u003e\n\n[npm-image]: http://img.shields.io/npm/v/@stdlib/random-sample.svg\n[npm-url]: https://npmjs.org/package/@stdlib/random-sample\n\n[test-image]: https://github.com/stdlib-js/random-sample/actions/workflows/test.yml/badge.svg?branch=main\n[test-url]: https://github.com/stdlib-js/random-sample/actions/workflows/test.yml?query=branch:main\n\n[coverage-image]: https://img.shields.io/codecov/c/github/stdlib-js/random-sample/main.svg\n[coverage-url]: https://codecov.io/github/stdlib-js/random-sample?branch=main\n\n\u003c!--\n\n[dependencies-image]: https://img.shields.io/david/stdlib-js/random-sample.svg\n[dependencies-url]: https://david-dm.org/stdlib-js/random-sample/main\n\n--\u003e\n\n[chat-image]: https://img.shields.io/gitter/room/stdlib-js/stdlib.svg\n[chat-url]: https://app.gitter.im/#/room/#stdlib-js_stdlib:gitter.im\n\n[stdlib]: https://github.com/stdlib-js/stdlib\n\n[stdlib-authors]: https://github.com/stdlib-js/stdlib/graphs/contributors\n\n[umd]: https://github.com/umdjs/umd\n[es-module]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules\n\n[deno-url]: https://github.com/stdlib-js/random-sample/tree/deno\n[deno-readme]: https://github.com/stdlib-js/random-sample/blob/deno/README.md\n[umd-url]: https://github.com/stdlib-js/random-sample/tree/umd\n[umd-readme]: https://github.com/stdlib-js/random-sample/blob/umd/README.md\n[esm-url]: https://github.com/stdlib-js/random-sample/tree/esm\n[esm-readme]: https://github.com/stdlib-js/random-sample/blob/esm/README.md\n[branches-url]: https://github.com/stdlib-js/random-sample/blob/main/branches.md\n\n[stdlib-license]: https://raw.githubusercontent.com/stdlib-js/random-sample/main/LICENSE\n\n[@vose:1991]: https://doi.org/10.1109/32.92917\n\n\u003c/section\u003e\n\n\u003c!-- /.links --\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstdlib-js%2Frandom-sample","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fstdlib-js%2Frandom-sample","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstdlib-js%2Frandom-sample/lists"}