|
| 1 | +(function (exports) { |
| 2 | + 'use strict'; |
| 3 | + |
| 4 | + var variationsWithRepetion = (function () { |
| 5 | + var res; |
| 6 | + |
| 7 | + function variations(arr, k, index, current) { |
| 8 | + if (k === index) { |
| 9 | + return res.push(current.slice()); |
| 10 | + } |
| 11 | + for (var i = 0; i < arr.length; i += 1) { |
| 12 | + current[index] = arr[i]; |
| 13 | + variations(arr, k, index + 1, current); |
| 14 | + } |
| 15 | + } |
| 16 | + |
| 17 | + /** |
| 18 | + * Finds all the variations with repetition of given array.<br><br> |
| 19 | + * Variations with repetition is the number of ways to sample k elements |
| 20 | + * from a set of elements (which may be repeated). |
| 21 | + * |
| 22 | + * @example |
| 23 | + * var variations = require('path-to-algorithms/src/combinatorics/' + |
| 24 | + * 'variations-repetition').variationsWithRepetion; |
| 25 | + * var result = variations(['apple', 'orange', 'pear'], 2); |
| 26 | + * |
| 27 | + * // [['apple', 'apple'], |
| 28 | + * // ['apple', 'orange'], |
| 29 | + * // ['apple', 'pear'], |
| 30 | + * // ['orange', 'apple'], |
| 31 | + * // ['orange', 'orange'], |
| 32 | + * // ['orange', 'pear'], |
| 33 | + * // ['pear', 'apple'], |
| 34 | + * // ['pear', 'orange'], |
| 35 | + * // ['pear', 'pear']] |
| 36 | + * console.log(result); |
| 37 | + * |
| 38 | + * @module combinatorics/variations-repetition |
| 39 | + * @public |
| 40 | + * @param arr {Array} Set of items. |
| 41 | + * @param k {Number} Size of each combination. |
| 42 | + * @return {Array} Returns all combinations. |
| 43 | + */ |
| 44 | + return function (arr, k) { |
| 45 | + res = []; |
| 46 | + variations(arr, k, 0, []); |
| 47 | + var temp = res; |
| 48 | + res = undefined; |
| 49 | + return temp; |
| 50 | + }; |
| 51 | + }()); |
| 52 | + |
| 53 | + exports.variationsWithRepetion = variationsWithRepetion; |
| 54 | + |
| 55 | +}((typeof window === 'undefined') ? module.exports : window)); |
0 commit comments