Created
December 9, 2022 12:49
-
-
Save iampato/72cfd7fc0f5a4b307ca5474aa94aca9c to your computer and use it in GitHub Desktop.
Here is a possible solution for a Dart function that randomly generates unique names without using predefined lists of names:
This file contains hidden or 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 'dart:math'; | |
| // A set to store the generated names. | |
| final Set<String> generatedNames = Set(); | |
| String generateUniqueName() { | |
| // Generate a random first and last name. | |
| final firstName = generateRandomName(); | |
| final lastName = generateRandomName(); | |
| // Concatenate the first and last name to form a full name. | |
| final name = "$firstName $lastName"; | |
| // If the name is not in the set of generated names, add it and return it. | |
| // Otherwise, generate a new name. | |
| if (!generatedNames.contains(name)) { | |
| generatedNames.add(name); | |
| return name; | |
| } else { | |
| return generateUniqueName(); | |
| } | |
| } | |
| // Generates a random name by picking a random letter from the alphabet | |
| // and repeating it a random number of times (between 2 and 6). | |
| String generateRandomName() { | |
| final random = Random(); | |
| final charCode = random.nextInt(26) + 97; // Generate a random letter from 'a' to 'z'. | |
| final char = String.fromCharCode(charCode); | |
| final length = random.nextInt(5) + 2; // Generate a random length between 2 and 6. | |
| return char * length; // Repeat the letter the given number of times. | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment

This function generates random first and last names using the generateRandomName helper function, which picks a random letter from the alphabet and repeats it a random number of times (between 2 and 6) to form a name. Then, the function concatenates the first and last name to form a full name and checks if it is already in the generatedNames set. If the name is not in the set, the function adds it to the set and returns it. Otherwise, the function generates a new name by calling itself recursively. This process continues until a unique name is generated.
As with the previous solution, this is just one possible way to implement the function, and there may be other ways to achieve the same result.