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. [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.marcinmoskala/DiscreteMathToolkit/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.marcinmoskala/DiscreteMathToolkit) [![Build Status](https://travis-ci.org/MarcinMoskala/KotlinDiscreteMathToolkit.svg?branch=master)](https://travis-ci.org/MarcinMoskala/KotlinDiscreteMathToolkit) [![codecov](https://codecov.io/gh/MarcinMoskala/KotlinDiscreteMathToolkit/branch/master/graph/badge.svg)](https://codecov.io/gh/MarcinMoskala/KotlinDiscreteMathToolkit) [![codebeat badge](https://codebeat.co/badges/70bb9b0e-a47e-477a-933d-adc7220ae926)](https://codebeat.co/projects/github-com-marcinmoskala-kotlindiscretemathtoolkit-master) [![Analytics](https://ga-beacon.appspot.com/UA-92159206-7/main-page?pixel)](https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit) To stay current with news about library [![Twitter URL](https://img.shields.io/twitter/url/https/twitter.com/fold_left.svg?style=social&label=Follow%20%40marcinmoskala)](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> = when { combinationSize < 0 -> throw Error("combinationSize cannot be smaller then 0. It is equal to $combinationSize") combinationSize == 0 -> setOf(mapOf()) else -> combinationsWithRepetitions(combinationSize - 1) .flatMap { subset -> this.map { subset + (it to (subset.getOrElse(it) { 0 } + 1)) } } .toSet() } fun Set.combinationsWithRepetitionsNumber(combinationSize: Int): Long = when { combinationSize < 0 -> throw Error("combinationSize cannot be smaller then 0. It is equal to $combinationSize") combinationSize == 0 -> 1 else -> (size + combinationSize - 1).factorial() / (combinationSize.factorial() * (size - 1).factorial()) } ================================================ FILE: src/main/java/com/marcinmoskala/math/FactorialFun.kt ================================================ @file:JvmName("DiscreteMath") @file:JvmMultifileClass package com.marcinmoskala.math fun Int.factorial(): Long = (1..this).product() ================================================ FILE: src/main/java/com/marcinmoskala/math/IterableMultiplication.kt ================================================ @file:JvmName("DiscreteMath") @file:JvmMultifileClass package com.marcinmoskala.math operator fun List.times(l: List): List> = flatMap { e1 -> l.map { e2 -> e1 to e2 } } @JvmName("listOfPairTimes") operator fun List>.times(l: List): List> = flatMap { (e1, e2) -> l.map { e3 -> Triple(e1, e2, e3) } } ================================================ FILE: src/main/java/com/marcinmoskala/math/NumSplitFunc.kt ================================================ @file:JvmName("DiscreteMath") @file:JvmMultifileClass package com.marcinmoskala.math // Number of splits of n identical elements to k groups fun Int.splitsNumber(groupsNum: Int): Int = when { groupsNum < 0 -> throw Error("groupsNum cannot be smaller then 0. It is now equal to $groupsNum") groupsNum == 0 -> if (this == 0) 1 else 0 groupsNum == 1 || groupsNum == this -> 1 groupsNum > this -> 0 else -> (1..groupsNum).sumBy { i -> (this - groupsNum).splitsNumber(i) } } ================================================ FILE: src/main/java/com/marcinmoskala/math/NumbersDivisible.kt ================================================ @file:JvmName("DiscreteMath") @file:JvmMultifileClass package com.marcinmoskala.math fun IntRange.divisiveBy(vararg numbers: Int) = filter { n -> numbers.any { n % it == 0 } } fun IntRange.countDivisiveBy(vararg numbers: Int) = count { n -> numbers.any { n % it == 0 } } fun IntRange.nonDivisiveBy(vararg numbers: Int) = filter { n -> numbers.all { n % it != 0 } } fun IntRange.countNonDivisiveBy(vararg numbers: Int) = count { n -> numbers.all { n % it != 0 } } ================================================ FILE: src/main/java/com/marcinmoskala/math/PermutationsExt.kt ================================================ @file:JvmName("DiscreteMath") @file:JvmMultifileClass package com.marcinmoskala.math /** * Permutations are all different ways to arrange elements from some collection (https://en.wikipedia.org/wiki/Permutation). * For sets it's number is n!, for lists it is n! / (n1! * n2! * ...) where n1, n2... are numbers elements that are the same. */ /* This function returns number of all permutations of elements from set. It is equal to n! where n is size of set. */ fun Set.permutationsNumber(): Long = size.factorial() /* This function returns number of all permutations of elements from list. It is equal to n! / (n1! * n2! * ...) where n1, n2... are numbers elements that are the same. */ fun List.permutationsNumber(): Long = if (size < 1) 1L else size.factorial() / groupBy { it }.map { it.value.size.factorial() }.product() /* This function returns all permutations of elements from set. These are different ways to arrange elements from this list. */ fun Set.permutations(): Set> = toList().permutations() /* This function returns all permutations of elements from list. These are different ways to arrange elements from this list. */ fun List.permutations(): Set> = when { isEmpty() -> setOf() size == 1 -> setOf(listOf(get(0))) else -> { val element = get(0) drop(1).permutations() .flatMap { sublist -> (0..sublist.size).map { i -> sublist.plusAt(i, element) } } .toSet() } } internal fun List.plusAt(index: Int, element: T): List = when { index !in 0..size -> throw Error("Cannot put at index $index because size is $size") index == 0 -> listOf(element) + this index == size -> this + element else -> dropLast(size - index) + element + drop(index) } ================================================ FILE: src/main/java/com/marcinmoskala/math/Power.kt ================================================ @file:JvmName("DiscreteMath") @file:JvmMultifileClass package com.marcinmoskala.math import java.math.BigDecimal import java.math.BigInteger infix fun Number.pow(power: Number): Double = Math.pow(this.toDouble(), power.toDouble()) infix fun Int.pow(power: Int): Int = Math.pow(this.toDouble(), power.toDouble()).toInt() ================================================ FILE: src/main/java/com/marcinmoskala/math/PowersetExt.kt ================================================ @file:JvmName("DiscreteMath") @file:JvmMultifileClass package com.marcinmoskala.math fun Collection.powerset(): Set> = powerset(this, setOf(setOf())) private tailrec fun powerset(left: Collection, acc: Set>): Set> = when { left.isEmpty() -> acc else ->powerset(left.drop(1), acc + acc.map { it + left.first() }) } val Collection.powersetSize: Int get() = 2.pow(size) ================================================ FILE: src/main/java/com/marcinmoskala/math/ProductExt.kt ================================================ @file:JvmName("DiscreteMath") @file:JvmMultifileClass package com.marcinmoskala.math fun Iterable.product(): Long = fold(1L) { a, n -> a * n } @JvmName("productLong") fun Collection.product(): Long = fold(1L) { a, n -> a * n } ================================================ FILE: src/main/java/com/marcinmoskala/math/SetSplitFunc.kt ================================================ @file:JvmName("DiscreteMath") @file:JvmMultifileClass package com.marcinmoskala.math // Stirling function - number of splits of n different elements to k groups fun Set.splitsNumber(groupsNum: Int): Int = when { groupsNum < 0 -> throw Error("groupsNum cannot be smaller then 0. It is equal to $groupsNum") groupsNum == 0 -> if (isEmpty()) 1 else 0 groupsNum == 1 || groupsNum == size -> 1 groupsNum > size -> 0 else -> (1..(size - 1)).toSet().splitsNumber(groupsNum - 1) + groupsNum * (1..(size - 1)).toSet().splitsNumber(groupsNum) } // Takes set of elements and returns set of splits and each of them is set of sets fun Set.splits(groupsNum: Int): Set>> = when { groupsNum < 0 -> throw Error("groupsNum cannot be smaller then 0. It is equal to $groupsNum") groupsNum == 0 -> if (isEmpty()) setOf(emptySet()) else emptySet() groupsNum == 1 -> setOf(setOf(this)) groupsNum == size -> setOf(this.map { setOf(it) }.toSet()) groupsNum > size -> emptySet() else -> setOf>>() .plus(splitsWhereFirstIsAlone(groupsNum)) .plus(splitsForFirstIsInAllGroups(groupsNum)) } private fun Set.splitsWhereFirstIsAlone(groupsNum: Int): List>> = this .minusElement(first()) .splits(groupsNum - 1) .map { it.plusElement(setOf(first())) } private fun Set.splitsForFirstIsInAllGroups(groupsNum: Int): List>> = this .minusElement(first()) .splits(groupsNum) .flatMap { split -> split.map { group -> split.minusElement(group).plusElement(group + first()) } } ================================================ FILE: src/main/java/com/marcinmoskala/math/SublistsBySplittersExt.kt ================================================ @file:JvmName("DiscreteMath") @file:JvmMultifileClass package com.marcinmoskala.math fun List.sublistsBySplitters(isSplitter: (T) -> Boolean): List> = when { isEmpty() -> listOf(listOf()) isSplitter(last()) -> sublistFromRest(isSplitter) .flatMap { listOf(it + last(), it) } else -> sublistFromRest(isSplitter) .map { it + last() } } private fun List.sublistFromRest(isSplitter: (T) -> Boolean) = dropLast(1).sublistsBySplitters(isSplitter) ================================================ FILE: src/test/java/com/marcinmoskala/math/tests/CartesianProductPropertyTest.kt ================================================ package com.marcinmoskala.math.tests import com.marcinmoskala.math.cartesianProduct import io.kotest.core.spec.style.StringSpec import io.kotest.property.Arb import io.kotest.property.arbitrary.int import io.kotest.property.arbitrary.list import io.kotest.property.forAll internal class CartesianProductPropertyTest : StringSpec({ val intListGen = Arb.list( Arb.int(0..100), 2..5 ) val listOfIntListsGen = Arb.list( intListGen, 2..5 ) "output product size is product of sizes of inputs" { forAll(listOfIntListsGen) { list -> val head = list[0] val tail = list.drop(1).toTypedArray() head.cartesianProduct(*tail).toList().size == list.map { it.size }.reduce(Int::times) } } "cartesian product with repeat of empty list is empty list" { forAll(Arb.int(2..10)) { repeat -> emptyList().cartesianProduct(repeat).toList().isEmpty() } } "cartesian product of empty list and non empty list is empty list" { forAll(intListGen) { list -> emptyList().cartesianProduct(list).toList().isEmpty() } } "cartesian product of non empty list and empty list is empty list" { forAll(intListGen) { list -> list.cartesianProduct(emptyList()).toList().isEmpty() } } "set of elements in product is the same as in input" { forAll(listOfIntListsGen) { list -> val head = list[0] val tail = list.drop(1).toTypedArray() head.cartesianProduct(*tail).toList().flatten().toSet() == list.flatten().toSet() } } }) ================================================ FILE: src/test/java/com/marcinmoskala/math/tests/CartesianProductTest.kt ================================================ package com.marcinmoskala.math.tests import com.marcinmoskala.math.cartesianProduct import io.kotest.property.Arb import io.kotest.property.arbitrary.int import io.kotest.property.arbitrary.next import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.assertEquals internal class CartesianProductTest { @Test fun `cartesian product with size more than MAX_INT throws`() { assertThrows(IllegalArgumentException::class.java) { listOf(1, 2, 3, 5, 6, 7, 8, 9, 0).cartesianProduct(10).toList() } } @Test fun `cartesian product with repeat less than 1 throws`() { val repeat = Arb.int(-100..0).next() assertThrows(IllegalArgumentException::class.java) { listOf(1, 2, 3).cartesianProduct(repeat) } } @Test fun `cartesian product with repeat = 1`() { val actual = listOf(1, 2, 3).cartesianProduct(1).toList() val expected = listOf( listOf(1), listOf(2), listOf(3) ) assertEquals(expected, actual) } @Test fun `cartesian product with repeat`() { val actual = listOf(1, 2, 3).cartesianProduct(2).toList() val expected = listOf( listOf(1, 1), listOf(1, 2), listOf(1, 3), listOf(2, 1), listOf(2, 2), listOf(2, 3), listOf(3, 1), listOf(3, 2), listOf(3, 3) ) assertEquals(expected, actual) } @Test fun `cartesian product of different sizes`() { val actual = listOf(1, 2, 3).cartesianProduct(listOf(8, 9)).toList() val expected = listOf( listOf(1, 8), listOf(1, 9), listOf(2, 8), listOf(2, 9), listOf(3, 8), listOf(3, 9) ) assertEquals(expected, actual) } @Test fun `cartesian product of same sizes`() { val actual = listOf(1, 2).cartesianProduct(listOf(8, 9)).toList() val expected = listOf( listOf(1, 8), listOf(1, 9), listOf(2, 8), listOf(2, 9) ) assertEquals(expected, actual) } @Test fun `cartesian product of 3 lists`() { val actual = listOf(1, 2).cartesianProduct( listOf(3, 4), listOf(5, 6) ).toList() val expected = listOf( listOf(1, 3, 5), listOf(1, 3, 6), listOf(1, 4, 5), listOf(1, 4, 6), listOf(2, 3, 5), listOf(2, 3, 6), listOf(2, 4, 5), listOf(2, 4, 6) ) assertEquals(expected, actual) } @Test fun `cartesian product of 3 lists with different size`() { val actual = listOf(0, 1, 2).cartesianProduct( listOf(3, 4), listOf(5, 6) ).toList() val expected = listOf( listOf(0, 3, 5), listOf(0, 3, 6), listOf(0, 4, 5), listOf(0, 4, 6), listOf(1, 3, 5), listOf(1, 3, 6), listOf(1, 4, 5), listOf(1, 4, 6), listOf(2, 3, 5), listOf(2, 3, 6), listOf(2, 4, 5), listOf(2, 4, 6) ) assertEquals(expected, actual) } @Test fun `cartesian product of 2 lists with different types`() { val expected = listOf( listOf("A", 1), listOf("A", 2), listOf("A", 3), listOf("B", 1), listOf("B", 2), listOf("B", 3) ) val actual = listOf("A", "B").cartesianProduct(listOf(1, 2, 3)).toList() assertEquals(expected, actual) } } ================================================ FILE: src/test/java/com/marcinmoskala/math/tests/CombinationTest.kt ================================================ package com.marcinmoskala.math.tests import com.marcinmoskala.math.combinations import com.marcinmoskala.math.combinationsNumber import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class CombinationTest { @Test fun `combinations function is throwing error when asked for subsets of size smaller then 0`() { val set = setOf(1, 2, 3, 4) for (subsetSize in -10..-1) { assertIsThrowingError { set.combinations(subsetSize) } } } @Test fun `combinationsNumber function is throwing error when asked for subsets of size smaller then 0`() { val set = setOf(1, 2, 3, 4) for (subsetSize in -10..-1) { assertIsThrowingError { set.combinationsNumber(subsetSize) } } } @Test fun `Test combinationsNumber for Sets with different sizes`() { val set = setOf(1, 2, 3, 4) val subsetSizeToCombinationNumber = mapOf( 0 to 1L, 1 to 4L, 2 to 6L, 3 to 4L, 4 to 1L, 5 to 1L ) for ((subsetSize, expectedCombinationNumber) in subsetSizeToCombinationNumber) { assertEquals(expectedCombinationNumber, set.combinationsNumber(subsetSize)) } } @Test fun `Test combinations for Sets with different sizes`() { val set = setOf(1, 2, 3, 4) val sizeToCombinations = mapOf( 0 to setOf(setOf()), 1 to setOf(setOf(1), setOf(2), setOf(3), setOf(4)), 2 to setOf(setOf(1, 2), setOf(2, 3), setOf(3, 4), setOf(1, 3), setOf(2, 4), setOf(1, 4)), 3 to setOf(setOf(1, 2, 3), setOf(1, 2, 4), setOf(1, 3, 4), setOf(2, 3, 4)), 4 to setOf(setOf(1, 2, 3, 4)), 5 to setOf(setOf(1, 2, 3, 4)) ) for ((subsetSize, expectedCombinations) in sizeToCombinations) { assertEquals(expectedCombinations, set.combinations(subsetSize)) } } @Test fun `Test combinations size and combinationsNumber correctness`() { val set = (1..6).toSet() (1..7).forEach { i -> assertEquals(set.combinationsNumber(i), set.combinations(i).size.toLong()) } } } ================================================ FILE: src/test/java/com/marcinmoskala/math/tests/CombinationWithRepetitionTest.kt ================================================ package com.marcinmoskala.math.tests import com.marcinmoskala.math.combinationsWithRepetitions import com.marcinmoskala.math.combinationsWithRepetitionsNumber import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class CombinationWithRepetitionTest { @Test fun `combinationsWithRepetitions function is throwing error when asked for subsets of size smaller then 0`() { val set = setOf(1, 2, 3, 4) for (subsetSize in -10..-1) { assertIsThrowingError { set.combinationsWithRepetitions(subsetSize) } } } @Test fun `combinationsWithRepetitionsNumber function is throwing error when asked for subsets of size smaller then 0`() { val set = setOf(1, 2, 3, 4) for (subsetSize in -10..-1) { assertIsThrowingError { set.combinationsWithRepetitionsNumber(subsetSize) } } } @Test fun `Test combinationsWithRepetitionsNumber for Sets with different sizes`() { val set = setOf(1, 2, 3) val subsetSizeToCombinationNumber = mapOf( 0 to 1L, 1 to 3L, 2 to 6L, 3 to 10L, 4 to 15L, 5 to 21L ) for ((subsetSize, expectedCombinationNumber) in subsetSizeToCombinationNumber) { assertEquals(expectedCombinationNumber, set.combinationsWithRepetitionsNumber(subsetSize)) } } @Test fun `Simple combinationsWithRepetitions test`() { val set = setOf(1, 2, 3) val sizeToCombinations = mapOf>>( 0 to setOf(mapOf()), 1 to setOf(mapOf(1 to 1), mapOf(2 to 1), mapOf(3 to 1)), 2 to setOf(mapOf(1 to 1, 2 to 1), mapOf(2 to 1, 3 to 1), mapOf(1 to 1, 3 to 1), mapOf(1 to 2), mapOf(2 to 2), mapOf(3 to 2)) ) for ((subsetSize, expectedCombinations) in sizeToCombinations) { assertEquals(expectedCombinations, set.combinationsWithRepetitions(subsetSize)) } } } ================================================ FILE: src/test/java/com/marcinmoskala/math/tests/FactorialTest.kt ================================================ package com.marcinmoskala.math.tests import com.marcinmoskala.math.factorial import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class FactorialTest { @Test fun `Test factorial results`() { val numberWithFactorial = mapOf( 0 to 1L, 1 to 1L, 2 to 2L, 3 to 6L, 4 to 24L, 10 to 3628800L, 15 to 1307674368000L, 20 to 2432902008176640000L ) for ((i, factorialResult) in numberWithFactorial) { assertEquals(factorialResult, i.factorial()) } } } ================================================ FILE: src/test/java/com/marcinmoskala/math/tests/IterableMultipliationTest.kt ================================================ package com.marcinmoskala.math.tests import com.marcinmoskala.math.times import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class IterableMultipliationTest { @Test fun `When one list empty then multiplication is also returning empty`() { assertEquals(listOf(), listOf() * listOf()) assertEquals(listOf(), listOf(1) * listOf()) assertEquals(listOf(), listOf() * listOf(1)) assertEquals(listOf(), listOf(1, 2) * listOf()) } @Test fun `When size of one list is 1 then multiplication of it with other list returns list with size of second with element of it paired with element from other list`() { assertEquals(listOf("A" to 1, "A" to 2), listOf("A") * listOf(1, 2)) assertEquals(listOf("A" to 1, "A" to 2, "A" to 3), listOf("A") * listOf(1, 2, 3)) assertEquals(listOf("A" to 1, "A" to 2, "A" to 2), listOf("A") * listOf(1, 2, 2)) } @Test fun `Simple list multiplication returns each combination of pairs from lists`() { assertEquals(listOf("A" to 1, "A" to 2, "B" to 1, "B" to 2), listOf("A", "B") * listOf(1, 2)) } @Test fun `Multiplication of tree lists is returning triple with each combination of each lists`() { assertEquals(listOf( Triple("A", 1, 'a'), Triple("A", 1, 'b'), Triple("A", 2, 'a'), Triple("A", 2, 'b'), Triple("B", 1, 'a'), Triple("B", 1, 'b'), Triple("B", 2, 'a'), Triple("B", 2, 'b') ), listOf("A", "B") * listOf(1, 2) * listOf('a', 'b')) } @Test fun `Size of result of list multipication is equeal to multiplication of list sizes`() { val list1 = (1..5).toList() val list2 = (1..10).toList() val list3 = (1..25).toList() assertEquals(list1.size * list2.size, (list1 * list2).size) assertEquals(list1.size * list3.size, (list1 * list3).size) assertEquals(list2.size * list3.size, (list2 * list3).size) assertEquals(list1.size * list1.size, (list1 * list1).size) assertEquals(list2.size * list2.size, (list2 * list2).size) assertEquals(list3.size * list3.size, (list3 * list3).size) assertEquals(list1.size * list2.size * list3.size, (list1 * list2 * list3).size) assertEquals(list1.size * list1.size * list1.size, (list1 * list1 * list1).size) assertEquals(list2.size * list2.size * list2.size, (list2 * list2 * list2).size) assertEquals(list3.size * list3.size * list3.size, (list3 * list3 * list3).size) } } ================================================ FILE: src/test/java/com/marcinmoskala/math/tests/JavaTest.java ================================================ package com.marcinmoskala.math.tests; import com.marcinmoskala.math.DiscreteMath; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class JavaTest { private static Set smallSet = new HashSet<>(); private static List smallList = new ArrayList<>(); @BeforeAll static public void setUp() { smallSet.add(0); smallSet.add(1); smallSet.add(2); smallList.add(0); smallList.add(1); smallList.add(1); } @Test public void permutationsTest() { Assertions.assertEquals(6, DiscreteMath.permutationsNumber(smallSet)); Assertions.assertEquals(3, DiscreteMath.permutationsNumber(smallList)); } @Test public void combinationsTest() { Assertions.assertEquals(3, DiscreteMath.combinationsNumber(smallSet, 2)); Assertions.assertEquals(6, DiscreteMath.combinationsWithRepetitionsNumber(smallSet, 2)); } @Test public void powersetTest() { Assertions.assertEquals(8, DiscreteMath.getPowersetSize(smallSet)); } @Test public void productTest() { Assertions.assertEquals(0, DiscreteMath.product(smallList)); } @Test public void factorialTest() { Assertions.assertEquals(3628800L, DiscreteMath.factorial(10)); } @Test public void splitsOfSetTest() { Assertions.assertEquals(3, DiscreteMath.splitsNumber(smallSet, 2)); } @Test public void splitsOfNumberTest() { Assertions.assertEquals(3, DiscreteMath.splitsNumber(7, 4)); } @Test public void iterableMultiplicationTest() { Assertions.assertEquals(smallList.size() * smallList.size(), DiscreteMath.times(smallList, smallList).size()); } } ================================================ FILE: src/test/java/com/marcinmoskala/math/tests/NumberSplitTest.kt ================================================ package com.marcinmoskala.math.tests import com.marcinmoskala.math.splitsNumber import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class NumberSplitTest { @Test fun `splitsNumber function for number is throwing error when asked for groupsNum of size smaller then 0`() { for (groupsNum in -10..-1) { for (num in 0..10) { assertIsThrowingError { num.splitsNumber(groupsNum) } } } } @Test fun `n number can be only one way splitted to one or n components`() { for (n in 1..100) { assertEquals(1, n.splitsNumber(1)) assertEquals(1, n.splitsNumber(n)) } } @Test fun `For 0 splits, number splits function is returning 1 for 0 and 0 otherwise`() { assertEquals(1, 0.splitsNumber(0)) for (n in 1..100) { assertEquals(0, n.splitsNumber(0)) } } @Test fun `Number splits function is correct according to recurrence definition`() { for (n in 1..10) { for (k in 1..(n - 1)) { assertEquals(n.splitsNumber(k), (1..k).sumBy { i -> (n - k).splitsNumber(i) }) } } } @Test fun `Simple number splits examples are calculated correctly`() { assertEquals(3, 7.splitsNumber(4)) assertEquals(11, 11.splitsNumber(4)) assertEquals(5, 9.splitsNumber(5)) assertEquals(7, 13.splitsNumber(8)) } } ================================================ FILE: src/test/java/com/marcinmoskala/math/tests/NumbersDivisibleTest.kt ================================================ package com.marcinmoskala.math.tests import com.marcinmoskala.math.countDivisiveBy import com.marcinmoskala.math.countNonDivisiveBy import com.marcinmoskala.math.divisiveBy import com.marcinmoskala.math.nonDivisiveBy import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class NumbersDivisibleTest { @Test fun `Simple count divisible test`() { assertEquals(462, (1..1000).countNonDivisiveBy(2, 6, 13)) assertEquals(520, (1..1000).countNonDivisiveBy(3, 7, 11)) assertEquals(768, (1..1000).countNonDivisiveBy(6, 9, 33)) } @Test fun `Simple count nondivisible test`() { assertEquals(1000 - 462, (1..1000).countDivisiveBy(2, 6, 13)) assertEquals(1000 - 520, (1..1000).countDivisiveBy(3, 7, 11)) assertEquals(1000 - 768, (1..1000).countDivisiveBy(6, 9, 33)) } @Test fun `Simple divisible test`() { assertEquals(listOf(1, 5, 7), (1..10).nonDivisiveBy(2, 3)) } @Test fun `Simple nondivisible test`() { assertEquals(listOf(2, 3, 4, 6, 8, 9, 10), (1..10).divisiveBy(2, 3)) } @Test fun `Divisible (and non divisible) size and count matches`() { val r = (1..100) for(i in 1..10) { for(j in 1..10) { assertEquals(r.countDivisiveBy(i, j), r.divisiveBy(i, j).size) assertEquals(r.countNonDivisiveBy(i, j), r.nonDivisiveBy(i, j).size) } } } } ================================================ FILE: src/test/java/com/marcinmoskala/math/tests/PermutationTest.kt ================================================ package com.marcinmoskala.math.tests import com.marcinmoskala.math.permutations import com.marcinmoskala.math.permutationsNumber import com.marcinmoskala.math.plusAt import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class PermutationTest { @Test fun `Test permutation numbers for Sets with different sizes`() { val setSizeToPermutations = mapOf( 0 to 1L, 1 to 1L, 2 to 2L, 3 to 6L, 4 to 24L ) for ((setSize, expectedNumber) in setSizeToPermutations) { val set = (1..setSize).toSet() assertEquals(expectedNumber, set.permutationsNumber()) } } @Test fun `Test permutation numbers for Lists with different sizes and different elements`() { val listSizeToPermutations = mapOf( 0 to 1L, 1 to 1L, 2 to 2L, 3 to 6L, 4 to 24L ) for ((listSize, expectedNumber) in listSizeToPermutations) { val set = (1..listSize).toList() assertEquals(expectedNumber, set.permutationsNumber()) } } @Test fun `Test permutation numbers for Lists with different sizes and same elements`() { val listToPermutations = mapOf( listOf(1, 1, 1, 1) to 1L, listOf(1, 1, 2, 2) to 6L, listOf(1, 1, 1, 2) to 4L ) for ((list, expectedNumber) in listToPermutations) { assertEquals(expectedNumber, list.permutationsNumber()) } } @Test fun `Get all permutations for different elements`() { val setToPermutations = mapOf( setOf() to setOf>(), setOf(1, 2) to setOf(listOf(1, 2), listOf(2, 1)), setOf(1, 2, 3) to setOf(listOf(1, 2, 3), listOf(2, 1, 3), listOf(1, 3, 2), listOf(2, 3, 1), listOf(3, 1, 2), listOf(3, 2, 1)) ) for ((set, allExpectedPermutations) in setToPermutations) { assertEquals(allExpectedPermutations, set.permutations()) } } @Test fun `Check permutations number in allPermutations for bigger numbers`() { val set = (1..5).toSet() assertEquals(set.permutationsNumber(), set.permutations().size.toLong()) } @Test fun `Simple plusAt tests`() { val list = listOf(1,2,3) assertIsThrowingError { list.plusAt(-1, 100) } assertIsThrowingError { list.plusAt(-100, 100) } assertIsThrowingError { list.plusAt(1000, 100) } assertEquals(listOf(100, 1, 2, 3), list.plusAt(0, 100)) assertEquals(listOf(1, 100, 2, 3), list.plusAt(1, 100)) assertEquals(listOf(1, 2, 3, 100), list.plusAt(3, 100)) } } ================================================ FILE: src/test/java/com/marcinmoskala/math/tests/PowerTest.kt ================================================ package com.marcinmoskala.math.tests import com.marcinmoskala.math.pow import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test @Suppress("USELESS_IS_CHECK") internal class PowerTest { @Test fun `Power for Number tests`() { assertEquals(4.0, (2 as Number).pow(2)) assertEquals(81.0, (3 as Number).pow(4)) assertEquals(100000.0, (10 as Number).pow(5)) assertTrue((10 as Number).pow(5) is Double) } @Test fun `Power for Int tests`() { assertEquals(4, 2.pow(2)) assertEquals(81, 3.pow(4)) assertEquals(100000, 10.pow(5)) assertTrue(10.pow(5) is Int) } @Test fun `Power for Double tests`() { assertEquals(4.0, 2.0.pow(2)) assertEquals(81.0, 3.0.pow(4)) assertEquals(100000.0, 10.0.pow(5)) assertTrue(2.0.pow(5) is Double) } } ================================================ FILE: src/test/java/com/marcinmoskala/math/tests/PowersetTest.kt ================================================ package com.marcinmoskala.math.tests import com.marcinmoskala.math.pow import com.marcinmoskala.math.powerset import com.marcinmoskala.math.powersetSize import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class PowersetTest { @Test fun `Sublists from empty list is only empty list`() { val emptyList = setOf() assertEquals(setOf(emptyList), emptyList.powerset()) } @Test fun `Powerset simple example test`() { val set = setOf( setOf(1, 2, 3), setOf(1, 2), setOf(1, 3), setOf(2, 3), setOf(1), setOf(2), setOf(3), setOf()) assertEquals(set, setOf(1, 2, 3).powerset()) } @Test fun `Size of n element set powerset is 2^n`() { for(n in 1..6) { val set = (1..n).toSet() val size = 2.pow(n) assertEquals(size, set.powerset().size) assertEquals(size, set.powersetSize) } } } ================================================ FILE: src/test/java/com/marcinmoskala/math/tests/ProductTest.kt ================================================ package com.marcinmoskala.math.tests import com.marcinmoskala.math.product import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class ProductTest { @Test fun `Product of empty IntRange is 1`() { assertEquals(1, (0..-1).product()) } @Test fun `Test products of different IntRanges`() { val rangeToProduct = mapOf( 2..4 to 24L, 1..4 to 24L, 3..4 to 12L, 100..100 to 100L ) for ((range, product) in rangeToProduct) assertEquals(product, range.product()) } @Test fun `Test products of different Int Collections`() { val collectionToProduct = mapOf( listOf(1,2,3) to 6L, listOf(2,3) to 6L, listOf(3) to 3L, listOf(10, 10, 10) to 1000L ) for ((collection, product) in collectionToProduct) assertEquals(product, collection.product()) } @Test fun `Test products of different Long Collections`() { val collectionToProduct = mapOf( listOf(1L,2L,3L) to 6L, listOf(2L,3L) to 6L, listOf(3L) to 3L, listOf(10L, 10L, 10L) to 1000L ) for ((collection, product) in collectionToProduct) assertEquals(product, collection.product()) } } ================================================ FILE: src/test/java/com/marcinmoskala/math/tests/SetSplitTest.kt ================================================ package com.marcinmoskala.math.tests import com.marcinmoskala.math.splits import com.marcinmoskala.math.splitsNumber import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class SetSplitTest { fun set(size: Int) = (1..size).toSet() @Test fun `splitsNumber function for set is throwing error when asked for groupsNum of size smaller then 0`() { for (groupsNum in -10..-1) { for (num in 0..10) { assertIsThrowingError { set(num).splitsNumber(groupsNum) } } } } @Test fun `splits function for set is throwing error when asked for groupsNum of size smaller then 0`() { for (groupsNum in -10..-1) { for (num in 0..10) { assertIsThrowingError { set(num).splits(groupsNum) } } } } @Test fun `n elements can be only one way splitted to one or n groups`() { for (n in 1..100) { assertEquals(1, set(n).splitsNumber(1)) assertEquals(1, set(n).splitsNumber(n)) } } @Test fun `For 0 splits, Stirling function is returning 1 for 0 and 0 otherwise`() { assertEquals(1, set(0).splitsNumber(0)) for (n in 1..100) { assertEquals(0, set(n).splitsNumber(0)) } } @Test fun `Stirling function is correct according to recurrence definition`() { for (n in 1..10) { for (k in 1..(n - 1)) { assertEquals( set(n).splitsNumber(k), set(n - 1).splitsNumber(k - 1) + k * set(n - 1).splitsNumber(k) ) } } } @Test fun `Simple set splits number for examples are calculated correctly`() { assertEquals(1, set(3).splitsNumber(1)) assertEquals(3, set(3).splitsNumber(2)) assertEquals(7, set(4).splitsNumber(2)) assertEquals(25, set(5).splitsNumber(3)) assertEquals(140, set(7).splitsNumber(5)) assertEquals(350, set(7).splitsNumber(4)) } @Test fun `There is no splits to 0, except empty set`() { assertEquals(setOf(emptySet()), set(0).splits(0)) for (n in 1..100) assertEquals(emptySet>(), set(n).splits(0)) } @Test fun `Split to 1 is returning only base set`() { (1..10).map { set(it) }.forEach { s -> assertEquals(setOf(setOf(s)), s.splits(1)) } } @Test fun `Split to set size is returning set with each element separated`() { (1..10).map { set(it) }.forEach { s -> assertEquals(setOf(s.map { setOf(it) }.toSet()), s.splits(s.size)) } } @Test fun `Simple set split is correct`() { assertEquals(setOf(setOf(setOf(1, 2), setOf(3)), setOf(setOf(1, 3), setOf(2)), setOf(setOf(3, 2), setOf(1))), setOf(1, 2, 3).splits(2)) } @Test fun `Splits size and splitsNumber matches`() { for (i in 1..5) for (j in 1..5) { val s = set(i) assertEquals(s.splitsNumber(j), s.splits(j).size) } } } ================================================ FILE: src/test/java/com/marcinmoskala/math/tests/SublistsBySplittersTest.kt ================================================ package com.marcinmoskala.math.tests import com.marcinmoskala.math.sublistsBySplitters import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class SublistsBySplittersTest { @Test fun `Sublists from empty list is only empty list`() { val emptyList = listOf() assertEquals(listOf(emptyList), emptyList.sublistsBySplitters { true }) assertEquals(listOf(emptyList), emptyList.sublistsBySplitters { false }) } @Test fun `Sublists order is from biggest list to empty with elements in natural order`() { assertEquals(listOf(listOf(1, 2), listOf(1), listOf(2), listOf()), listOf(1, 2).sublistsBySplitters { true }) assertEquals(listOf(listOf(1, 2), listOf(1)), listOf(1, 2).sublistsBySplitters { it % 2 == 0 }) } @Test fun `Sublist creation for mixed splitters and simple`() { assertEquals(setOf(listOf(1, 2, 3), listOf(1, 3)), listOf(1, 2, 3).sublistsBySplitters { it % 2 == 0 }.toSet()) assertEquals(setOf(listOf(1, 2, 3, 4), listOf(1, 2, 3), listOf(1, 3, 4), listOf(1, 3)), listOf(1, 2, 3, 4).sublistsBySplitters { it % 2 == 0 }.toSet()) } @Test fun `Big sublists results sizes are correct`() { // 10 splitters, so 2^10 = 1024 lists assert((1..20).toList().sublistsBySplitters { it % 2 == 0 }.size == 1024) assert((1..40).toList().sublistsBySplitters { it % 4 == 0 }.size == 1024) } } ================================================ FILE: src/test/java/com/marcinmoskala/math/tests/TestUtils.kt ================================================ package com.marcinmoskala.math.tests internal fun assertIsThrowingError(f: () -> T) { try { f() } catch (r: Error) { return } assert(false) }