By Alvin Alexander. Last updated: July 17, 2024
As a brief note today, here’s a Scala method to generate a random string that is random length and also contains blank spaces:
/**
* Produces random-length strings like these:
* genRandomVariableLengthStringWithBlankSpaces(r, 3, 15, "abcdef")
* "bff bcf"
* "f cbfe cff"
*/
def genRandomVariableLengthStringWithBlankSpaces(
r: Random,
minLength: Int,
maxLength: Int,
charsToUse: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
): String =
val ab = scala.collection.mutable.ArrayBuffer[Char]()
val strLength = randomIntBetween(minLength, maxLength)
for i <- 1 to strLength do
if i % 5 == 0 then
ab.append(' ')
else
// ab.append(r.nextPrintableChar)
val randomChar = charsToUse(Random.nextInt(charsToUse.length))
ab.append(randomChar)
val charSeq: scala.collection.mutable.Seq[Char] = Random.shuffle(ab)
charSeq.mkString
I created this because the methods in the Scala Random
class don’t work for what I need today, which is a string with a lot of blank spaces in it. I’m sure the code can be improved but I’m on a tight deadline today and this is what I came up with in the time allotted.