https://kotlinlang.org logo
#announcements
Title
# announcements
l

LastExceed

10/13/2019, 7:39 AM
i have a function that takes 5 boolean parameters. i'd like to call it with all 10 possible value combinations where 3 of them are true and 2 are false. is there any fancy way to do this or do i just put 10 consecutive function calls ?
p

Paul Woitaschek

10/13/2019, 10:10 AM
Like for testing? You can use a parametrized test
a

Anil Gorthy

10/13/2019, 11:18 AM
I'd certainly recommend using Builder Pattern especially because you are passing
boolean
- builder pattern reduces the burden on the developer and prevents confusion when the order of the parameters is important
p

Paul Woitaschek

10/13/2019, 12:34 PM
This is kotlin, not java. I have never seen a builder being necessary in kotlin on any project
👆 1
a

Anil Gorthy

10/13/2019, 1:42 PM
That's true, thank you @Paul Woitaschek. In K we could just use named and default arguments instead of using a builder pattern
k

karelpeeters

10/13/2019, 4:51 PM
First thing that comes to mind:
Copy code
fun testFoo() {
    fun Int.has(index: Int) = ((this shr index) and 1) != 0

    for (i in 0 until (2 shl 4))
        if (Integer.bitCount(i) == 3)
            foo(i.has(0), i.has(1), i.has(2), i.has(3), i.has(4))
}

fun foo(a: Boolean, b: Boolean, c: Boolean, d: Boolean, e: Boolean) = println("$a, $b, $c, $d, $e")
I don't know if that's the cleanest way though 😕
l

LastExceed

10/13/2019, 4:54 PM
that would result in calling the function with EVERY possible value combination instead of just those where 3 are true and 2 are false
i tasked my roommate with this as practice since he's just getting started with programming, he came up with this:
Copy code
fun getCombinations(onesRequired: Int, digitsRequired: Int, currentSolution: String = "", solutions: MutableList<String> = mutableListOf()): MutableList<String> {
    if (digitsRequired < onesRequired) {
        return solutions //no solution possible from here
    }

    if(onesRequired == 0) {
        var y = currentSolution
        for(x in 1..digitsRequired) {
            y += "0" //append missing 0's
        }
        solutions.add(y)
        return solutions
    }
    bitarray(onesRequired - 1, digitsRequired - 1, currentSolution + "1", solutions)
    bitarray(onesRequired - 0, digitsRequired - 1, currentSolution + "0", solutions)
    return solutions
}

fun main() {
    val combinations = getCombinations(3,5)
    combinations.forEach {
        foo(it[0]=='1', it[1]=='1', it[2]=='1', it[3]=='1', it[4]=='1')
    }
}
not a perfect solution, but it does the job. also lets me use it more generalized for n out of m instead of being locked to 3 out of 5
k

karelpeeters

10/13/2019, 5:12 PM
That's not true, the if checks if there are indeed 3 bit sets.
l

LastExceed

10/13/2019, 5:12 PM
oh, i missed that. in that case your solution works too