How to create a random 4 character alphanumeric string

Hello
Recently someone asked to come up with Scala code on an over the phone coding screen. I failed that interview of course. That is the bitter truth.
So this question here is only to educate myself on how to solve that problem. Perhaps it might just help me learn more about Scala . That is the intention.
Stressful as it was and the fact that I had to come up with a one-liner Scala expression quickly, did not help.
'
So, the question was: Come up with code that generates a 4 character alphanumeric string like: W1234, or B2351, Z7891. Note that special characters are not allowed. Capitalization does not matter.

I could go into the scala,util.Random library and try writing the code myself. But I would like to request the Scala folks here to help me solve this problem, from scratch. I want to get a glimpse into the thought process of a seasoned, experienced, quick-thinking Scala programmer.
My goal is to learn from all this and start contributing my own solutions on this forum. Let this be the way to get all this started.

Thanks
ilango

Hi

The 4 character codes in your example are all 5 character codes - maybe it was a trick question!

For short lived codes (e.g. send by email/sms to provide the user can access the email account or phone) I do this:

object OneTimeCode {
def apply(length: Int = 6) = {
Random.alphanumeric.take(length).mkString("")
}
}

If you want a specific pattern you’d need to adjust accordingly, and it’s worth noting that this doesn’t use SecureRandom so it’s not cryptographically strong.

Thanks
Brian

another solution (based on slightly different assumptions of what the problem even is):

scala> import util.Random.nextInt
import util.Random.nextInt

scala> f"\${('A' to 'Z')(nextInt(26))}\${nextInt(10000)}%04d"
res5: String = J3739

I missed that entirely. You are right. It could have been a trick question.
So, if we changed the question to: Come up with code that generates a 4 character alphanumeric string like: W123, or B235, Z789. Note that special characters are not allowed.
Would the code then be:

object OneTimeCode {
def apply(length: Int = 5) = {
Random.alphanumeric.take(length).mkString("")
}
}

The results of running your code are here under:

1. apply has an argument 6 - the method returned dNmVwa
2. apply has an argument 5 - the method returned P049a

Both the results do not contain number.

The way I am interpreting this is: If the interviewer wanted only 4 ‘characters’ or 5 'characters" then the result will contain only characters.

But, if, say, we took the trick part out of the question and assume he just wanted an 4 or 5 length alphanumeric string, then we would need W123 or W1234, right?

And the OneTimeCode code has to be modified, right?

I did not know about the “take” method at all.
Thank you.

I ran your code again by passing argument 5
This time, it generated, xW0L4.
What if we wanted our string to be exactly of the pattern: W1234, a letter followed by 4 numbers.
This may not be necessarily what the had interviewer wanted. I am just trying to challenge myself

Thank you, Seth. I am going to run this in my interpreter right now.

Mildly related - never use screen shots of code. Copy the text instead. For me, someone using a screenshot to show code is a huge red flag, right there.

Oh, I did not know that. That was an innocent doing - copying a screenshot
Let me copy the text instead. Here it is:

The code in question was written for me by Brian, of course.

scala> import scala.util.Random
import scala.util.Random

scala> OneTimeCode.apply
OneTimeCode.apply
^

scala> object OneTimeCode {
| def apply(length: Int = 5) = {
| Random.alphanumeric.take(length).mkString("")
| }
| }
defined module OneTimeCode

scala> OneTimeCode.apply
:10: error: missing arguments for method apply in object OneTimeCode;
follow this method with `_’ if you want to treat it as a partially applied function
OneTimeCode.apply
^

scala> OneTimeCode.apply(5)
res2: String = Po49a

scala> OneTimeCode.apply(6)
res3: String = dNmVwA

scala> OneTimeCode.apply(5)
res4: String = xW0L4

scala>

You’ll find that some interviewers intentionally ask confusing, vague, or even incorrect questions, to see how you respond when given unclear requirements.

Here’s the thought process.

1. The examples all have a letter first, followed by four numbers.
2. This is five characters, but whatever. Let’s make that a parameter.
3. You can get random numbers from scala.util.Random
4. The nextIntmethod can get numbers in a range
5. This needn’t be fast, we just want numbers to become letters
6. nextInt(26) + 'A' will give us a number corresponding to a letter (but we need a toChar)
7. nextInt(10).toString will give us digits
8. We need a bunch of digits, but if they’re in a collection we can just mkString it
9. Okay, write it all down in code
import scala.util.Random._
def alns(digits: Int) =
(nextInt(26) + 'A').toChar.toString +
(0 until digits).map(_ => nextInt(10)).mkString

That is the thought process I was looking for. I am going to try out the code.
Thanks to you for being so thorough.

Awesome. That produced:
scala> f"\${(‘A’ to ‘Z’) (nextInt(26))}\${nextInt(10000)}%04d"
res8: String = Z1893

and
scala> f"\${(‘A’ to ‘Z’) (nextInt(26))}\${nextInt(10000)}%04d"
res9: String = D0254

This works perfectly.

Can you throw some light on the last part "nextInt(10000)…

I am reading up the Scala documentation right now

Works beautifully. Here are the results in my REPL

scala> def alns(digits: Int) = (nextInt(26) + ‘A’).toChar.toString + (0 until digits).map(_ => nextInt(10)).mkString
alns: (digits: Int)String

scala> alns(4)
res11: String = K8632

scala> alns(4)
res12: String = Y0058

scala> alns(4)
res13: String = V6898

I certainly have some learning to do to incorporate this kind of thought process into my Scala code

So seems to be the case. I thought something was not right about the interviewer’s question but, did not step up and could not show my chops, speaking of which, I have some building to do.

Thank you. that was a learning process

The f string interpolator uses C-style printf format strings (https://en.wikipedia.org/wiki/Printf_format_string), in which %04d means to left-pad an integer with 0s until it’s at least 4 full digits.

printf format strings are 1970s stuff. I am not seriously suggesting that involving one is the best way to go here, I just thought it would be fun to throw a variety of solutions out there.

Thanks again. That helps

Thank you for going above and beyond