How can I efficiently generate unique combinations from multiple lists?

I am on a mission to create a football squad consisting of 11 players. Each of these players is directly linked to some others, forming what can be visualized as a "neural network architecture with 11 nodes".

Picture this scenario: I have a dedicated list for each position (node area) on the field - GoalKeeper_List, LeftBack_List, CenterMid_List, and so forth.

Within each list, there are 15 potential players. This means that a particular node area can only be filled by the corresponding 15 players.

The fundamental rule in place states that when a node's neighboring positions are occupied (i.e., its neighbors are no longer empty), a function is triggered. This function evaluates how well the node performs alongside its neighbors and returns either "OK" or "Not-OK".

If the function deems the performance "Not-OK", it signals that the entire squad configuration cannot work, regardless of other node statuses.

It is essential to note that the function runs independently for each node, based on the parameters of its neighboring positions, but it can only execute when all of a node's adjacent spots are occupied.

My objective is to have my program generate all possible squads using the pool of 11x15 players (from 11 separate lists). Without any restrictions, there would be a staggering 15^11 possible combinations – equivalent to approximately 8.6 trillion squads, rendering computations nearly impossible. However, applying the rules significantly trims down the available options. Consequently, when the code executes, it typically yields results ranging from 1 to 30000, which the computer can handle effectively. I have conducted several trials to arrive at these figures. Nevertheless, my current implementation suffers from sluggish performance due to the nested loops within the code structure, often leading to variable computation times — sometimes resolving in 40 seconds, other times extending to 10 minutes, or occasionally failing to produce results altogether despite viable squad configurations.

I am convinced that there exists a more efficient approach to enhance the speed of this code execution, thereby necessitating a fresh strategy to tackle this challenge.

Below is the code snippet giving insight into the ongoing process:

let working_squads = []

let current_full_squad = []
for (gk of GK_List){


  for(cb1 of CB1_List){
    current_full_squad = [gk]


    for(cb2 of CB2_List){
      current_full_squad = [gk, cb1]

      let GK_status = get_player_status(gk, [cb1, cb2])
      if(GK_status === "Not-OK") continue


      // Nested loop continues...
      
    }                     
  }
}

console.log(working_squads.length.toString() + " squads found! Here they are... ")

Answer №1

This particular technique may not offer a faster solution (in theory), but it does provide a more elegant approach. It allows for the creation of teams with varying sizes if any list is completely rejected. If you only desire squads of a specific size, filters can be applied either during or after the function execution.

The methodology involves recursively posing the same question: Given a team and a collection of other player lists, what are all the possible combinations? The process entails seeking input from each player regarding their willingness to join the squad, and upon approval, adding them to the team roster before repeating the procedure with the updated team configuration sans the chosen player list.

class Player {
    constructor ( name ) {
        this.name = name;
        this.wontPlayWith = [];
    }

    AddRejectedPlayers ( ...player ) {
        this.wontPlayWith.push( ...player );
        return this;
    }

    WillPlayWith ( player ) { // simply a demonstration; customization is encouraged.
        return !this.wontPlayWith.includes( player );
    }
}

class Squad {
    constructor ( players ) {
        this.players = [ ...players ];
    }

    static MakeAllPossibleSquads ( acceptedPlayers, remainingPlayerLists ) {
        let result = ( remainingPlayerLists.length == 0 ) ? [ new Squad( acceptedPlayers ) ] : [];
        remainingPlayerLists = [ ...remainingPlayerLists ]; // safeguarding the original list

         while ( remainingPlayerLists.length != 0 ) {
            let nextList = remainingPlayerLists.pop();

            for ( let i = 0; i < nextList.length; i++ ) {
                let nextPlayer = nextList[ i ];

                if ( acceptedPlayers.every( x => x.WillPlayWith( nextPlayer ) && nextPlayer.WillPlayWith( x ) ) ) {
                    result.push( ...Squad.MakeAllPossibleSquads( [ acceptedPlayers, nextPlayer ], remainingPlayerLists) );
                }
            }
        }

        return result;
    }
}

console.log( Squad.MakeAllPossibleSquads( [], yourListOfPlayerLists ) );

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

Troubleshooting: Problems with Encoding and Decoding JSON

I am attempting to establish a connection between a Chrome extension and a PHP file using XMLHttpRequest. It is working fine, but I am having trouble using JSON.parse to decode the JSON. This is my JavaScript file: var client = new XMLHttpRequest(); ...

The margins within the div of the new tab are not applying as expected

Greetings! Currently, I am in the process of generating a dynamic form within a new tab using JavaScript. For some reason, the margin effects on the div element are not being applied correctly. Despite my attempts to set the margins using both classes and ...

Modifying button text dynamically during save operation with AngularJS

Is it possible to dynamically change the text on a submit button while data is being saved in a form? Here's an example of the button: <button ng-click="save()">Save data</button> I have updated my save function based on some suggestion ...

What is the most effective way to monitor the duration of video playback?

Whenever a user watches a video, I aim to initiate 2 AJAX calls. The first call should trigger when the user finishes watching the entire video or if the time played is equal to or greater than the duration of the video (considering users may rewind). time ...

Protractor struggles to locate Angular framework

I am experiencing issues with Protractor recognizing that Angular is loaded and operational. Upon opening Chrome, my application fully loads in the browser, confirming that Angular is indeed loaded and running correctly. Here is the configuration file: e ...

Remove rows that have values within a specific range

I'm facing an issue in Google Sheets where I'm attempting to delete entire rows on the "Data" sheet if any value in column B matches values from the range D3:E20 in the "Backend" sheet. The code provided works when a word is hardcoded as the cond ...

"Surprising Outcomes When Using JSP, JavaScript, and Servlet Together

I am facing an issue with a form on a jsp that calls a javascript function, which in turn calls a servlet. The problem is that the code works intermittently, and when it does reach the servlet, the parameters come back as null. It's also strange that ...

Is there a way to transmit the ENTER key press to the page setup dialog within Internet Explorer 7?

My code is designed to change the page orientation. It functions correctly in IE6, but encounters issues in IE7. Specifically, it stops at %a and fails to input the enter or tab keys needed to press 'OK'. var shell; function SetPrintProperties() ...

Learning React: Error - Unable to access the 'data' property when it is null

Currently, I am learning React by following a tutorial available at this link: http://facebook.github.io/react/docs/tutorial.html Specifically, I am focusing on the section related to fetching data from the server, which can be found here: http://facebook ...

Prevent the date each month in asp.net

Is there a way to block Sundays for all months and years in a text box with the Text mode set to Date? <asp:TextBox ID="txtfromdate" runat="server" Enabled="True" OnTextChanged="From_TextChanged" TextMode="Date" ></asp:TextBox> ...

Is there a way to make all Bootstrap column heights equal using only jQuery?

I am currently working on matching the heights of two columns without using an existing library like match-height.js. In this specific case, I have a row with 2 columns where the first column contains a centered black square and the second column contains ...

Utilizing 'this' in jQuery: Image swapping with thumbnails, Twitter Bootstrap framework

Is it possible for jQuery's 'this' to simplify my code? You can view the full code here. Thank you for any help or suggestions. Here is the jQuery code: /* Ref: http://api.jquery.com/hover/ Calling $( selector ).hover( handlerIn, handler ...

Difficulty navigating through pages on an iPad due to slow scrolling with JavaScript

My operation is executed within a scroll function, like this: Query(window).scroll(function(){ jQuery('.ScrollToTop').show(); // my operation. }); While my web page responds quickly to the operation, it seems slo ...

What is the best way to choose multiple values from a dropdown menu and display them as a comma-separated string in a Material Table in React

I am exploring the editComponent feature in React's material table to implement a dropdown that allows users to select multiple options and display them as a comma-separated string. For example, if a user selects option1 and option3, the value disp ...

Attempting to feed information into a computed property within Vue.js

I'm currently working on a project that involves Vue JS, specifically Nuxt JS. Within my web page, I am required to render certain classes onto an element that exists within a v-for loop. To achieve this, I need to pass data to a computed property alo ...

Modifying multiple heading tags simultaneously with jQuery

Currently utilizing jQuery to append a string to all heading tags (h1, h2,..., h6) and display it on the screen. Seeking guidance specifically for the replacing aspect, and open to solutions using plain javascript as well. The code I have so far, which I ...

Inadequate tweening adjustments upon mouse exit

When I try to tween a variable down to zero on mouseleave, nothing seems to happen when the mouse leaves the container. I've experimented with different approaches but can't figure out what I'm doing wrong. Here's the code snippet in q ...

Issue with the react-native-autocomplete-input where the list does not close after selecting an option

After selecting an item from the list in my react-native-autocomplete-input, the list does not close. let Location = (props) => ( <View style={styles.formItem}> <Autocomplete data={props.autocompleteResults.predictions} de ...

Implement a one-second delay before nesting another animation

I'm currently utilizing a timeout function, but I am interested in using a delay instead. My goal is to have the second animation start when one second has passed from the beginning of the first animation, and it should be a linear animation. How can ...

A `PUT` request is sent using AJAX, but no data is transferred along with it

When using AJAX, you should have support for the "PUT" and "DELETE" requests. I'm encountering an issue where the server acknowledges the data sent via the "PUT" request, but no parameters are being transmitted. The same problem occurs with the "DELET ...