In Go, you can calculate permutations and combinations using combinatorial formulas and loops. Here are the steps to calculate permutations and combinations in Go:
math
package to access mathematical functions:import (
"fmt"
"math"
)
func factorial(n int) int {
if n == 0 {
return 1
}
return n * factorial(n-1)
}
n
and r
(where n
is the total number of elements and r
is the number of elements in each permutation):func permutations(n, r int) int {
return factorial(n) / factorial(n-r)
}
n
and r
as arguments:func combinations(n, r int) int {
return factorial(n) / (factorial(r) * factorial(n-r))
}
func main() {
n := 5 // Total number of elements
r := 3 // Number of elements in each permutation or combination
fmt.Println("Permutations:", permutations(n, r))
fmt.Println("Combinations:", combinations(n, r))
}
In the above example, n
is set to 5 and r
is set to 3. The output will be:
Permutations: 60
Combinations: 10
These calculations are based on the formulas: nPr = n! / (n-r)!
for permutations and nCr = n! / (r! * (n-r)!)
for combinations.