How to resolve the algorithm Lah numbers step by step in the jq programming language

Published on 12 May 2024 09:40 PM
#Jq

How to resolve the algorithm Lah numbers step by step in the jq programming language

Table of Contents

Problem Statement

Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets. Lah numbers are closely related to Stirling numbers of the first & second kinds, and may be derived from them. Lah numbers obey the identities and relations:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Lah numbers step by step in the jq programming language

Source code in the jq programming language

## Generic functions

def factorial: reduce range(2;.+1) as $i (1; . * $i);

# nCk assuming n >= k
def binomial($n; $k): 
  if $k > $n / 2 then binomial($n; $n-$k)
  else (reduce range($k+1; $n+1) as $i (1; . * $i)) as $numerator
  | reduce range(1;1+$n-$k) as $i ($numerator; . / $i)
  end;

def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;

def max(s): reduce s as $x (-infinite; if $x > . then $x else . end);

def lah($n; $k; $signed):
    if $n == $k then 1
    elif $n == 0 or $k == 0 or $k > $n then 0
    elif $k == 1 then $n|factorial
    else
       (binomial($n; $k) * binomial($n - 1; $k - 1) * (($n - $k)|factorial)) as $unsignedvalue
        | if $signed and ($n % 1 == 1)
          then -$unsignedvalue
          else $unsignedvalue
          end
    end;

def lah($n; $k): lah($n;$k;false);

def printlahtable($kmax):
  def pad: lpad(12);
  reduce range(0;$kmax+1) as $k ("n/k"|lpad(4); . + ($k|pad)),
  (range(0; $kmax+1) as $n
   | reduce range(0;$n+1) as $k ($n|lpad(4);
       . + (lah($n; $k) | pad)) ) ;

def task:
 "Unsigned Lah numbers up to n==12",
 printlahtable(12), "",
 "The maxiumum of lah(100, _) is: \(max( lah(100; range(0;101)) ))"
 ;

task

  

You may also check:How to resolve the algorithm Apply a callback to an array step by step in the Pop11 programming language
You may also check:How to resolve the algorithm Program termination step by step in the GW-BASIC programming language
You may also check:How to resolve the algorithm Tokenize a string step by step in the Pop11 programming language
You may also check:How to resolve the algorithm Assertions step by step in the Lasso programming language
You may also check:How to resolve the algorithm Menu step by step in the Logo programming language