How to resolve the algorithm Combinations step by step in the CoffeeScript programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Combinations step by step in the CoffeeScript programming language

Table of Contents

Problem Statement

Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted).

3   comb   5     is: If it is more "natural" in your language to start counting from   1   (unity) instead of   0   (zero), the combinations can be of the integers from   1   to   n.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Combinations step by step in the CoffeeScript programming language

Source code in the coffeescript programming language

combinations = (n, p) ->
  return [ [] ] if p == 0
  i = 0
  combos = []
  combo = []
  while combo.length < p
    if i < n
      combo.push i
      i += 1
    else
      break if combo.length == 0
      i = combo.pop() + 1
      
    if combo.length == p
      combos.push clone combo
      i = combo.pop() + 1
  combos

clone = (arr) -> (n for n in arr)

N = 5
for i in [0..N]
  console.log "------ #{N} #{i}"
  for combo in combinations N, i
    console.log combo


  

You may also check:How to resolve the algorithm Sorting algorithms/Gnome sort step by step in the jq programming language
You may also check:How to resolve the algorithm The Name Game step by step in the Arturo programming language
You may also check:How to resolve the algorithm Formatted numeric output step by step in the Phix programming language
You may also check:How to resolve the algorithm Bifid cipher step by step in the Nim programming language
You may also check:How to resolve the algorithm Delete a file step by step in the Phix programming language