I'm planning to use this function to combine hashC...
# announcements
d
I'm planning to use this function to combine hashCodes. Does it make sense?
Copy code
fun bitLength(n: Int) = floor(log2(n.toFloat())).toInt() + 1

fun combine(vararg numbers: Int): Int {
    var total = 0
    var prevBitLength = 0
    
    for (num in numbers) {
        total += num shl prevBitLength
        prevBitLength += bitLength(num)
    }
    
    return total
}
d
You might want to check out the source code for
java.util.Arrays.hashCode
d
I realized that two numbers could overlap, so I changed it to
Copy code
private fun bitCombine(vararg numbers: Int): Int {
        var total = 0
        var prevBitLength = 0

        for (num in numbers) {
            total += num shl prevBitLength
            prevBitLength += Int.SIZE_BITS
        }

        return total
    }
n
I think you're going to want to xor things rather than + them. also the for loop does an allocation. and the vararg.
d
Why xor?
n
I guess I don't understand how that method doesn't int overflow immediately, since the second element is shifting left by the number of bits int supports
d
Thank you!
n
xor because there aren't a lot of ways to combine ints of size 0-2^32 without overflowing, and if you're just going for unique, it's fine
I think IntelliJ does something like "thing1.hashcode + thing2.hashcode * 31 + thing3.hashcode * 31", where 31 is some prime
generated by IntelliJ
okay so that's not xor obviously, but I guess it works
d
That makes sense, I guess
n
xor is not good for combining hashes either
d
Why not?
n
because if the two hashes are equal you get zero
d
good point
n
so it has a huge blind spot
with stuff like hashes, you basically never want to improvise tbh
look up proper algorithms
here's an example I'm familiar with from my work (it's in C++ but trivial to adapt obviously)
n
I think if you multiplied by a prime first the xor might be okay. but yeah, it's one reason why I like data classes -- I don't have to think about it, and it doesn't get out of sync with new fields
n
yeah a dataclass is a pretty simple solution for this
d
Yeah, I just get a warning in the IDE that I shouldn't be allocating in onDraw when I use a dataclass