How to resolve the algorithm Permutations step by step in the UNIX Shell programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Permutations step by step in the UNIX Shell programming language

Table of Contents

Problem Statement

Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!)

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Permutations step by step in the UNIX Shell programming language

Source code in the unix programming language

function permute {
  if (( $# == 1 )); then
    set -- $(seq $1)
  fi
  local A=("$@")
  permuteAn "$#"
}

function permuteAn {
  # print all permutations of first n elements of the array A, with remaining
  # elements unchanged.
  local -i n=$1 i
  shift
  if (( n == 1 )); then
    printf '%s\n' "${A[*]}"
  else
    permuteAn $(( n-1 ))
    for (( i=0; i
      local -i k
      (( k=n%2 ? 0: i ))
      local t=${A[k]}
      A[k]=${A[n-1]}
      A[n-1]=$t
      permuteAn $(( n-1 ))
    done
  fi
}

function permuteAn {
  # print all permutations of first n elements of the array A, with remaining
  # elements unchanged.
  local -i n=$1 i
  shift
  if (( n == 1 )); then
    printf '%s\n' "${A[*]}"
  else
    permuteAn $(( n-1 ))
    for (( i=1; i
      local -i k
      (( k=n%2 ? 1 : i ))
      local t=$A[k]
      A[k]=$A[n]
      A[n]=$t
      permuteAn $(( n-1 ))
    done
  fi
}

  

You may also check:How to resolve the algorithm Walk a directory/Recursively step by step in the PowerShell programming language
You may also check:How to resolve the algorithm Hofstadter Figure-Figure sequences step by step in the C# programming language
You may also check:How to resolve the algorithm Stack step by step in the Tailspin programming language
You may also check:How to resolve the algorithm Ordered words step by step in the Factor programming language
You may also check:How to resolve the algorithm Exceptions/Catch an exception thrown in a nested call step by step in the Amazing Hopper programming language