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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Combinations step by step in the Nim 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 Nim programming language

Source code in the nim programming language

iterator comb(m, n: int): seq[int] =
  var c = newSeq[int](n)
  for i in 0 ..< n: c[i] = i

  block outer:
    while true:
      yield c

      var i = n - 1
      inc c[i]
      if c[i] <= m - 1: continue

      while c[i] >= m - n + i:
        dec i
        if i < 0: break outer
      inc c[i]
      while i < n-1:
        c[i+1] = c[i] + 1
        inc i

for i in comb(5, 3):
  echo i


iterator combinations(m: int, n: int): seq[int] =

  var result = newSeq[int](n)
  var stack = newSeq[int]()
  stack.add 0

  while stack.len > 0:
    var index = stack.high
    var value = stack.pop()

    while value < m:
      result[index] = value
      inc value
      inc index
      stack.add value

      if index == n:
        yield result
        break
 
for i in combinations(5, 3):
  echo i


  

You may also check:How to resolve the algorithm Literals/String step by step in the Groovy programming language
You may also check:How to resolve the algorithm Compile-time calculation step by step in the C3 programming language
You may also check:How to resolve the algorithm Munchausen numbers step by step in the VBScript programming language
You may also check:How to resolve the algorithm Abundant odd numbers step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Check input device is a terminal step by step in the Ring programming language