Repository: MarcinMoskala/KotlinDiscreteMathToolkit
Branch: master
Commit: 17a7329af042
Files: 37
Total size: 59.1 KB
Directory structure:
gitextract_4rnnvbxx/
├── .gitignore
├── .travis.yml
├── KotlinDiscreteMathToolkit.iml
├── README.md
├── _config.yml
├── build.gradle
├── gradle/
│ └── wrapper/
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── src/
├── main/
│ └── java/
│ └── com/
│ └── marcinmoskala/
│ └── math/
│ ├── CartesianProductExt.kt
│ ├── CombinationsExt.kt
│ ├── FactorialFun.kt
│ ├── IterableMultiplication.kt
│ ├── NumSplitFunc.kt
│ ├── NumbersDivisible.kt
│ ├── PermutationsExt.kt
│ ├── Power.kt
│ ├── PowersetExt.kt
│ ├── ProductExt.kt
│ ├── SetSplitFunc.kt
│ └── SublistsBySplittersExt.kt
└── test/
└── java/
└── com/
└── marcinmoskala/
└── math/
└── tests/
├── CartesianProductPropertyTest.kt
├── CartesianProductTest.kt
├── CombinationTest.kt
├── CombinationWithRepetitionTest.kt
├── FactorialTest.kt
├── IterableMultipliationTest.kt
├── JavaTest.java
├── NumberSplitTest.kt
├── NumbersDivisibleTest.kt
├── PermutationTest.kt
├── PowerTest.kt
├── PowersetTest.kt
├── ProductTest.kt
├── SetSplitTest.kt
├── SublistsBySplittersTest.kt
└── TestUtils.kt
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
*.class
*.jar
*.war
*.ear
/.idea/
DiscreteMathToolkit.iml
out/
gradle.properties
*.log
*.ctxt
.mtj.tmp/
*.zip
*.tar.gz
*.rar
hs_err_pid*
.gradle/
build/
================================================
FILE: .travis.yml
================================================
language: java
jdk:
- oraclejdk8
install: true
script:
- ./gradlew check
after_success:
- bash <(curl -s https://codecov.io/bash)
================================================
FILE: KotlinDiscreteMathToolkit.iml
================================================
================================================
FILE: README.md
================================================
# DiscreteMathToolkit
Set of extensions for Kotlin that provides Discrete Math functionalities as an Kotlin extension functions.
[](https://maven-badges.herokuapp.com/maven-central/com.marcinmoskala/DiscreteMathToolkit)
[](https://travis-ci.org/MarcinMoskala/KotlinDiscreteMathToolkit)
[](https://codecov.io/gh/MarcinMoskala/KotlinDiscreteMathToolkit)
[](https://codebeat.co/projects/github-com-marcinmoskala-kotlindiscretemathtoolkit-master)
[](https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit)
To stay current with news about library [](https://twitter.com/marcinmoskala?ref_src=twsrc%5Etfw)
# Permutations
```kotlin
setOf(1, 2, 3).permutations() // {[1, 2, 3], [2, 1, 3], [3, 2, 1], [1, 3, 2], [2, 3, 1], [3, 1, 2]}
setOf(1, 2, 3).permutationsNumber() // 6
listOf(1, 2, 2).permutations() // {[1, 2, 2], [2, 1, 2], [2, 2, 1]}
listOf(1, 2, 2).permutationsNumber() // 3
```
More examples [here](https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit/blob/master/src/test/java/com/marcinmoskala/math/tests/PermutationTest.kt)
# Combinations
```kotlin
setOf(1, 2, 3, 4).combinations(3) // { {1, 2, 3}, {1, 2, 4}, {1, 4, 3}, {4, 2, 3} }
setOf(1, 2, 3, 4).combinationNumber(3) // 4
setOf(1, 2, 3, 4).combinationsWithRepetitions(2) // [{1=2}, {1=1, 2=1}, {1=1, 3=1}, {1=1, 4=1}, {2=2}, {2=1, 3=1}, {2=1, 4=1}, {3=2}, {3=1, 4=1}, {4=2}]
setOf(1, 2, 3, 4).combinationsWithRepetitionsNumber(2) // 10
```
More examples [here](https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit/blob/master/src/test/java/com/marcinmoskala/math/tests/CombinationTest.kt) and [here](https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit/blob/master/src/test/java/com/marcinmoskala/math/tests/CombinationWithRepetitionTest.kt)
# Powerset
Powerset of any set S is the set of all subsets of S, including the empty set and S itself.
```kotlin
setOf(1, 2, 3).powerset() // { {}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3} }
setOf(1, 2, 3).powersetSize() // 8
```
# Product
Product is the result of multiplying.
```kotlin
(3..4).product() // 12
listOf(10, 10, 10).product() // 1000
```
More examples [here](https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit/blob/master/src/test/java/com/marcinmoskala/math/tests/ProductTest.kt).
# Factorial
Factorian of n (n!) is a product of all positive integers less than or equal to n.
```kotlin
3.factorial() // 6L
10.factorial() // 3628800L
20.factorial() // 2432902008176640000L
```
More examples [here](https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit/blob/master/src/test/java/com/marcinmoskala/math/tests/FactorialTest.kt).
# Numbers divisible and non-divisible by
```kotlin
(1..1000).countNonDivisiveBy(2) // 500
(1..1000).countNonDivisiveBy(3) // 777
(1..1000).countNonDivisiveBy(2, 6, 13) // 462
(1..1000).countNonDivisiveBy(3, 7, 11) // 520
(1..1000).countDivisiveBy(2) // 500
(1..1000).countDivisiveBy(3) // 333
(1..1000).countDivisiveBy(2, 6, 13) // 538
(1..1000).countDivisiveBy(3, 7, 11) // 480
```
More examples [here](https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit/blob/master/src/test/java/com/marcinmoskala/math/tests/NumbersDivisibleTest.kt).
# Splits of sets and numbers
In Descrete Math there are two functions used to count number of splits:
S(n, k) - Stirling function - number of splits of n different elements to k groups
P(n, k) - number of splits of n identical elements to k groups
```kotlin
(1..n).toSet().splitsNumber(1) // 1
(1..n).toSet().splitsNumber(n) // 1
setOf(1, 2, 3).splitsNumber(2) // 3
setOf(1, 2, 3, 4).splitsNumber(2) // 7
setOf(1, 2, 3, 4, 5).splitsNumber(3) // 25
setOf(1, 2, 3, 4, 5, 6, 7).splitsNumber(4) // 350
setOf(1, 2, 3).splits(2) // { { {1, 2}, {3} },{ {1, 3}, {2} },{ {3, 2}, {1} } }
```
More examples [here](https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit/blob/master/src/test/java/com/marcinmoskala/math/tests/SetSplitTest.kt)
```kotlin
n.splitsNumber(1) // 1
n.splitsNumber(n) // 1
7.splitsNumber(4) // 3
11.splitsNumber(4) // 11
9.splitsNumber(5) // 5
13.splitsNumber(8) // 7
```
More examples [here](https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit/blob/master/src/test/java/com/marcinmoskala/math/tests/NumberSplitTest.kt)
# Iterable multiplication
Multiplication of iterables returns iterable with pairs of each possible connections of elements from first and iterable:
```kotlin
listOf(1, 2) * listOf("A", "B") // returns List>
// [(1, "A"), (1, "B"), (2, "A"), (2, "B")]
listOf('a', 'b') * listOf(1, 2) * listOf("A", "B") // returns List>
// [
// ('a', 1, "A"), ('a', 1, "B"),
// ('a', 2, "A"), ('a', 2, "B"),
// ('b', 1, "A"), ('b', 1, "B"),
// ('b', b, "A"), ('b', 2, "B")
// ]
```
More examples [here](https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit/blob/master/src/test/java/com/marcinmoskala/math/tests/IterableMultipliationTest.kt).
# Cartesian product of lists
Similar to iterable multiplication but produces sequence of lists:
```kotlin
listOf('A', 'B', 'C', D).cartesianProduct(listOf('x', 'y')) // returns List>
// [
// ['A', 'x'],
// ['A', 'y'],
// ['B', 'x'],
// ['B', 'y'],
// ['C', 'x'],
// ['C', 'y'],
// ['D', 'x'],
// ['D', 'y']
// ]
listOf(0, 1).cartesianProduct(repeat = 2) // returns List>
// [
// [0, 0],
// [0, 1],
// [1, 0],
// [1, 1]
// ]
listOf(1, 2).cartesianProduct(listOf("ABC")) // returns List>
// [
// [1, "ABC"],
// [2, "ABC"]
// ]
```
More examples [here](https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit/blob/master/src/test/java/com/marcinmoskala/math/tests/CartesianProductTest.kt).
# Java support
Library is fully supporting usage from Java. All functions can be used as static function of DiscreteMath. For example:
```java
DiscreteMath.permutationsNumber(set)
DiscreteMath.permutationsNumber(list)
DiscreteMath.factorial(10) // 3628800L
```
Returned list and sets are Java standard lists and sets. More examples of Java usage [here](https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit/blob/master/src/test/java/com/marcinmoskala/math/tests/JavaTest.java).
# Install
Gradle:
```groovy
compile "com.marcinmoskala:DiscreteMathToolkit:1.0.3"
```
Maven:
```
com.marcinmoskala
DiscreteMathToolkit
1.0.3
```
Jar to download together with sources and javadoc can be found on [Maven Central](http://search.maven.org/#search%7Cga%7C1%7Cmarcinmoskala).
License
-------
Copyright 2017 Marcin Moskała
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: _config.yml
================================================
theme: jekyll-theme-midnight
================================================
FILE: build.gradle
================================================
apply plugin: 'kotlin'
if (project.hasProperty("signing.keyId")) {
apply plugin: 'signing'
}
apply plugin: 'maven-publish'
apply plugin: "jacoco"
repositories {
mavenCentral()
}
buildscript {
ext.kotlin_version = '1.3.72'
ext.junit_version = '5.6.1'
ext.kotest_version = '4.0.6'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
jacocoTestReport {
reports {
xml.enabled = true
html.enabled = true
}
}
check.dependsOn jacocoTestReport
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version"
testImplementation "org.junit.jupiter:junit-jupiter-engine:$junit_version"
testImplementation "io.kotest:kotest-runner-junit5-jvm:$kotest_version"
testImplementation "io.kotest:kotest-property-jvm:$kotest_version"
}
// Publishing
test {
// show standard out and standard error of the test JVM(s) on the console
testLogging.showStandardStreams = true
}
task sourceJar(type: Jar) {
classifier "sources"
from sourceSets.main.allJava
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier "javadoc"
from javadoc.destinationDir
}
artifacts {
archives sourceJar, javadocJar
}
signing {
sign configurations.archives
}
publishing {
publications {
mavenJava(MavenPublication) {
customizePom(pom)
groupId "com.marcinmoskala"
artifactId "DiscreteMathToolkit"
version '1.0.5'
from components.java
// create the sign pom artifact
pom.withXml {
def pomFile = file("${project.buildDir}/generated-pom.xml")
writeTo(pomFile)
def pomAscFile = signing.sign(pomFile).signatureFiles[0]
artifact(pomAscFile) {
classifier = null
extension = 'pom.asc'
}
}
artifact(sourceJar) {
classifier = 'sources'
}
artifact(javadocJar) {
classifier = 'javadoc'
}
// create the signed artifacts
project.tasks.signArchives.signatureFiles.each {
artifact(it) {
def matcher = it.file =~ /-(sources|javadoc)\.jar\.asc$/
if (matcher.find()) {
classifier = matcher.group(1)
} else {
classifier = null
}
extension = 'jar.asc'
}
}
}
}
repositories {
maven {
url "https://oss.sonatype.org/service/local/staging/deploy/maven2"
credentials {
username sonatypeUsername
password sonatypePassword
}
}
}
}
def customizePom(pom) {
pom.withXml {
def root = asNode()
root.dependencies.removeAll { dep ->
dep.scope == "test"
}
root.children().last() + {
resolveStrategy = Closure.DELEGATE_FIRST
name 'DescreteMathToolkit'
description 'Set of extensions for Kotlin that provides Discrete Math functionalities as an Kotlin extension functions.'
url 'https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit'
scm {
connection 'scm:https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit'
developerConnection 'scm:https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit'
url 'https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit'
}
licenses {
license {
name 'The Apache License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
}
}
developers {
developer {
id 'MarcinMoskala'
name 'Marcin Moskala'
email 'marcinmoskala@gmail.com'
}
}
}
}
}
model {
tasks.generatePomFileForMavenJavaPublication {
destination = file("$buildDir/generated-pom.xml")
}
tasks.publishMavenJavaPublicationToMavenLocal {
dependsOn project.tasks.signArchives
}
tasks.publishMavenJavaPublicationToMavenRepository {
dependsOn project.tasks.signArchives
}
}
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Mon Jun 08 23:32:02 CEST 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.5.1-all.zip
================================================
FILE: gradlew
================================================
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save ( ) {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: src/main/java/com/marcinmoskala/math/CartesianProductExt.kt
================================================
@file:JvmName("DiscreteMath")
@file:JvmMultifileClass
package com.marcinmoskala.math
/**
* Cartesian product of a list with itself, specify the number of repetitions with the optional repeat keyword argument.
* For example, A.cartesianProduct(repeat=4) means the same as A.cartesianProduct(A, A, A).
* Throws an [IllegalArgumentException]: if [repeat] is less or equals to 0
* Throws an [IllegalArgumentException]: if size of result should exceeds [Int.MAX_VALUE]
*/
fun List.cartesianProduct(repeat: Int = 2): Sequence> {
require(repeat > 0) { "Parameter repeat should be greater than 0" }
return product(*Array(repeat) { this })
}
/**
* Cartesian product of lists.
* Throws an [IllegalArgumentException]: if size of result should exceeds [Int.MAX_VALUE]
*/
fun List.cartesianProduct(vararg lists: List): Sequence> =
product(this, *lists)
private fun product(vararg iterables: List): Sequence> = sequence {
require(iterables.map { it.size.toLong() }.reduce(Long::times) <= Int.MAX_VALUE) {
"Cartesian product function can produce result whose size does not exceed Int.MAX_VALUE"
}
val numberOfIterables = iterables.size
val lstLengths = ArrayList()
val lstRemaining = ArrayList(listOf(1))
iterables.reversed().forEach {
lstLengths.add(0, it.size)
lstRemaining.add(0, it.size * lstRemaining[0])
}
val nProducts = lstRemaining.removeAt(0)
(0 until nProducts).forEach { product ->
val result = ArrayList()
(0 until numberOfIterables).forEach { iterableIndex ->
val elementIndex = product / lstRemaining[iterableIndex] % lstLengths[iterableIndex]
result.add(iterables[iterableIndex][elementIndex])
}
yield(result.toList())
}
}
================================================
FILE: src/main/java/com/marcinmoskala/math/CombinationsExt.kt
================================================
@file:JvmName("DiscreteMath")
@file:JvmMultifileClass
package com.marcinmoskala.math
/**
* In mathematics, a combination is a way of selecting items from a collection, such that (unlike permutations) the
* order of selection does not matter.
*
* For set {1, 2, 3}, 2 elements combinations are {1, 2}, {2, 3}, {1, 3}.
* All possible combinations is called 'powerset' and can be found as an
* extension function for set under this name
*/
fun Set.combinations(combinationSize: Int): Set> = when {
combinationSize < 0 -> throw Error("combinationSize cannot be smaller then 0. It is equal to $combinationSize")
combinationSize == 0 -> setOf(setOf())
combinationSize >= size -> setOf(toSet())
else -> powerset()
.filter { it.size == combinationSize }
.toSet()
}
fun Set.combinationsNumber(combinationSize: Int): Long = when {
combinationSize < 0 -> throw Error("combinationSize cannot be smaller then 0. It is equal to $combinationSize")
combinationSize >= size || combinationSize == 0 -> 1
else -> size.factorial() / (combinationSize.factorial() * (size - combinationSize).factorial())
}
fun Set.combinationsWithRepetitions(combinationSize: Int): Set