Skip to content

Commit

Permalink
Replace java.util.Random with kotlin Random object (#4364)
Browse files Browse the repository at this point in the history
This also improves randomness by avoiding to reinitialize the random
number generator repeatedly from a seed based on the current time.
Typically, if the number generator is reinitialized repeatedly at
non-random times (like multiple times in a row), then generated numbers
have a higher chance of repeating.

The Kotlin Random object is only initialized once, using the best seed
available for the current Android version.
  • Loading branch information
cbeyls authored Apr 10, 2024
1 parent 2a4d60b commit ec599c8
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import com.keylesspalace.tusky.util.getFormattedDescription
import com.keylesspalace.tusky.util.hide
import com.keylesspalace.tusky.util.show
import com.keylesspalace.tusky.viewdata.AttachmentViewData
import java.util.Random
import kotlin.random.Random

class AccountMediaGridAdapter(
private val useBlurhash: Boolean,
Expand Down Expand Up @@ -60,7 +60,6 @@ class AccountMediaGridAdapter(
)

private val itemBgBaseHSV = FloatArray(3)
private val random = Random()

override fun onCreateViewHolder(
parent: ViewGroup,
Expand All @@ -72,7 +71,7 @@ class AccountMediaGridAdapter(
false
)
Color.colorToHSV(baseItemBackgroundColor, itemBgBaseHSV)
itemBgBaseHSV[2] = itemBgBaseHSV[2] + random.nextFloat() / 3f - 1f / 6f
itemBgBaseHSV[2] = itemBgBaseHSV[2] + Random.nextFloat() / 3f - 1f / 6f
binding.root.setBackgroundColor(Color.HSVToColor(itemBgBaseHSV))
return BindingHolder(binding)
}
Expand Down
5 changes: 2 additions & 3 deletions app/src/main/java/com/keylesspalace/tusky/util/StringUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@
package com.keylesspalace.tusky.util

import android.text.Spanned
import java.util.Random
import kotlin.random.Random

private const val POSSIBLE_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

fun randomAlphanumericString(count: Int): String {
val chars = CharArray(count)
val random = Random()
for (i in 0 until count) {
chars[i] = POSSIBLE_CHARS[random.nextInt(POSSIBLE_CHARS.length)]
chars[i] = POSSIBLE_CHARS[Random.nextInt(POSSIBLE_CHARS.length)]
}
return String(chars)
}
Expand Down

0 comments on commit ec599c8

Please sign in to comment.