What is the best way to check if any value in one ...
# getting-started
a
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
Dunno whether the best, but at least concise:
Copy code
foo.zip(bar).all { (f, b) -> f > b }
👍🏻 2
a
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
Was that a question?
Copy code
fun inBounds(shape: Array<Int>, indices: Array<Int>) =
    shape.zip(indices).all { (s, i) -> s >= i }
a
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
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
What would be the performance impacts between the two?
v
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
I am aware of those. I was just curious since I could not tell from the byte code.
v
Well, I have no idea, but I wouldn't expect any measurable difference
e
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
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.