Generating random mobile numbers with Scala

Sometimes in testing we need to generate random data. When it comes to generating mobile numbers it would be helpful if we could be sure they aren’t allocated to a real person, just in case we accidentally send 1000 text messages to random phone numbers. Luckily Ofcom has reserved ranges of numbers for dramatic use that are guaranteed not to be allocated to providers.

Here’s a little random UK mobile number generator wrapped in an infinite-length iterator:

val random = new util.Random
val randomMobile = Iterator.continually("447700900" + f"${random.nextInt(999)}%03d")

Bonus random MAC address generator

Sometimes we need MAC addresses too. This will generate strings that look like MAC addresses (6 groups of hex digits) but aren’t really. Good enough for my purposes:

val random = new util.Random
val randomMac = Iterator.continually(Array.fill[String](6)(f"${random.nextInt(255)}%02x").mkString(":"))

Comments

2 responses to “Generating random mobile numbers with Scala”

  1. […] a previous post I gave a way of generating random test mobile numbers (Ofcom approved!) using Scala […]

  2. Marc Avatar

    This is fantastic! What a timely post; I was just wrestling with test data issues. The idea of using Ofcom’s reserved number ranges is brilliant and perfectly solves the worry of accidentally sending texts to real people during testing.

    I’ve already used your method to successfully implement data generation for a website I’m working on, and it’s working great! Thanks for sharing such practical code and insights!

    https://randomphonenumber.org/

Leave a Reply

Your email address will not be published. Required fields are marked *