Currently tackling a challenging exercism problem that involves generating 10000 random names without any duplicates. The jasmine-node test checks for this specific requirement:
it('there can be lots of robots with different names each', function() {
var i,
numRobots = 10000,
usedNames = {};
for (i = 0; i < numRobots; i++) {
var newRobot = new Robot();
usedNames[newRobot.name] = true;
}
expect(Object.keys(usedNames).length).toEqual(numRobots);
});
I believe the solution involves creating an array to store generated names and checking for duplicates before adding them to the array.
The code I've written so far is as follows...
"use strict";
var robotNames = [];
var name;
var Robot = function() {
this.name = this.generateName();
};
Robot.prototype.generateName = function() {
var letters = "";
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numbers = "";
var digits = "0123456789";
// generate random characters for robot name...
for( var i=0; i < 2; i++ ) {
letters += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
};
for( var i=0; i < 3; i++ ) {
numbers += digits.charAt(Math.floor(Math.random() * digits.length));
};
name = letters+numbers;
// Check for duplicate names in the array
for(var i = 0; i < robotNames.length; i++) {
if (name == robotNames[i]) {
this.generateName();
return;
} else {
robotNames.push(name);
}
}
return name;
};
Robot.prototype.reset = function() {
this.name = this.generateName();
};
module.exports = Robot;
Unfortunately, the test fails with the error message: "Expected 9924 to equal 10000."
The number '9924' varies slightly upon each test run, indicating that there may be instances where the generateName function produces matching names. It seems like my current approach to checking for duplicates might not be executing correctly.
I have experimented with variations of the loop but have yet to achieve success. Therefore, I am seeking guidance on whether my method is correct and if there are any issues with the syntax of my loop, or perhaps I am misunderstanding how to identify duplicates in this scenario.
Any help or suggestions would be greatly appreciated. Thank you.