How to resolve the algorithm Determinant and permanent step by step in the Scala programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Determinant and permanent step by step in the Scala programming language

Table of Contents

Problem Statement

For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by while the permanent is given by In both cases the sum is over the permutations

σ

{\displaystyle \sigma }

of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.) More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Determinant and permanent step by step in the Scala programming language

Source code in the scala programming language

def permutationsSgn[T]: List[T] => List[(Int,List[T])] = {
  case Nil => List((1,Nil))
  case xs => {
    for {
      (x, i) <- xs.zipWithIndex
      (sgn,ys) <- permutationsSgn(xs.take(i) ++ xs.drop(1 + i))
    } yield {
      val sgni = sgn * (2 * (i%2) - 1)
      (sgni, (x :: ys))
    }
  }
}

def det(m:List[List[Int]]) = {
  val summands =
    for {
      (sgn,sigma) <- permutationsSgn((0 to m.length - 1).toList).toList
    }
    yield {
      val factors =
        for (i <- 0 to (m.length - 1))
        yield m(i)(sigma(i))
      factors.toList.foldLeft(sgn)({case (x,y) => x * y})
    }
  summands.toList.foldLeft(0)({case (x,y) => x + y})


  

You may also check:How to resolve the algorithm Abstract type step by step in the Haskell programming language
You may also check:How to resolve the algorithm FizzBuzz step by step in the APEX programming language
You may also check:How to resolve the algorithm Include a file step by step in the Racket programming language
You may also check:How to resolve the algorithm Balanced brackets step by step in the Component Pascal programming language
You may also check:How to resolve the algorithm Even or odd step by step in the Asymptote programming language