Movatterモバイル変換


[0]ホーム

URL:


combinations

packagemodule
v1.2.0Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2022 License:MITImports:1Imported by:42

Details

Repository

github.com/mxschmitt/golang-combinations

Links

README

Golang combinations

GoDocGoCoverage StatusGo Report CardLicense

This package provides a method to generate all ordered combinations out of a given string array.This essentially creates the powerset of the given array except that the empty set is disregarded.

Examples

Take a look at thegodoc for examples.

In general when you have e.g.[]string{"A", "B", "C"} you will get:

[    ["A"],    ["B"],    ["A", "B"],    ["C"],    ["A", "C"],    ["B", "C"],    ["A", "B", "C"]]

Background

The algorithm iterates over each number from1 to2^length(input), separating it by binary components and utilizes the true/false interpretation of binary 1's and 0's to extract all unique ordered combinations of the input slice.

E.g. a binary number0011 means selecting the first and second index from the slice and ignoring the third and fourth. For input{"A", "B", "C", "D"} this signifies the combination{"A", "B"}.

For input slice{"A", "B", "C", "D"} there are2^4 - 1 = 15 binary combinations, so mapping each bit position to a slice index and selecting the entry for binary1 and discarding for binary0 gives the full subset as:

1=0001=>---A=>{"A"}2=0010=>--B-=>{"B"}3=0011=>--BA=>{"A", "B"}4=0100=>-C--=>{"C"}5=0101=>-C-A=>{"A", "C"}6=0110=>-CB-=>{"B", "C"}7=0111=>-CBA=>{"A", "B", "C"}8=1000=>D---=>{"D"}9=1001=>D--A=>{"A", "D"}10=1010=>D-B-=>{"B", "D"}11=1011=>D-BA=>{"A", "B", "D"}12=1100=>DC--=>{"C", "D"}13=1101=>DC-A=>{"A", "C", "D"}14=1110=>DCB-=>{"B", "C", "D"}15=1111=>DCBA=>{"A", "B", "C", "D"}

Documentation

Overview

Package combinations provides a method to generate all combinations out of a given string array.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

funcAll

func All[Tany](set []T) (subsets [][]T)

All returns all combinations for a given string array.This is essentially a powerset of the given set except that the empty set is disregarded.

Example
combinations := All([]string{"A", "B", "C"})fmt.Println(combinations)
Output:[[A] [B] [A B] [C] [A C] [B C] [A B C]]

funcCombinationsadded inv1.1.0

func Combinations[Tany](set []T, nint) (subsets [][]T)

Combinations returns combinations of n elements for a given string array.For n < 1, it equals to All and returns all combinations.

Types

This section is empty.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp