Creating a fairness algorithm with circular arrays in Javascript: A step-by-step guide

My child's baseball team consists of 13 players. In order to ensure that each player has an equal opportunity to play different positions, I devised a JavaScript algorithm. However, the current algorithm does not seem to be distributing the positions fairly and is quite confusing. Can anyone suggest a simpler and more effective approach?

var kids = new Array("Amelie","Avery","Brennan","Clayton","Devin","Flynn","Haydn","Jack","Kai","Liam","Max","Maxi","Sterling");
    var kids_copy = kids.slice(0);
    var positions = new Array("Pitcher","Catcher","Third Base","Short Stop","Second Base","First Base","Right Field","Ctr Right","Ctr Left","Left");
    var positions_copy = positions.slice(0);
    var assignment = new Array();

    for(i=0;i<positions_copy.length;i++){
        j = i%positions.length;
        assignment[j] = new Object();
          for(h=0;h<kids_copy.length;h++){
                  if((positions[0]) && (kids[0])){
                    role = positions[0].trim();
                    person = kids[0].trim();
                    assignment[j][role] = person; 
                  }
                  var shifted = kids.shift();
                  kids.push(shifted);

                  var position_shifted = positions.shift();
                  positions.push(position_shifted);    
            }
            var shifted = kids.shift();
            kids.push(shifted);
          }

    for(i=0;i<assignment.length;i++){

        console.log("\nIteration: " + (i+1));

        for(h=0;h<positions_copy.length;h++){
            l = positions_copy[h];
            console.log(l + '=' + assignment[i][l]);

        }
    }

Answer №1

// Initialize the roster.
var members = ["Amelie","Avery","Brennan","Clayton","Devin","Flynn","Haydn","Jack","Kai","Liam","Max","Maxi","Sterling"];
var positions = ["Pitcher","Catcher","Third Base","Short Stop","Second Base","First Base","Right Field","Ctr Right","Ctr Left","Left"];

for (var count=members.length; count>0; count--) {
    var firstToLastMember = members[0]; // Store first member temporarily
    members.shift (); // Remove first member from the list 
    members.push(firstToLastMember); // Add the stored member to the end
    console.log (members); // ["Avery", "Brennan", "Clayton", "Devin", "Flynn", "Haydn", "Jack", "Kai", "Liam", "Max", "Maxi", "Sterling", "Amelie"]

    // Display the list of positions next to each member
    for (var index=0; index<positions.length; index++) {
        console.log (members[index] + ': ' + positions[index]);
    }
    console.log ('-----');
}

If your goal is simply to rotate the members' list, this script should accomplish that.

Edit: Added a loop.

Answer №2

With an abundance of players compared to available jobs, I have incorporated the concept of 'Not playing' roles into your array. This allows for a seamless rotation of jobs while ensuring everything aligns perfectly.

Here is a straightforward solution that involves rotating the jobs array by a specified number:

var people = ["Amelie", "Avery", "Brennan", "Clayton", "Devin", "Flynn", "Haydn", "Jack", "Kai", "Liam", "Max", "Maxi", "Sterling"];
var jobs = ["Pitcher", "Catcher", "Third Base", "Not playing", "Short Stop", "Second Base", "First Base", "Not playing", "Right Field", "Ctr Right", "Ctr Left", "Left", "Not playing"];


function getPositions(gameNumber) {
    for (var i = 0; i < people.length; i++) {
        console.log("Player: " + people[i] + ", " + jobs[(i + gameNumber) % jobs.length]);
    }
}

If you plan on playing 10 games, simply call the function 10 times with the gameNumber parameter ranging from 1-10.

To ensure fairness, you can also shuffle the initial players array. Refer to How can I shuffle an array? for more details.

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

I'm looking to create a unit test for my AngularJS application

I am currently working on a weather application that utilizes the to retrieve weather data. The JavaScript code I have written for this app is shown below: angular.module('ourAppApp') .controller('MainCtrl', function($scope,apiFac) { ...

Communicating PHP variables with JavaScript through AJAX in a chat application

Hello there! I am currently in the process of developing a chat application for my website that includes user registration and login. My backend server is built using NodeJS to leverage SocketIO capabilities. Within my index.php file, I have implemented ...

Is Click and Mousemove available for iPhones?

I am experiencing some difficulties with mouseover and click events. While they work fine on desktop and laptop web browsers, they do not seem to function on the Safari browser of an iPhone. Below is the code snippet causing the issue: <script type="te ...

Tips for retrieving the text from a child element in a list with jQuery

I'm having trouble accessing the text of a child element within a list. I can only access the parent element and not sure how to get to the child element. Here is the HTML code: <ul class="nav nav-list"> <li class="active"> < ...

In the production build of Next.js, accessing dynamic routes may lead to a 404 error

Incorporating Dynamic Routing in my next JS project has been a seamless process so far. During development mode, all features are functioning as expected. However, I noticed that when I access a dynamic page for the first time, it loads without any issue ...

Generate a dropdown menu with dynamic options populated from an API by adding an input type select element dynamically

Greetings! I am working on designing a decision tree that dynamically generates options based on user selections and API responses. When a user chooses a reason option, the corresponding reasons are fetched from the API and displayed in a select dropdown. ...

How can I make AWS SDK wait for an asynchronous call to finish executing?

Understanding the AWS SDK documentation can be a bit confusing when it comes to making asynchronous service calls synchronous. The page at https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html states: All ...

Output certain elements from an array and then incorporate them into an if-else statement

I am currently working on developing an on and off switch that is based on an item within an array. The data has already been extracted from JSON, so now I just need to work with the array. This array has been generated from an API call and is returned in ...

Verify if an array consists of numbers or strings and finalize the if/else statement

I'm struggling to figure out how to modify my code to determine whether the array contains an integer. If it does, I want to increment it by 1, and if it doesn't, I want to display the string or symbol as is. I have added #notes where I got stuc ...

Creating a Java array without specifying the size in advance

Is there a way to create an array of objects from a class within another class without specifying the size in advance? ...

Implementing a custom button specifically for the month view in JavaScript FullCalendar

I have successfully added a custom button to my JavaScript full calendar code, but I would like this button to be displayed only in the month view. $(document).ready(function() { var calendar = $('#calendar').fullCalendar({ editable: tru ...

Parsing the JSON object from the PHP/AJAX response results in the display of [object, Object

My AJAX request response is returning [object, Object] values instead of the expected ones after parsing it as JSON. What could be causing this issue? In my setup, I have two scripts – "apply.php" and "suburb.php". The "apply.php" script contains a shor ...

Postman: Iterating through requests with various input data sets to dynamically generate the request body

I am facing a challenge with my login API request that requires 3 parameters (userName, password, and remember) in the request body. Out of these parameters, userName and password are mandatory, while remember is optional. The input data is being pulled fr ...

Can Angular handle properties containing hyphens within them?

As I embark on creating my first complete Angular application, I encountered an interesting quirk. The model I am working with has a data structure that looks like this: { id: "12345", host: { name: "someHostServer", ip-addresses: ...

Combine two entities to create a new entity that mirrors the structure of the first entity

Can someone assist me with a data structure issue? Here are the objects I am working with: const elements = { item1: {color: 'blue', name: 'Item One' }, item2: {color: 'green', name: 'Item Two' }, item3: {colo ...

Reset input fields while retaining placeholder text

Seeking advice on how to use this handy jQuery tool properly: $('.myDiv input').each(function () { $(this).val(""); }); Though it clears my form, I'm struggling to maintain the placeholders of the inputs. Any suggestions? C ...

Using JQuery to attach a click event to a div element

My HTML code looks something like this: <div class="vmail vmail-bar normal-vmail-bar" id="pm_<?php echo $pm->to_id; ?>"> <div class="checkbox"><input type="checkbox" class="checkbox" /></div> ...

having trouble retrieving information from the input field

I'm having trouble retrieving the user's input from the input field, can someone assist me with this issue? I can't seem to identify what the problem is here. var ftemp = document.getElementById("Farenheit").value; <td> <i ...

The Javascript toggle for hiding and showing did not function as expected

I've been attempting to create a JavaScript toggle so that when I click on any of the buttons below, only that particular div is shown and all others are hidden. Unfortunately, my code is not working as expected: function toggle(show,hide) { do ...

Controlling numerous websockets using React

I am currently developing a single-page application using React.js with a JSON RPC 2.0 backend API that relies on websockets. Managing multiple websocket connections simultaneously across different React.js components has been a challenge. Initially, I th ...