Idiomatic way to generate a random alphanumeric string in Kotlin
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
I can generate a random sequence of numbers in a certain range like the following:
fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) + start
fun generateRandomNumberList(len: Int, low: Int = 0, high: Int = 255): List<Int> {
(0..len-1).map {
(low..high).random()
}.toList()
}
Then I'll have to extend List
with:
fun List<Char>.random() = this[Random().nextInt(this.size)]
Then I can do:
fun generateRandomString(len: Int = 15): String{
val alphanumerics = CharArray(26) { it -> (it + 97).toChar() }.toSet()
.union(CharArray(9) { it -> (it + 48).toChar() }.toSet())
return (0..len-1).map {
alphanumerics.toList().random()
}.joinToString("")
}
But maybe there's a better way?
kotlin
add a comment |
I can generate a random sequence of numbers in a certain range like the following:
fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) + start
fun generateRandomNumberList(len: Int, low: Int = 0, high: Int = 255): List<Int> {
(0..len-1).map {
(low..high).random()
}.toList()
}
Then I'll have to extend List
with:
fun List<Char>.random() = this[Random().nextInt(this.size)]
Then I can do:
fun generateRandomString(len: Int = 15): String{
val alphanumerics = CharArray(26) { it -> (it + 97).toChar() }.toSet()
.union(CharArray(9) { it -> (it + 48).toChar() }.toSet())
return (0..len-1).map {
alphanumerics.toList().random()
}.joinToString("")
}
But maybe there's a better way?
kotlin
add a comment |
I can generate a random sequence of numbers in a certain range like the following:
fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) + start
fun generateRandomNumberList(len: Int, low: Int = 0, high: Int = 255): List<Int> {
(0..len-1).map {
(low..high).random()
}.toList()
}
Then I'll have to extend List
with:
fun List<Char>.random() = this[Random().nextInt(this.size)]
Then I can do:
fun generateRandomString(len: Int = 15): String{
val alphanumerics = CharArray(26) { it -> (it + 97).toChar() }.toSet()
.union(CharArray(9) { it -> (it + 48).toChar() }.toSet())
return (0..len-1).map {
alphanumerics.toList().random()
}.joinToString("")
}
But maybe there's a better way?
kotlin
I can generate a random sequence of numbers in a certain range like the following:
fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) + start
fun generateRandomNumberList(len: Int, low: Int = 0, high: Int = 255): List<Int> {
(0..len-1).map {
(low..high).random()
}.toList()
}
Then I'll have to extend List
with:
fun List<Char>.random() = this[Random().nextInt(this.size)]
Then I can do:
fun generateRandomString(len: Int = 15): String{
val alphanumerics = CharArray(26) { it -> (it + 97).toChar() }.toSet()
.union(CharArray(9) { it -> (it + 48).toChar() }.toSet())
return (0..len-1).map {
alphanumerics.toList().random()
}.joinToString("")
}
But maybe there's a better way?
kotlin
kotlin
edited Oct 26 '17 at 1:53
breezymri
asked Oct 26 '17 at 0:07
breezymribreezymri
86721633
86721633
add a comment |
add a comment |
10 Answers
10
active
oldest
votes
Assuming you have a specific set of source characters (source
in this snippet), you could do this:
val source = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
java.util.Random().ints(outputStrLength, 0, source.length)
.asSequence()
.map(source::get)
.joinToString("")
Which gives strings like "LYANFGNPNI" for outputStrLength = 10.
The two important bits are
Random().ints(length, minValue, maxValue)
which produces a stream of length random numbers each from minValue to maxValue-1, and
asSequence()
which converts the not-massively-usefulIntStream
into a much-more-usefulSequence<Int>
.
2
As a Kotlin newby I was look for this solution - very cool! However I would usesource.length
instead ofsource.length - 1
, otherwise one wont ever see a Z. The ints range parameter marks an exclusive upper bound.
– ToBe
Nov 16 '17 at 10:10
2
Well spotted. Very interesting idea of the Java8 API designers to make this (almost) the only exclusive bound-describing parameter in Java...
– Paul Hicks
Nov 16 '17 at 20:47
Fixed now, in example and description.
– Paul Hicks
Nov 16 '17 at 20:49
1
I get an unresolved reference on the.asSequence()
asIntStream
doesn't have that method
– z3ntu
Mar 7 '18 at 13:59
1
@PaulHicks you can use.toArray()
instead of.asSequence()
without the need to import additional methods.
– denys
Jan 9 at 12:44
|
show 6 more comments
Lazy folks would just do
java.util.UUID.randomUUID().toString()
You can not restrict the character range here, but I guess it's fine in many situations anyway.
add a comment |
Without JDK8:
fun ClosedRange<Char>.randomString(lenght: Int) =
(1..lenght)
.map { (Random().nextInt(endInclusive.toInt() - start.toInt()) + start.toInt()).toChar() }
.joinToString("")
usage:
('a'..'z').randomString(6)
add a comment |
Since Kotlin 1.3 you can do this:
fun getRandomString(length: Int) : String {
val allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
return (1..length)
.map { allowedChars.random() }
.joinToString("")
}
add a comment |
Or use coroutine API for the true Kotlin spirit:
buildSequence { val r = Random(); while(true) yield(r.nextInt(24)) }
.take(10)
.map{(it+ 65).toChar()}
.joinToString("")
1
The advantage of coroutines is avoiding all these higher-order functions and writing a simple loop that does the equivalent of all of them.(1..10).forEach { yield(r.nextInt(24) + 65).toChar() }
– Marko Topolnik
May 29 '18 at 10:29
add a comment |
('A'..'z').map { it }.shuffled().subList(0, 4).joinToString("")
1
While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review
– Nick
Nov 24 '18 at 6:50
add a comment |
Building off the answer from Paul Hicks, I wanted a custom string as input. In my case, upper and lower-case alphanumeric characters. Random().ints(...)
also wasn't working for me, as it required an API level of 24 on Android to use it.
This is how I'm doing it with Kotlin's Random
abstract class:
import kotlin.random.Random
object IdHelper {
private val ALPHA_NUMERIC = ('0'..'9') + ('A'..'Z') + ('a'..'z')
private const val LENGTH = 20
fun generateId(): String {
return List(LENGTH) { Random.nextInt(0, ALPHA_NUMERIC.size) }
.map { ALPHA_NUMERIC[it] }
.joinToString(separator = "")
}
}
The process and how this works is similar to a lot of the other answers already posted here:
- Generate a list of numbers of length
LENGTH
that correspond to the index values of the source string, which in this case isALPHA_NUMERIC
- Map those numbers to the source string, converting each numeric index to the character value
- Convert the resulting list of characters to a string, joining them with the empty string as the separator character.
- Return the resulting string.
Usage is easy, just call it like a static function: IdHelper.generateId()
add a comment |
Using Kotlin 1.3:
This method uses an input of your desired string length desiredStrLength
as an Integer and returns a random alphanumeric String of your desired string length.
fun randomAlphaNumericString(desiredStrLength: Int): String {
val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
return (1..desiredStrLength)
.map{ kotlin.random.Random.nextInt(0, charPool.size) }
.map(charPool::get)
.joinToString("")
}
If you prefer unknown length of alphanumeric (or at least a decently long string length like 36
in my example below), this method can be used:
fun randomAlphanumericString(): String {
val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
val outputStrLength = (1..36).shuffled().first()
return (1..outputStrLength)
.map{ kotlin.random.Random.nextInt(0, charPool.size) }
.map(charPool::get)
.joinToString("")
}
add a comment |
fun randomAlphaNumericString(@IntRange(from = 1, to = 62) lenght: Int): String {
val alphaNumeric = ('a'..'z') + ('A'..'Z') + ('0'..'9')
return alphaNumeric.shuffled().take(lenght).joinToString("")
}
While this may solve OP's problem (I have not tested), code only answers are generally discouraged on SO. It would be better if you could include a description as to why this is an answer to the question. Thanks!
– d_kennetz
Feb 19 at 18:00
add a comment |
The best way I think:
fun generateID(size: Int): String {
val source = "A1BCDEF4G0H8IJKLM7NOPQ3RST9UVWX52YZab1cd60ef2ghij3klmn49opq5rst6uvw7xyz8"
return (source).map { it }.shuffled().subList(0, size).joinToString("")
}
But isn't it, that this just mixes the characters (elements of the list) and thus every character would be chosen only once? Or am I missing something?
– Tobias Reich
Jan 3 at 9:10
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f46943860%2fidiomatic-way-to-generate-a-random-alphanumeric-string-in-kotlin%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
10 Answers
10
active
oldest
votes
10 Answers
10
active
oldest
votes
active
oldest
votes
active
oldest
votes
Assuming you have a specific set of source characters (source
in this snippet), you could do this:
val source = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
java.util.Random().ints(outputStrLength, 0, source.length)
.asSequence()
.map(source::get)
.joinToString("")
Which gives strings like "LYANFGNPNI" for outputStrLength = 10.
The two important bits are
Random().ints(length, minValue, maxValue)
which produces a stream of length random numbers each from minValue to maxValue-1, and
asSequence()
which converts the not-massively-usefulIntStream
into a much-more-usefulSequence<Int>
.
2
As a Kotlin newby I was look for this solution - very cool! However I would usesource.length
instead ofsource.length - 1
, otherwise one wont ever see a Z. The ints range parameter marks an exclusive upper bound.
– ToBe
Nov 16 '17 at 10:10
2
Well spotted. Very interesting idea of the Java8 API designers to make this (almost) the only exclusive bound-describing parameter in Java...
– Paul Hicks
Nov 16 '17 at 20:47
Fixed now, in example and description.
– Paul Hicks
Nov 16 '17 at 20:49
1
I get an unresolved reference on the.asSequence()
asIntStream
doesn't have that method
– z3ntu
Mar 7 '18 at 13:59
1
@PaulHicks you can use.toArray()
instead of.asSequence()
without the need to import additional methods.
– denys
Jan 9 at 12:44
|
show 6 more comments
Assuming you have a specific set of source characters (source
in this snippet), you could do this:
val source = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
java.util.Random().ints(outputStrLength, 0, source.length)
.asSequence()
.map(source::get)
.joinToString("")
Which gives strings like "LYANFGNPNI" for outputStrLength = 10.
The two important bits are
Random().ints(length, minValue, maxValue)
which produces a stream of length random numbers each from minValue to maxValue-1, and
asSequence()
which converts the not-massively-usefulIntStream
into a much-more-usefulSequence<Int>
.
2
As a Kotlin newby I was look for this solution - very cool! However I would usesource.length
instead ofsource.length - 1
, otherwise one wont ever see a Z. The ints range parameter marks an exclusive upper bound.
– ToBe
Nov 16 '17 at 10:10
2
Well spotted. Very interesting idea of the Java8 API designers to make this (almost) the only exclusive bound-describing parameter in Java...
– Paul Hicks
Nov 16 '17 at 20:47
Fixed now, in example and description.
– Paul Hicks
Nov 16 '17 at 20:49
1
I get an unresolved reference on the.asSequence()
asIntStream
doesn't have that method
– z3ntu
Mar 7 '18 at 13:59
1
@PaulHicks you can use.toArray()
instead of.asSequence()
without the need to import additional methods.
– denys
Jan 9 at 12:44
|
show 6 more comments
Assuming you have a specific set of source characters (source
in this snippet), you could do this:
val source = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
java.util.Random().ints(outputStrLength, 0, source.length)
.asSequence()
.map(source::get)
.joinToString("")
Which gives strings like "LYANFGNPNI" for outputStrLength = 10.
The two important bits are
Random().ints(length, minValue, maxValue)
which produces a stream of length random numbers each from minValue to maxValue-1, and
asSequence()
which converts the not-massively-usefulIntStream
into a much-more-usefulSequence<Int>
.
Assuming you have a specific set of source characters (source
in this snippet), you could do this:
val source = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
java.util.Random().ints(outputStrLength, 0, source.length)
.asSequence()
.map(source::get)
.joinToString("")
Which gives strings like "LYANFGNPNI" for outputStrLength = 10.
The two important bits are
Random().ints(length, minValue, maxValue)
which produces a stream of length random numbers each from minValue to maxValue-1, and
asSequence()
which converts the not-massively-usefulIntStream
into a much-more-usefulSequence<Int>
.
edited Jan 19 at 22:59
answered Oct 26 '17 at 1:07
Paul HicksPaul Hicks
9,65832856
9,65832856
2
As a Kotlin newby I was look for this solution - very cool! However I would usesource.length
instead ofsource.length - 1
, otherwise one wont ever see a Z. The ints range parameter marks an exclusive upper bound.
– ToBe
Nov 16 '17 at 10:10
2
Well spotted. Very interesting idea of the Java8 API designers to make this (almost) the only exclusive bound-describing parameter in Java...
– Paul Hicks
Nov 16 '17 at 20:47
Fixed now, in example and description.
– Paul Hicks
Nov 16 '17 at 20:49
1
I get an unresolved reference on the.asSequence()
asIntStream
doesn't have that method
– z3ntu
Mar 7 '18 at 13:59
1
@PaulHicks you can use.toArray()
instead of.asSequence()
without the need to import additional methods.
– denys
Jan 9 at 12:44
|
show 6 more comments
2
As a Kotlin newby I was look for this solution - very cool! However I would usesource.length
instead ofsource.length - 1
, otherwise one wont ever see a Z. The ints range parameter marks an exclusive upper bound.
– ToBe
Nov 16 '17 at 10:10
2
Well spotted. Very interesting idea of the Java8 API designers to make this (almost) the only exclusive bound-describing parameter in Java...
– Paul Hicks
Nov 16 '17 at 20:47
Fixed now, in example and description.
– Paul Hicks
Nov 16 '17 at 20:49
1
I get an unresolved reference on the.asSequence()
asIntStream
doesn't have that method
– z3ntu
Mar 7 '18 at 13:59
1
@PaulHicks you can use.toArray()
instead of.asSequence()
without the need to import additional methods.
– denys
Jan 9 at 12:44
2
2
As a Kotlin newby I was look for this solution - very cool! However I would use
source.length
instead of source.length - 1
, otherwise one wont ever see a Z. The ints range parameter marks an exclusive upper bound.– ToBe
Nov 16 '17 at 10:10
As a Kotlin newby I was look for this solution - very cool! However I would use
source.length
instead of source.length - 1
, otherwise one wont ever see a Z. The ints range parameter marks an exclusive upper bound.– ToBe
Nov 16 '17 at 10:10
2
2
Well spotted. Very interesting idea of the Java8 API designers to make this (almost) the only exclusive bound-describing parameter in Java...
– Paul Hicks
Nov 16 '17 at 20:47
Well spotted. Very interesting idea of the Java8 API designers to make this (almost) the only exclusive bound-describing parameter in Java...
– Paul Hicks
Nov 16 '17 at 20:47
Fixed now, in example and description.
– Paul Hicks
Nov 16 '17 at 20:49
Fixed now, in example and description.
– Paul Hicks
Nov 16 '17 at 20:49
1
1
I get an unresolved reference on the
.asSequence()
as IntStream
doesn't have that method– z3ntu
Mar 7 '18 at 13:59
I get an unresolved reference on the
.asSequence()
as IntStream
doesn't have that method– z3ntu
Mar 7 '18 at 13:59
1
1
@PaulHicks you can use
.toArray()
instead of .asSequence()
without the need to import additional methods.– denys
Jan 9 at 12:44
@PaulHicks you can use
.toArray()
instead of .asSequence()
without the need to import additional methods.– denys
Jan 9 at 12:44
|
show 6 more comments
Lazy folks would just do
java.util.UUID.randomUUID().toString()
You can not restrict the character range here, but I guess it's fine in many situations anyway.
add a comment |
Lazy folks would just do
java.util.UUID.randomUUID().toString()
You can not restrict the character range here, but I guess it's fine in many situations anyway.
add a comment |
Lazy folks would just do
java.util.UUID.randomUUID().toString()
You can not restrict the character range here, but I guess it's fine in many situations anyway.
Lazy folks would just do
java.util.UUID.randomUUID().toString()
You can not restrict the character range here, but I guess it's fine in many situations anyway.
edited Mar 16 '18 at 8:14
answered Mar 16 '18 at 7:53
Holger BrandlHolger Brandl
4,3373229
4,3373229
add a comment |
add a comment |
Without JDK8:
fun ClosedRange<Char>.randomString(lenght: Int) =
(1..lenght)
.map { (Random().nextInt(endInclusive.toInt() - start.toInt()) + start.toInt()).toChar() }
.joinToString("")
usage:
('a'..'z').randomString(6)
add a comment |
Without JDK8:
fun ClosedRange<Char>.randomString(lenght: Int) =
(1..lenght)
.map { (Random().nextInt(endInclusive.toInt() - start.toInt()) + start.toInt()).toChar() }
.joinToString("")
usage:
('a'..'z').randomString(6)
add a comment |
Without JDK8:
fun ClosedRange<Char>.randomString(lenght: Int) =
(1..lenght)
.map { (Random().nextInt(endInclusive.toInt() - start.toInt()) + start.toInt()).toChar() }
.joinToString("")
usage:
('a'..'z').randomString(6)
Without JDK8:
fun ClosedRange<Char>.randomString(lenght: Int) =
(1..lenght)
.map { (Random().nextInt(endInclusive.toInt() - start.toInt()) + start.toInt()).toChar() }
.joinToString("")
usage:
('a'..'z').randomString(6)
edited Mar 7 '18 at 21:58
answered Mar 7 '18 at 21:01
Andrzej SawoniewiczAndrzej Sawoniewicz
398613
398613
add a comment |
add a comment |
Since Kotlin 1.3 you can do this:
fun getRandomString(length: Int) : String {
val allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
return (1..length)
.map { allowedChars.random() }
.joinToString("")
}
add a comment |
Since Kotlin 1.3 you can do this:
fun getRandomString(length: Int) : String {
val allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
return (1..length)
.map { allowedChars.random() }
.joinToString("")
}
add a comment |
Since Kotlin 1.3 you can do this:
fun getRandomString(length: Int) : String {
val allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
return (1..length)
.map { allowedChars.random() }
.joinToString("")
}
Since Kotlin 1.3 you can do this:
fun getRandomString(length: Int) : String {
val allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
return (1..length)
.map { allowedChars.random() }
.joinToString("")
}
answered Jan 28 at 11:24
WhiteAngelWhiteAngel
680421
680421
add a comment |
add a comment |
Or use coroutine API for the true Kotlin spirit:
buildSequence { val r = Random(); while(true) yield(r.nextInt(24)) }
.take(10)
.map{(it+ 65).toChar()}
.joinToString("")
1
The advantage of coroutines is avoiding all these higher-order functions and writing a simple loop that does the equivalent of all of them.(1..10).forEach { yield(r.nextInt(24) + 65).toChar() }
– Marko Topolnik
May 29 '18 at 10:29
add a comment |
Or use coroutine API for the true Kotlin spirit:
buildSequence { val r = Random(); while(true) yield(r.nextInt(24)) }
.take(10)
.map{(it+ 65).toChar()}
.joinToString("")
1
The advantage of coroutines is avoiding all these higher-order functions and writing a simple loop that does the equivalent of all of them.(1..10).forEach { yield(r.nextInt(24) + 65).toChar() }
– Marko Topolnik
May 29 '18 at 10:29
add a comment |
Or use coroutine API for the true Kotlin spirit:
buildSequence { val r = Random(); while(true) yield(r.nextInt(24)) }
.take(10)
.map{(it+ 65).toChar()}
.joinToString("")
Or use coroutine API for the true Kotlin spirit:
buildSequence { val r = Random(); while(true) yield(r.nextInt(24)) }
.take(10)
.map{(it+ 65).toChar()}
.joinToString("")
answered Mar 16 '18 at 8:14
Holger BrandlHolger Brandl
4,3373229
4,3373229
1
The advantage of coroutines is avoiding all these higher-order functions and writing a simple loop that does the equivalent of all of them.(1..10).forEach { yield(r.nextInt(24) + 65).toChar() }
– Marko Topolnik
May 29 '18 at 10:29
add a comment |
1
The advantage of coroutines is avoiding all these higher-order functions and writing a simple loop that does the equivalent of all of them.(1..10).forEach { yield(r.nextInt(24) + 65).toChar() }
– Marko Topolnik
May 29 '18 at 10:29
1
1
The advantage of coroutines is avoiding all these higher-order functions and writing a simple loop that does the equivalent of all of them.
(1..10).forEach { yield(r.nextInt(24) + 65).toChar() }
– Marko Topolnik
May 29 '18 at 10:29
The advantage of coroutines is avoiding all these higher-order functions and writing a simple loop that does the equivalent of all of them.
(1..10).forEach { yield(r.nextInt(24) + 65).toChar() }
– Marko Topolnik
May 29 '18 at 10:29
add a comment |
('A'..'z').map { it }.shuffled().subList(0, 4).joinToString("")
1
While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review
– Nick
Nov 24 '18 at 6:50
add a comment |
('A'..'z').map { it }.shuffled().subList(0, 4).joinToString("")
1
While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review
– Nick
Nov 24 '18 at 6:50
add a comment |
('A'..'z').map { it }.shuffled().subList(0, 4).joinToString("")
('A'..'z').map { it }.shuffled().subList(0, 4).joinToString("")
answered Nov 23 '18 at 16:12
Louis SaglioLouis Saglio
39447
39447
1
While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review
– Nick
Nov 24 '18 at 6:50
add a comment |
1
While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review
– Nick
Nov 24 '18 at 6:50
1
1
While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review
– Nick
Nov 24 '18 at 6:50
While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review
– Nick
Nov 24 '18 at 6:50
add a comment |
Building off the answer from Paul Hicks, I wanted a custom string as input. In my case, upper and lower-case alphanumeric characters. Random().ints(...)
also wasn't working for me, as it required an API level of 24 on Android to use it.
This is how I'm doing it with Kotlin's Random
abstract class:
import kotlin.random.Random
object IdHelper {
private val ALPHA_NUMERIC = ('0'..'9') + ('A'..'Z') + ('a'..'z')
private const val LENGTH = 20
fun generateId(): String {
return List(LENGTH) { Random.nextInt(0, ALPHA_NUMERIC.size) }
.map { ALPHA_NUMERIC[it] }
.joinToString(separator = "")
}
}
The process and how this works is similar to a lot of the other answers already posted here:
- Generate a list of numbers of length
LENGTH
that correspond to the index values of the source string, which in this case isALPHA_NUMERIC
- Map those numbers to the source string, converting each numeric index to the character value
- Convert the resulting list of characters to a string, joining them with the empty string as the separator character.
- Return the resulting string.
Usage is easy, just call it like a static function: IdHelper.generateId()
add a comment |
Building off the answer from Paul Hicks, I wanted a custom string as input. In my case, upper and lower-case alphanumeric characters. Random().ints(...)
also wasn't working for me, as it required an API level of 24 on Android to use it.
This is how I'm doing it with Kotlin's Random
abstract class:
import kotlin.random.Random
object IdHelper {
private val ALPHA_NUMERIC = ('0'..'9') + ('A'..'Z') + ('a'..'z')
private const val LENGTH = 20
fun generateId(): String {
return List(LENGTH) { Random.nextInt(0, ALPHA_NUMERIC.size) }
.map { ALPHA_NUMERIC[it] }
.joinToString(separator = "")
}
}
The process and how this works is similar to a lot of the other answers already posted here:
- Generate a list of numbers of length
LENGTH
that correspond to the index values of the source string, which in this case isALPHA_NUMERIC
- Map those numbers to the source string, converting each numeric index to the character value
- Convert the resulting list of characters to a string, joining them with the empty string as the separator character.
- Return the resulting string.
Usage is easy, just call it like a static function: IdHelper.generateId()
add a comment |
Building off the answer from Paul Hicks, I wanted a custom string as input. In my case, upper and lower-case alphanumeric characters. Random().ints(...)
also wasn't working for me, as it required an API level of 24 on Android to use it.
This is how I'm doing it with Kotlin's Random
abstract class:
import kotlin.random.Random
object IdHelper {
private val ALPHA_NUMERIC = ('0'..'9') + ('A'..'Z') + ('a'..'z')
private const val LENGTH = 20
fun generateId(): String {
return List(LENGTH) { Random.nextInt(0, ALPHA_NUMERIC.size) }
.map { ALPHA_NUMERIC[it] }
.joinToString(separator = "")
}
}
The process and how this works is similar to a lot of the other answers already posted here:
- Generate a list of numbers of length
LENGTH
that correspond to the index values of the source string, which in this case isALPHA_NUMERIC
- Map those numbers to the source string, converting each numeric index to the character value
- Convert the resulting list of characters to a string, joining them with the empty string as the separator character.
- Return the resulting string.
Usage is easy, just call it like a static function: IdHelper.generateId()
Building off the answer from Paul Hicks, I wanted a custom string as input. In my case, upper and lower-case alphanumeric characters. Random().ints(...)
also wasn't working for me, as it required an API level of 24 on Android to use it.
This is how I'm doing it with Kotlin's Random
abstract class:
import kotlin.random.Random
object IdHelper {
private val ALPHA_NUMERIC = ('0'..'9') + ('A'..'Z') + ('a'..'z')
private const val LENGTH = 20
fun generateId(): String {
return List(LENGTH) { Random.nextInt(0, ALPHA_NUMERIC.size) }
.map { ALPHA_NUMERIC[it] }
.joinToString(separator = "")
}
}
The process and how this works is similar to a lot of the other answers already posted here:
- Generate a list of numbers of length
LENGTH
that correspond to the index values of the source string, which in this case isALPHA_NUMERIC
- Map those numbers to the source string, converting each numeric index to the character value
- Convert the resulting list of characters to a string, joining them with the empty string as the separator character.
- Return the resulting string.
Usage is easy, just call it like a static function: IdHelper.generateId()
edited Dec 16 '18 at 14:40
answered Dec 15 '18 at 23:16
Kyle FalconerKyle Falconer
5,25423256
5,25423256
add a comment |
add a comment |
Using Kotlin 1.3:
This method uses an input of your desired string length desiredStrLength
as an Integer and returns a random alphanumeric String of your desired string length.
fun randomAlphaNumericString(desiredStrLength: Int): String {
val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
return (1..desiredStrLength)
.map{ kotlin.random.Random.nextInt(0, charPool.size) }
.map(charPool::get)
.joinToString("")
}
If you prefer unknown length of alphanumeric (or at least a decently long string length like 36
in my example below), this method can be used:
fun randomAlphanumericString(): String {
val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
val outputStrLength = (1..36).shuffled().first()
return (1..outputStrLength)
.map{ kotlin.random.Random.nextInt(0, charPool.size) }
.map(charPool::get)
.joinToString("")
}
add a comment |
Using Kotlin 1.3:
This method uses an input of your desired string length desiredStrLength
as an Integer and returns a random alphanumeric String of your desired string length.
fun randomAlphaNumericString(desiredStrLength: Int): String {
val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
return (1..desiredStrLength)
.map{ kotlin.random.Random.nextInt(0, charPool.size) }
.map(charPool::get)
.joinToString("")
}
If you prefer unknown length of alphanumeric (or at least a decently long string length like 36
in my example below), this method can be used:
fun randomAlphanumericString(): String {
val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
val outputStrLength = (1..36).shuffled().first()
return (1..outputStrLength)
.map{ kotlin.random.Random.nextInt(0, charPool.size) }
.map(charPool::get)
.joinToString("")
}
add a comment |
Using Kotlin 1.3:
This method uses an input of your desired string length desiredStrLength
as an Integer and returns a random alphanumeric String of your desired string length.
fun randomAlphaNumericString(desiredStrLength: Int): String {
val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
return (1..desiredStrLength)
.map{ kotlin.random.Random.nextInt(0, charPool.size) }
.map(charPool::get)
.joinToString("")
}
If you prefer unknown length of alphanumeric (or at least a decently long string length like 36
in my example below), this method can be used:
fun randomAlphanumericString(): String {
val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
val outputStrLength = (1..36).shuffled().first()
return (1..outputStrLength)
.map{ kotlin.random.Random.nextInt(0, charPool.size) }
.map(charPool::get)
.joinToString("")
}
Using Kotlin 1.3:
This method uses an input of your desired string length desiredStrLength
as an Integer and returns a random alphanumeric String of your desired string length.
fun randomAlphaNumericString(desiredStrLength: Int): String {
val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
return (1..desiredStrLength)
.map{ kotlin.random.Random.nextInt(0, charPool.size) }
.map(charPool::get)
.joinToString("")
}
If you prefer unknown length of alphanumeric (or at least a decently long string length like 36
in my example below), this method can be used:
fun randomAlphanumericString(): String {
val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
val outputStrLength = (1..36).shuffled().first()
return (1..outputStrLength)
.map{ kotlin.random.Random.nextInt(0, charPool.size) }
.map(charPool::get)
.joinToString("")
}
answered Jan 16 at 21:17
jojojojo
8401328
8401328
add a comment |
add a comment |
fun randomAlphaNumericString(@IntRange(from = 1, to = 62) lenght: Int): String {
val alphaNumeric = ('a'..'z') + ('A'..'Z') + ('0'..'9')
return alphaNumeric.shuffled().take(lenght).joinToString("")
}
While this may solve OP's problem (I have not tested), code only answers are generally discouraged on SO. It would be better if you could include a description as to why this is an answer to the question. Thanks!
– d_kennetz
Feb 19 at 18:00
add a comment |
fun randomAlphaNumericString(@IntRange(from = 1, to = 62) lenght: Int): String {
val alphaNumeric = ('a'..'z') + ('A'..'Z') + ('0'..'9')
return alphaNumeric.shuffled().take(lenght).joinToString("")
}
While this may solve OP's problem (I have not tested), code only answers are generally discouraged on SO. It would be better if you could include a description as to why this is an answer to the question. Thanks!
– d_kennetz
Feb 19 at 18:00
add a comment |
fun randomAlphaNumericString(@IntRange(from = 1, to = 62) lenght: Int): String {
val alphaNumeric = ('a'..'z') + ('A'..'Z') + ('0'..'9')
return alphaNumeric.shuffled().take(lenght).joinToString("")
}
fun randomAlphaNumericString(@IntRange(from = 1, to = 62) lenght: Int): String {
val alphaNumeric = ('a'..'z') + ('A'..'Z') + ('0'..'9')
return alphaNumeric.shuffled().take(lenght).joinToString("")
}
answered Feb 19 at 13:43
Sefa GürelSefa Gürel
111
111
While this may solve OP's problem (I have not tested), code only answers are generally discouraged on SO. It would be better if you could include a description as to why this is an answer to the question. Thanks!
– d_kennetz
Feb 19 at 18:00
add a comment |
While this may solve OP's problem (I have not tested), code only answers are generally discouraged on SO. It would be better if you could include a description as to why this is an answer to the question. Thanks!
– d_kennetz
Feb 19 at 18:00
While this may solve OP's problem (I have not tested), code only answers are generally discouraged on SO. It would be better if you could include a description as to why this is an answer to the question. Thanks!
– d_kennetz
Feb 19 at 18:00
While this may solve OP's problem (I have not tested), code only answers are generally discouraged on SO. It would be better if you could include a description as to why this is an answer to the question. Thanks!
– d_kennetz
Feb 19 at 18:00
add a comment |
The best way I think:
fun generateID(size: Int): String {
val source = "A1BCDEF4G0H8IJKLM7NOPQ3RST9UVWX52YZab1cd60ef2ghij3klmn49opq5rst6uvw7xyz8"
return (source).map { it }.shuffled().subList(0, size).joinToString("")
}
But isn't it, that this just mixes the characters (elements of the list) and thus every character would be chosen only once? Or am I missing something?
– Tobias Reich
Jan 3 at 9:10
add a comment |
The best way I think:
fun generateID(size: Int): String {
val source = "A1BCDEF4G0H8IJKLM7NOPQ3RST9UVWX52YZab1cd60ef2ghij3klmn49opq5rst6uvw7xyz8"
return (source).map { it }.shuffled().subList(0, size).joinToString("")
}
But isn't it, that this just mixes the characters (elements of the list) and thus every character would be chosen only once? Or am I missing something?
– Tobias Reich
Jan 3 at 9:10
add a comment |
The best way I think:
fun generateID(size: Int): String {
val source = "A1BCDEF4G0H8IJKLM7NOPQ3RST9UVWX52YZab1cd60ef2ghij3klmn49opq5rst6uvw7xyz8"
return (source).map { it }.shuffled().subList(0, size).joinToString("")
}
The best way I think:
fun generateID(size: Int): String {
val source = "A1BCDEF4G0H8IJKLM7NOPQ3RST9UVWX52YZab1cd60ef2ghij3klmn49opq5rst6uvw7xyz8"
return (source).map { it }.shuffled().subList(0, size).joinToString("")
}
answered Nov 29 '18 at 21:30
Mickael BelhassenMickael Belhassen
26011
26011
But isn't it, that this just mixes the characters (elements of the list) and thus every character would be chosen only once? Or am I missing something?
– Tobias Reich
Jan 3 at 9:10
add a comment |
But isn't it, that this just mixes the characters (elements of the list) and thus every character would be chosen only once? Or am I missing something?
– Tobias Reich
Jan 3 at 9:10
But isn't it, that this just mixes the characters (elements of the list) and thus every character would be chosen only once? Or am I missing something?
– Tobias Reich
Jan 3 at 9:10
But isn't it, that this just mixes the characters (elements of the list) and thus every character would be chosen only once? Or am I missing something?
– Tobias Reich
Jan 3 at 9:10
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f46943860%2fidiomatic-way-to-generate-a-random-alphanumeric-string-in-kotlin%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown