Developing unique partnerships in javascript without any duplicates

Currently tackling a small project with the code provided below. Encountering an issue as it doesn't accommodate duplicates. Seeking advice on how to address this challenge.

Note that by "duplicates" I mean scenarios where Joe can't be paired with Mark and then also be paired with Matt or any other person mentioned in the list.


var people = ["Joe", "Amy", "Garrett", "Mark", "Matt", "Bri", "Rithy", "Rob", "Sandro", "Sharmila"];

for (i = 0; i < 5; i++) { 
 var pick1 = Math.floor(Math.random()*11);
 var pick2 = Math.floor(Math.random()*11);

  while (pick1 === pick2) {
    pick2 = Math.floor(Math.random()*11);
  }
  console.log(people[pick1] + " and " + people[pick2] + " are a group!");
} 

Answer №1

If you're looking to mix things up a bit, one strategy could be to eliminate individuals who have already been selected from the pool so they don't get chosen again. Here's an example of how you could achieve this:

var people = [
"Joe",
"Amy",
"Garrett",
"Mark",
"Matt",
"Bri",
"Rithy",
"Rob",
"Sandro",
"Sharmila"
];

var num_people = people.length;
result = {};

while (num_people > 1){
[1,2].forEach(function(num){
    var index = Math.floor(Math.random() * num_people);
    result[num] = people[index];
    people.splice(index, 1);
    num_people--;
});
console.log(result[1] + " and " + result[2] + " make a team!");
}

Answer №2

While you're taking care of checking duplicates, I suggest a different approach without using a while loop. My recommendation is to encapsulate the for loop within a function and have the function recursively call itself if a duplicate is found. Here's an example:

List of people: ["Joe", "Amy", "Garrett", "Mark", "Matt", "Bri", "Rithy", "Rob", "Sandro", "Sharmila"];

var pickTwo = function() {

for (i = 0; i < 5; i++) { 
 var pick1 = Math.floor(Math.random()*11);
 var pick2 = Math.floor(Math.random()*11);

  if (pick1 === pick2) {
    pickTwo();
  } else {
  console.log(people[pick1] + " and " + people[pick2] +  " are in a group!");
} 
}
}

pickTwo();

This method ensures that pairs are selected without any duplicates by continuously calling the function until a suitable pair is found. While this could result in multiple calls to the function, the likelihood of it running for an excessively long time is slim.

Answer №3

Check out this code snippet to ensure unique pairings.

  var partners = ["Emma", "Liam", "Olivia", "Noah", "Ava", "William", "Isabella", "James", "Ella", "Alexander"];

    for (j = 0; j < partners.length/2; j++) { 

      alert(partners.splice(Math.floor(Math.random()*partners.length),1) + " and " + partners.splice(Math.floor(Math.random()*partners.length),1) + " make a great team!");
    } 

Answer №4

I'm having trouble grasping your concern about avoiding duplicates because your code inherently prevents duplicate entries for pick1 and pick2.

One improvement suggestion would be to utilize a do..while loop instead of a while loop after initializing the pick2 variable. Here is how your code could look with this adjustment:

var pick2;
do {
  pick2 = Math.floor(Math.random() * 10);
} while (pick1 === pick2);

See below for a demo:

var people = ["Joe", "Amy", "Garrett", "Mark", "Matt", "Bri", "Rithy", "Rob", "Sandro", "Sharmila"];

for (i = 0; i < 5; i++) {
  var pick1 = Math.floor(Math.random() * 10);
  var pick2;
  do {
    pick2 = Math.floor(Math.random() * 10);
  } while (pick1 === pick2);
  console.log(people[pick1] + " and " + people[pick2] + " are a group!");
}

Answer №5

Randomize the list, and then divide it into pairs:

var students = ["Alice", "Bob", "Charlie", "Diana", "Eve", "Frank", "Gina", "Hank", "Ivy", "Jack"];

// creates a shuffled version of the array
function randomizeList(list) {
  const arr = [...list];
  let n = arr.length, j;
  
  while (n) {
    j = (Math.random() * n--) >>> 0;
    [arr[n], arr[j]] = [arr[j], arr[n]]
  }
  return arr;
}

// split the array into pairs
function divideIntoPairs(array) {
  let duos = [];
  for(let i = 0; i < array.length; i += 2) {
    duos.push([array[i], array[i + 1]]);
  }
  return duos;
}

console.log(divideIntoPairs(randomizeList(students))); // mix up and divide into pairs

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

What could be causing the misalignment of the Datepicker calendar in Material UI?

I have integrated a datepicker using the library "@mui/x-date-pickers/DatePicker". import { DatePicker } from "@mui/x-date-pickers/DatePicker"; import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment"; import { Locali ...

Issue: Unhandled TypeError: Problem detected when calling storage.set(object items, optional function callback) in a Chrome Extension

