Set of extensions for Kotlin that provides Discrete math functionalities

Overview

DiscreteMathToolkit

Set of extensions for Kotlin that provides Discrete Math functionalities as an Kotlin extension functions.

Maven Central Build Status codecov codebeat badge Analytics

To stay current with news about library Twitter URL

Permutations

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

Combinations

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 and here

Powerset

Powerset of any set S is the set of all subsets of S, including the empty set and S itself.

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.

(3..4).product() // 12
listOf(10, 10, 10).product() // 1000

More examples here.

Factorial

Factorian of n (n!) is a product of all positive integers less than or equal to n.

3.factorial() // 6L
10.factorial() // 3628800L
20.factorial() // 2432902008176640000L

More examples here.

Numbers divisible and non-divisible by

(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.

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

(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

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

Iterable multiplication

Multiplication of iterables returns iterable with pairs of each possible connections of elements from first and iterable:

listOf(1, 2) * listOf("A", "B") // returns List<Pair<Int, String>>
// [(1, "A"), (1, "B"), (2, "A"), (2, "B")] 
listOf('a', 'b') * listOf(1, 2) * listOf("A", "B") // returns List<Triple<Char, Int, String>>
// [
//    ('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.

Cartesian product of lists

Similar to iterable multiplication but produces sequence of lists:

listOf('A', 'B', 'C', D).cartesianProduct(listOf('x', 'y')) // returns List<List<Char>>
// [
//     ['A', 'x'],
//     ['A', 'y'],
//     ['B', 'x'],
//     ['B', 'y'],
//     ['C', 'x'],
//     ['C', 'y'],
//     ['D', 'x'],
//     ['D', 'y']
// ]
listOf(0, 1).cartesianProduct(repeat = 2) // returns List<List<Int>>
// [
//     [0, 0],
//     [0, 1],
//     [1, 0],
//     [1, 1]
// ]
listOf(1, 2).cartesianProduct(listOf("ABC")) // returns List<List<Any>>
// [
//     [1, "ABC"],
//     [2, "ABC"]
// ]

More examples here.

Java support

Library is fully supporting usage from Java. All functions can be used as static function of DiscreteMath. For example:

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.

Install

Gradle:

compile "com.marcinmoskala:DiscreteMathToolkit:1.0.3"

Maven:

<dependency>
  <groupId>com.marcinmoskala</groupId>
  <artifactId>DiscreteMathToolkit</artifactId>
  <version>1.0.3</version>
</dependency>

Jar to download together with sources and javadoc can be found on Maven Central.

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.
Comments
  • update Power part

    update Power part

    in this commits:

    • add pow function for all Number types returning their same number type
    • add Number.pow function that accepts all type of numbers and return Double
    • makes pow function infix so that functions can use 1 pow 2 or 3.pow(4)
    • pow now accepts all types of Numbers like 3.5 pow 2 or 3f pow 8 or 8.pow(6L)
    opened by HKhademian 5
  • Add cartesian product of lists to the library

    Add cartesian product of lists to the library

    While adding new functionality I upgraded following dependencies:

    • gradle to 5.5.1
    • kotlin to 1.3.72
    • JUnit to Jupiter 5.6.1 (got warnings 'Assert' is deprecated. Deprecated in Java)
    opened by kuschanton 0
  • Latest version is 1.0.5, but only 1.0.3 is deployed to Central

    Latest version is 1.0.5, but only 1.0.3 is deployed to Central

    trying to use the cartesianProduct and it appears like it was added after the latest release to Maven Central, which was years ago. Anyway a new version could be published?

    opened by snowe2010 0
  • Feature request: All necklaces of a set/list

    Feature request: All necklaces of a set/list

    I would love it if this contained an implementation of Sawada's algorithm to generate all unique necklaces of a set/list (all distinct cyclic arrangements of the elements).

    Description of necklaces with a link to Sawada's paper that explains his algorithm: https://byorgey.wordpress.com/2010/03/12/math-combinatorics-multiset-and-sawadas-algorithm/

    opened by nibarius 0
  • Multiple issues using combinations

    Multiple issues using combinations

    I ran into mutliple issues depending on the inputs because of number overflows and too deep recursion. I also got concerned about the memory usage.

    For my use case it is enough to stream through the combinations and process one after one (instead of creating all combinations at once and blow my computer).

    For this reason I implemented my own (not optimized) combination extensions:

    fun <T : Collection<U>, U> T.forEachCombination(combinationSize: Int, callback: (Set<U>) -> Unit) {
        when {
            combinationSize < 2 -> IllegalArgumentException("combinationSize must be at least 2, actual value: $combinationSize")
            this.size <= combinationSize -> callback(this.toSet())
        }
    
        doForEachCombination(this.toList(), combinationSize) { callback(it) }
    }
    
    fun <T : Collection<U>, U> T.combinations(combinationSize: Int): Set<Set<U>> {
        val result = mutableSetOf<Set<U>>()
        forEachCombination(combinationSize) { result.add(it) }
        return result.toSet()
    }
    
    private fun <U> doForEachCombination(source: List<U>, combinationSize: Int, depth: Int = 0, idx: Int = 0, tmp: MutableList<U> = source.subList(0, combinationSize).toMutableList(), callback: (Set<U>) -> Unit) {
        for (i in idx..source.size - (combinationSize - depth)) {
            tmp[depth] = source[i]
            when (depth) {
                combinationSize - 1 -> callback(tmp.toSet()) // found new combination
                else -> doForEachCombination(source, combinationSize, depth + 1, i + 1, tmp, callback)
            }
        }
    }
    

    It converts the input collection to a List and just iterates through all combinations: [1,2,3,4] combinations of 2 => [1,2], [1,3], [1,4], [2,3], [2,4], [3,4]

    It may not the fastest way, but because of the issues mentioned above it works good for me. The recursion depth equals the size of the combinations. Maybe this implementation is useful for anyone.

    opened by mk2301 1
Owner
Marcin Moskała
Teacher, speaker, consultant, founder of Kt. Academy, author of Android Development with Kotlin.
Marcin Moskała
A Kotlin library used to analyse discrete Markov chains, in order to generate plausible sequences

Markov Markov is a Kotlin library used to analyse discrete Markov chains, in order to generate plausible sequences. Using This project is still under

Xavier F. Gouchet 0 Nov 14, 2021
SeatBookView is an Android Studio Library that helps to make it easier to create Bus, Train, Cinema Theater Seat UI and all functionalities are given.

SeatBookView SeatBookView is an Android Studio Library that helps to make it easier to create Bus ?? , Train ?? , Cinema Theater Seat UI and all funct

Md. Zahidul Islam 3 Oct 15, 2022
FlowExt is a Kotlin Multiplatform library, that provides many operators and extensions to Kotlin Coroutines Flow

FlowExt | Kotlinx Coroutines Flow Extensions | Kotlinx Coroutines Flow Extensions. Extensions to the Kotlin Flow library | kotlin-flow-extensions | Coroutines Flow Extensions | Kotlin Flow extensions | kotlin flow extensions | Flow extensions

Petrus Nguyễn Thái Học 151 Jan 1, 2023
Flowbius provides interoperability extensions for using Kotlin Flows with Mobius

Flowbius Flowbius provides interoperability extensions for using Kotlin Flows with Mobius. They allow conversion from Flows to Mobius types and vice v

Atlassian Labs 54 Jul 19, 2022
🔥The Android Startup library provides a straightforward, performant way to initialize components at the application startup. Both library developers and app developers can use Android Startup to streamline startup sequences and explicitly set the order of initialization.

??The Android Startup library provides a straightforward, performant way to initialize components at the application startup. Both library developers and app developers can use Android Startup to streamline startup sequences and explicitly set the order of initialization.

Rouse 1.3k Dec 30, 2022
This prototype app provides a list of events to be held under an organization (school, college, club, etc.) and the users can manually set event reminders at their scheduled time so that they do not miss an event.

E-CELL NITS Sample App This prototype app provides a list of events to be held under E-Cell NIT Silchar (for example, Srijan 2.0) and the users can ma

Ritam Nath 1 Nov 7, 2021
Kotlin extensions, BindingAdapters, Composable functions for Android CameraX

Setup dependencies { implementation "com.github.skgmn:cameraxx:0.6.0" } Features CameraXX provides extensions methods for CameraX to use functions

null 12 Aug 9, 2022
Various Ktor extensions and plugins.

Ktor Plugins Collection of useful Ktor plugins. All plugins are hosted on Maven central and have same version that should be similar to the latest ver

Lukas Forst 25 Nov 24, 2022
Kotlin-phoenix - A set of tools aimed to bridge Phoenix with the Kotlin Multiplatform world

Kotlin Phoenix This project is aimed to allow developers to work with Phoenix Ch

Adrien Jacquier Bret 5 Sep 21, 2022
Service exposes sensitive administration APIs to initialize and set lower level of Slurpanize infrastructure

slurpanize-baker Project This project uses Quarkus, the Supersonic Subatomic Java Framework. If you want to learn more about Quarkus, please visit its

Slurpanize by Tetracube RED 0 Nov 25, 2021
A Gradle plugin providing various utility methods and common code required to set up multi-version Minecraft mods.

Essential Gradle Toolkit A Gradle plugin providing various utility methods and common code required to set up multi-version Minecraft mods via archite

Essential 29 Nov 1, 2022
An Android app that scans images or human faces in real time and detects whether the mask is worn or not, with the ability to set an audible alert

Swift Mask Real time face mask detection Brief overview Swift Mask scans images or human faces in real time and detects whether the mask is worn or no

Giorgio Cantoni 4 Sep 22, 2022
A library that extends the existing JDBC API so that data objects can be used as input (to set parameters) and output (from ResultSet's rows).

SqlObjectMapper This is a library that extends the existing JDBC API so that data objects can be used as input (to set parameters) and output (from Re

Qualified Cactus 2 Nov 7, 2022
Provides Ktor Server libs for building awesome Kotlin plugins which needs to provide builtin HTTP servers

Ktor Plugin Provides Ktor Server libs for building awesome Kotlin plugins which needs to provide builtin HTTP servers. Requires: https://github.com/Po

null 0 Nov 13, 2021
Kotlin extension function provides a facility to "add" methods to class without inheriting a class or using any type of design pattern

What is Kotlin Extension Function ? Kotlin extension function provides a facility to "add" methods to class without inheriting a class or using any ty

mohsen 21 Dec 3, 2022
Kotter - aims to be a relatively thin, declarative, Kotlin-idiomatic API that provides useful functionality for writing delightful console applications.

Kotter (a KOTlin TERminal library) aims to be a relatively thin, declarative, Kotlin-idiomatic API that provides useful functionality for writing delightful console applications.

Varabyte 348 Dec 21, 2022
Andorid app which provides a bunch of useful Linux commands.

Linux Command Library for Android The app currently has 3203 manual pages, 1351 one-line scripts and a bunch of general terminal tips. It works 100% o

Simon Schubert 271 Dec 31, 2022
This project provides declarative camunda delegates for Spring based application

camunda-delegator-lib Features Declarative style for delegate code Generated delegates documentation and templates for camunda modeler(this feature is

Tinkoff.ru 27 Aug 12, 2022
Cago provides you way to do complex calculations on your device.

Cago Do your calculations easier. Cago provides you way to do complex calculations on your device. You can build functions that fit your goals by your

null 0 Feb 13, 2022