Skip to content

Instantly share code, notes, and snippets.

@plombardi89
Created August 25, 2014 02:50
Show Gist options
  • Save plombardi89/b07610cca47231998650 to your computer and use it in GitHub Desktop.
Save plombardi89/b07610cca47231998650 to your computer and use it in GitHub Desktop.
Name Generator
/*
* Copyright 2014 Philip Lombardi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.time.Instant
import java.util.Random
interface NameGenerator {
String nextMaleName()
String nextFemaleName()
}
class RandomPickerNameGenerator implements NameGenerator {
private final Random random
private final List<String> maleForenames
private final List<String> femaleForenames
private final List<String> surnames
RandomPickerNameGenerator(List<String> maleForenames, List<String> femaleForenames, List<String> surnames, Random random) {
this.random = random
this.maleForenames = new ArrayList<>(notEmptyOrNull(maleForenames))
this.femaleForenames = new ArrayList<>(notEmptyOrNull(femaleForenames))
this.surnames = new ArrayList<>(notEmptyOrNull(surnames))
}
RandomPickerNameGenerator(List<String> maleForenames, List<String> femaleForenames, List<String> surnames, long seed = Instant.now().toEpochMilli()) {
this(maleForenames, femaleForenames, surnames, new Random(seed))
}
private static Collection notEmptyOrNull(Collection coll) {
if (coll == null)
throw new IllegalArgumentException("cannot be null")
if (coll.empty)
throw new IllegalArgumentException("cannot be empty")
coll
}
private getRandomValueInList(List list) {
list[random.nextInt(list.size())]
}
String nextMaleName() {
getRandomValueInList(maleForenames) + " " + nextSurname()
}
String nextFemaleName() {
getRandomValueInList(femaleForenames) + " " + nextSurname()
}
String nextSurname() {
getRandomValueInList(surnames)
}
}
def names = new RandomPickerNameGenerator(['Phil', 'John', 'Mike', 'David', 'Josh'], ['Sara', 'Nicole', 'Dolores', 'Amanda', 'Elizabeth'], ['Wadsworth', 'Pemberton', 'Guiva', 'Johnson', 'Iqbal'])
println """
Males
-----
"""
10.times {
println names.nextMaleName()
}
println """
Females
-------
"""
10.times {
println names.nextFemaleName()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment