Last active
April 24, 2021 10:27
-
-
Save cho0o0/a8367f967048b81d9db62626a3568577 to your computer and use it in GitHub Desktop.
generateAlphanumericPassword (https://pl.kotl.in/DGX8N_Erw)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlin.random.Random.Default.nextInt | |
fun main() { | |
println(generatePassword(16)) | |
} | |
fun generatePassword(length: Int): String { | |
require(length > 8) { "password length must be longer than 8 characters." } | |
val lowerChars = ('a'..'z').toList() | |
val upperChars = ('A'..'Z').toList() | |
val numChars = ('0'..'9').toList() | |
val chars1 = generateRandomChars(2, lowerChars) | |
val chars2 = generateRandomChars(2, upperChars) | |
val chars3 = generateRandomChars(2, numChars) | |
val chars4 = generateRandomChars(length - 6, lowerChars + upperChars + numChars) | |
return (chars1 + chars2 + chars3 + chars4).shuffled().joinToString("") | |
} | |
private fun generateRandomChars(length: Int, candidates: List<Char>): List<Char> { | |
return (1..length).map { nextInt(0, candidates.size) } | |
.map(candidates::get) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment