Verify the presence of duplicate values in an array containing randomly generated elements

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.

Answer №1

The issue lies within this section:

for(var i = 0; i < robotNames.length; i++) {
    if (name == robotNames[i]) {
        this.generateName();
        return;
    } else {
        robotNames.push(name);
    }
}

It seems that you are adding the name to the list as soon as one does not match. It would be more appropriate to only push the name if NONE of the existing names match. Consider revising the code like so:

for(var i = 0; i < robotNames.length; i++) {
    if (name == robotNames[i]) {
        return this.generateName();
    }
}
robotNames.push(name);

(taking into account the missing return statement for the recursive call to this.generateName, it's questionable how your program was functioning correctly...)

Answer №2

Look for a library that provides Sets implementation, such as Collections.js which is highly recommended.

Sets are unique in nature as they do not allow duplicates. If you try to add a value to a set that already exists, it will simply ignore the duplicate and move on with adding the value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Traversing Firebase Datasnapshot and saving data into an array

While developing an Android magazine app, I encountered the task of retrieving information about magazines from a Firebase DataSnapshot and storing them in separate arrays. Utilizing a helpful guide on retrieving data from Firebase database was crucial i ...

I'm having trouble getting my window resize event listener to function properly. I'm using a combination of Three.js and Vuetify.js

My goal is to incorporate a three.js renderer into a div element using the vuetify.js framework. I want my code to dynamically adjust the dimensions of the div element whenever the window is resized. I have excluded unnecessary code blocks from this excer ...

The ASP.NET JSON response unexpectedly contained undefined data

I am working on a straightforward web application that features a HouseUnitController containing an action that delivers a JSONResult. public JsonResult GetHouseUnits() { var houseUnits = db.HouseUnits.Include(h => h.HouseModel).Include(h = ...

Having trouble locating a method in $scope following angular $compile

Apologies for the simple question, I am a beginner in AngularJS and front-end development. I am attempting to create a modal using bootbox as shown below: In Service: function _modalData(){ let element = "<div onclick=\"saveSelecti ...

Process for arranging an array according to the sorting sequence of another

Using two arrays in a Highcharts "series" parameter, for example: X = [25, 100, 50, 12] Y = [50, 12, 100, 25] The sequence of X and Y corresponds to the chart's Y value. When sorting X in ascending order, Y's order should match by becoming: X ...

Modifying an element's value according to user input: Step-by-step guide

Within my dropdown menu, there is a single option labeled "Others". Upon selecting this option, a textbox appears allowing me to input custom text. Is it possible to dynamically update the value of the <option value="Others">Others</option>, ...

Leveraging npm packages within a Meteor project through cosmos:browserify

Trying to implement Radium, a JavaScript library for inline CSS, by following the instructions located here. In my app.browserify.js file: Radium = require("radium"); Within package.json: "radium": "0.13.4" Upon attempting to utilize Radium in the app&a ...

What is the best way to divide two ranges that are intersecting?

Seeking a method to divide two overlapping ranges when they intersect. This is my current progress using typescript, type Range = { start: number; end: number; }; function splitOverlap(a: Range, b: Range): Range[][] { let result = []; const inters ...

How can we avoid page flickering and stuttering while scrolling using the ScrollTo script?

Currently, I am utilizing Ariel Flesler's ScrollTo script which can be found on this page. There are two links located at the bottom of the page that when clicked, will scroll to the top of the page. One of the links also triggers a contact form to op ...

Can the mDNS string received through webRTC be decoded to retrieve a user's IP address?

After doing some thorough research, I came across this insightful response from a different Stack Overflow question. The problem at hand involves retrieving an mDNS string, which looks like this: abcd1234-1e1e-1e1e-1e1e-abcd1a2bc3de.local I have a genuin ...

Encountering invalid parameters while attempting to utilize the track.scrobble service from the Last.Fm API in a Node.js application

After successfully completing the Last.Fm authentication process following the instructions provided here, I received the session key without any issues. However, my attempts to make an authenticated POST request to the track.scrobble method of the Last.Fm ...

Issue: Headers cannot be set again once they have been sent during page reload

Whenever I attempt to refresh a specific page, I encounter an Error: Can't set headers after they are sent. Interestingly, when I click on a link to navigate to that page, the error doesn't occur. I have meticulously reviewed the sequence of even ...

What is the best way to incorporate external scripts into a Node.js project?

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.js"></script> What is the process for adding an external library to a node.js application? I am seeking assistance on how to integrate the following library into my ...

Ways to convert a jQuery object into HTML that can be utilized?

When running the code below, an alert message of "object Object" is displayed: var shipImgs = $("#div").children(); alert(shipImgs); The container with id "div" includes a total of 4 children (image tags). <div id="div"> <img src="/imgs/spa ...

Discovering the process of retrieving API data upon a button click within Next.js using server-side rendering

Hi there, I'm fairly new to working with next.js and would greatly appreciate some assistance. I am trying to figure out how to fetch data from an API upon clicking a button in next.js on the server side. I understand that using onClick directly is ...

What benefits does redux-thunk offer?

Why is redux-thunk necessary? It seems like using a thunk just adds an extra layer of complexity by wrapping expressions and using middleware. The sample code from redux-thunk further confuses the process. import thunk from 'redux-thunk'; // No ...

When CSS is modified by inserting an extra div, it causes the positioning of other elements to shift towards

I'm currently working on adapting a method to make elements "sticky" for older browsers as discussed in this particular article. The basic idea involves implementing some JavaScript code that listens for scroll events. Upon detection of such an event ...

Browser Compatibility with AngularJS

Encountering an issue with AngularJS compatibility - are there any features not supported by Google Chrome? We have developed the AngularUI Calendar and utilized the JSFiddle link below: http://jsfiddle.net/joshkurz/xqjtw/52/ The UI calendar works on Fi ...

Trigger a JavaScript function just before navigating to the next page in the background

I am trying to call a Javascript function from the code-behind in vb.net, but I'm facing an issue where the function is not being executed properly due to redirection to the next page before it runs. I do not want to trigger this function on an Onclic ...

Having trouble retrieving the component state within AgGrid's cellRenderer

When working on my React app using functional components, I encountered an issue with accessing a local state (myObj) within a cellRenderer in AgGrid. The local state is populated via a context object from the parent component based on an API response. Un ...