https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

alex cole

01/10/2021, 1:54 AM
What is the best way to check if any value in one array is greater that the value of another of equal size in each index?
v

Vampire

01/10/2021, 2:01 AM
Dunno whether the best, but at least concise:
Copy code
foo.zip(bar).all { (f, b) -> f > b }
👍🏻 2
a

alex cole

01/10/2021, 2:25 AM
Would there be another way.
Copy code
fun inBounds(shape: Array<Int>, indices: Array<Int>): Boolean {
    for (i in 0 until shape.size) {
        if (indices[i] > shape[i]) return false
    }
    return true
}
v

Vampire

01/10/2021, 2:27 AM
Was that a question?
Copy code
fun inBounds(shape: Array<Int>, indices: Array<Int>) =
    shape.zip(indices).all { (s, i) -> s >= i }
a

alex cole

01/10/2021, 2:40 AM
is there a way that could also make sure
shape.size == indices.size
other than:
Copy code
private fun inBounds(shape: Array<Int>, indices: Array<Int>): Boolean {
    if (shape.size != indices.size) return false
    return shape.zip(indices).all { (s, i) -> s >= i }
}
v

Vampire

01/10/2021, 2:45 AM
For example, yes. Or
Copy code
fun inBounds(shape: Array<Int>, indices: Array<Int>) =
    (shape.size == indices.size)
        && shape.zip(indices).all { (s, i) -> s >= i }
Or probably many other variants
a

alex cole

01/10/2021, 2:46 AM
What would be the performance impacts between the two?
v

Vampire

01/10/2021, 2:47 AM
Probably none you should care of. 80% of the runtime of a program is spent in 20% of the code and there is not much point in optimizing the other 80%. 1. Make your code work (optimally with tests, especially for the latter steps) 2. Make your code nice by refactoring 3. If you then have an actual measured performance or memory problem, optimize exactly there.
👌 1
a

alex cole

01/10/2021, 2:56 AM
I am aware of those. I was just curious since I could not tell from the byte code.
v

Vampire

01/10/2021, 2:57 AM
Well, I have no idea, but I wouldn't expect any measurable difference
e

ephemient

01/11/2021, 2:01 AM
if anything, it's alternatives to
zip
where I would expect differences. probably direct indexing is faster for arrays and iterators is faster for certain types of collections. but zip is almost certainly good enough.
don't blindly optimize without benchmark
a

alex cole

01/11/2021, 3:10 AM
It was more of a curiosity of what happens in the jvm for each case and if there was a simple difference beyond the 7 lines in the byte code. I am expecting this library that I am building to be quite slow at first.
5 Views