d

Daniel

10/19/2020, 6:20 PM
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)
}

}``````
d

diesieben07

10/19/2020, 6:23 PM
You might want to check out the source code for
``java.util.Arrays.hashCode``
d

Daniel

10/19/2020, 6:23 PM
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
}

}``````
n

nanodeath

10/19/2020, 6:50 PM
I think you're going to want to xor things rather than + them. also the for loop does an allocation. and the vararg.
d

Daniel

10/19/2020, 6:51 PM
Why xor?
n

nanodeath

10/19/2020, 6:53 PM
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

Daniel

10/19/2020, 6:53 PM
Thank you!
n

nanodeath

10/19/2020, 6:53 PM
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

Daniel

10/19/2020, 6:56 PM
That makes sense, I guess
n

Nir

10/19/2020, 7:04 PM
xor is not good for combining hashes either
d

Daniel

10/19/2020, 7:04 PM
Why not?
n

Nir

10/19/2020, 7:04 PM
because if the two hashes are equal you get zero
d

Daniel

10/19/2020, 7:04 PM
good point
n

Nir

10/19/2020, 7:04 PM
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

nanodeath

10/19/2020, 7:07 PM
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

Nir

10/19/2020, 7:08 PM
yeah a dataclass is a pretty simple solution for this
d

Daniel

10/19/2020, 7:22 PM
Yeah, I just get a warning in the IDE that I shouldn't be allocating in onDraw when I use a dataclass
3 Views