usingMaths.com
From Theory to Practice - Math You Can Use.







<< PreviousNext >>

Selection With Repetition in JavaScript | Maths Fun Exercise



Possible Selections With Repetition. | Maths Explanation for JavaScript Kids

Selection with repetition is a core concept in combinatorial mathematics and appears frequently in probability theory, algorithm design, and computational problem-solving. In this tutorial, we demonstrate how to implement selection with repetition in JavaScript, allowing elements to be chosen multiple times while generating all valid combinations.

This page focuses on the algorithmic approach, explains the underlying logic, and provides a clear JavaScript implementation suitable for tertiary-level study.

What Is Selection With Repetition?

In combinatorics, selection with repetition (also known as *combinations with repetition*) refers to the process of selecting items from a set where each item may be chosen more than once and where order does not matter.

For example, selecting 3 items from {A, B, C} with repetition allowed produces combinations such as:

  • A, A, A
  • A, A, B
  • A, B, B
  • B, C, C

This concept differs from permutations and combinations without repetition, where either order matters or repeated elements are disallowed.

Imagine being given the opportunity to pick six (6) exercise books from a book-shop having 10 different brands of exercise books - Ben 10, Chelsea F.C., Superman, Tottenham F.C., Indomitables, Manchester City F.C., Spider Man, Power Rangers, Liverpool F.C. and Bat Man exercise books.
If you happen to be a big Power Rangers fan, nothing stops you from selecting all 6 exercise books to be Power Rangers exercise books.
But you can as well decide to pick only 3 Power Rangers exercise books and make up for the other 3 with any other brands of exercise book.

Whether you are calculating possible outcomes for a game, managing inventory combinations, or building a JavaScript math algorithm, understanding how to handle multisets is essential.


The nCr with Repetition Formula

To find the total number of ways to select items when repetition is allowed, we use a variation of the standard binomial coefficient. The formula for combinations with repetition is:

$$ \binom{n + r - 1}{r} = \frac{(n + r - 1)!}{r!(n - 1)!} $$

Where:

  • n = The number of distinct types of items to choose from.
  • r = The number of items being selected.

This is often visualized using the stars and bars method, where "stars" represent the items and "bars" represent the dividers between different categories.

Selection With vs Without Repetition

Comparison of Selection With and Without Repetition
FeatureWith RepetitionWithout Repetition
Repeated elements allowedYesNo
Order mattersNoNo
Common use casesProbability, modellingSampling, grouping
Algorithm styleRecursive / IterativeRecursive / Iterative

Understanding this distinction is essential when solving combinatorial selection problems in programming.


Selection With Repetition in JavaScript

To generate combinations with repetition in JavaScript, we typically use a recursive algorithm. Recursion allows us to build combinations incrementally while controlling the index from which elements may be selected, ensuring that duplicates and invalid orderings are avoided.

This approach is efficient, readable, and well suited for teaching JavaScript combinatorics.

JavaScript Selection With Repetition Algorithm

The algorithm for Selection with Repetition will be a lot similar to that of combination.

The selection with repetition algorithm follows these steps:

  1. Start with an empty selection array.
  2. At each recursive call, allow selection from the current index onward.
  3. Add the selected element to the current combination.
  4. Repeat until the desired selection length is reached.
  5. Store or output the completed combination.

By restricting future selections to the current index or higher, the algorithm ensures that combinations are generated without duplication while still allowing repetition.

This is how our Repetitive Selection code in JavaScript will work.

Create 2 new files; On Notepad++: File, New.
Call them SelectionWithRepetition.html and SelectionWithRepetition.js respectively.
Type out the adjoining JavaScript code for Selection with Repetition.


Why Use This JavaScript Algorithm?

Using a JavaScript combinations algorithm is vital for web-based tools that require real-time probability calculations. Common use cases include:

  • Multiset Generation: Listing all unique ways to group items.
  • Sampling with Replacement: Statistical modeling where items are returned to the pool after selection.
  • Resource Allocation: Distributing r identical units into n distinct bins.

Applications of Selection With Repetition

Selection with repetition is commonly used in:

  • Generating test cases for software development
  • Modeling probability and statistics problems
  • Creating secure password or key combinations
  • Resource allocation problems
  • Algorithm design exercises
  • Exploring mathematical concepts like combinatorics in JavaScript tutorials

The JavaScript approach shown here can be adapted easily for larger datasets or integrated into more complex applications.


Summary: JavaScript Selection with Repetition Algorithm

Selection with repetition is a fundamental concept in combinatorics that allows us to choose items from a set where each element can be selected more than once. In programming, this is often implemented using JavaScript recursive algorithms to generate combinations with repetition.

Combinatorics provides the mathematical foundation for solving problems involving group selection. By applying these principles in JavaScript math algorithms, developers can create efficient solutions for tasks such as generating password combinations, simulating probability distributions, or building test cases.










JavaScript Code for Selection with Repetition - .html

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Selection</title>
        <script src="SelectionWithRepetition.js"></script>
    </head>
    <body>

        <h3>Possible Selections with Repetition</h3>
        <!-- This is where the result will be displayed when it is ready.-->
        <div id="word_select"></div>

        <script>
            var result =
                    groupSelection([0123456789]3);
            var print = "", set, count = 0;
            for (set in result) {
                print += ++count + ": [" + result[set].join(", ") + "]<br/>";
            }
            document.getElementById("word_select").innerHTML +=
                    words.join(", ") + " selection " + r + ":<br/><br/>" + print +
                    "<br/><br/>Number of ways is " + count + ".";
        </script>

    </body>
</html>


JavaScript Code for Selection with Repetition - .js

var words;
var r; // min length of word
var i;
var complete_group = {}, c_index = 0;


function groupSelection(candidates, size) {
    words = candidates;
    r = size;

    i = 0;
    recursiveFillUp([]);
    return complete_group;
}

// pick elements recursively
function recursiveFillUp(temp) {
    var picked_elements = [];
    var j = i;
    while (< words.length) {
        picked_elements[j] = temp.slice(0);
        picked_elements[j].push(words[j]);
        // recoil factor
        if (>= words.length) {
            i = j;
        }
        // satisfied yet?
        if (picked_elements[j].length == r) {
            complete_group[c_index++] = picked_elements[j];
        } else if (picked_elements[j].length < r) {
            recursiveFillUp(picked_elements[j]);
        }
        j++;
    }
    if (picked_elements[--j] !== undefined && picked_elements[j].length == r) {
        i++// keep recoil factor straightened out
    }
}





<< PreviousNext >>