Attempting to create my first Chrome extension, focusing on blocking access to specific websites like Facebook or Instagram. Using code to close tabs if the blocked sites are accessed. In a separate HTML file, providing users with two radio button options ...

Retrieve and save audio files on firebase

I am currently facing a challenge in my attempt to upload an audio file and then download it later. My approach involves utilizing the Firebase server for this process. There are two specific queries that I find myself stuck on. Resolving either of them w ...

How can I add text to a textbox within a duplicated div using Javascript or Jquery?

I'm looking to add text to a cloned div's text box using jQuery. I have a div with a button and text box, and by cloning it, I want to dynamically insert text into the new div. $(document).ready(function () { $("#click").click(function () { ...

Guide on how to exit an async function

Here is the code I have been working on: myObject.myMethod('imageCheck', function () { var image = new Image(); image.onerror = function() { return false; }; image.onload = function() { return true; }; ...

Developing a compressed file in JavaScript

async purchaseMultiple(decoded, purchaseData){ const user = await Database.user.findOne({where: { id_user: decoded.id_user }}); if( ! user) return [404, 'ERROR: User [' + decoded.id_user + '] not found']; if(user.credi ...

Sorting through names within a nested array based on specific criteria

I have been struggling to filter by item name for the past day and haven't been successful. The issue lies in my attempt to use a sample array for filtering. While I am able to filter by category successfully, the same cannot be said for filtering by ...

Unending cycle of jQuery focus() event within a <select> element

This is the HTML code I am working with: <select id="select-one"> <option value="">Choose</option> <option value="1">House</option> </select> <select id="select-two"> <option value="">Choose< ...

A large canvas displaying a single optimized image

Hello, I have a large image on the canvas that measures around 10,000 pixels by 10,000 pixels. I am looking for zoom in/out functionality. Can you recommend what technology I should use? Should I consider splitting the image into smaller segments like Go ...

Is there a way to ensure my JQuery .on('click', ) function can be used multiple times?

Attempting to create a sliding pop-up feature where clicking on a label will reveal and slide out the content, then clicking the same label again will hide the content. Using JQuery for animating the div class, however the animation only triggers once per ...

Tips for fetching paginated HTTP requests from a backend API using Observables within Angular 4

My Angular 4 app has a service that retrieves a variable number of pages from a back-end API. I came across a solution on Stack Overflow which suggests using flatMap, but it doesn't work for me as the number and URLs of requests are dynamic and unkno ...

Mongoose consistently fails to properly save dates

I have created a Mongoose model and included a birthdate field in the following way: birthdate: { type: Date, required: [true, "Please enter a birthdate"], lowercase: true, validate: [isDate, "Please enter a valid birthdate&q ...

Determine the possible width of a concealed element

I am currently customizing the lavalamp plugin to be compatible with dropdown menus, but I have come across a minor issue. I am trying to determine the offsetWidth of a hidden element. Obviously, this question is a bit nonsensical. What I actually need is ...

Incorporate an element id from a separate HTML document

Trying to extract the employee's name from march.html which has an ID like: <h3 id="name">John Doe</h3> I want to retrieve this name and display it in my index.php. This is for an 'Employee of the Month' feature where I need to ...

Sliding Image Menu using jQuery

I am struggling with creating a menu using jquery mouseenter / mouseout effects. My goal is to have a small icon displayed that expands to the left and reveals the menu link when a user hovers over it. The issue I am facing is that the effect only works w ...

Angular 6 throws an error stating: "The property 'push' cannot be read of null."

The Cart model is defined as follows: //declaring a cart model for products to add export class Cart{ id:string; name:string; quantity:number; picture:string; } Below is the code for my app.service.ts: import { Injectable, Inject } fro ...

What is the best way to provide an accessible title to an SVG icon using a tooltip in MUI?

When a tooltip is used with an icon button, the button automatically takes on the accessibility name of the tooltip title. This setup, as demonstrated in the documentation example, ensures that a screen reader announces it as "Delete, button", which is ben ...

What is the best way to utilize AJAX to upload several images in PHP?

I have a UI that looks like this: https://i.sstatic.net/BAbwP.jpg I am trying to upload multiple videos using ajax in PHP. I attempted to use FormData() in jQuery for this purpose. However, it seems to only upload one image and not more than that. Her ...

Module 'prompt-sync' not found

When attempting to take user input in Node.js using the prompt module, I encountered the following error message: node:internal/modules/cjs/loader:998 throw err; ^ Error: Cannot find module 'prompt-sync' Require stack: - D:\Code\C+ ...

Choose the text that appears in the input or textbox field when tapping or clicking on it

Desperately Seeking a Clickable Textbox The Quest: In search of a cross-browser textbox/input field that can select its content on click or tap. An elusive challenge haunting developers for years. The Dilemma: Using a touch device triggers the tap e ...