Finding the number of ways to extract arrays with 7 elements from a larger array of 49 elements in Javascript

I have a task to create unique groups of 7 elements from an array of 49 and determine the number of possible outputs.

For example: [A,a,B,b,C,c,D,d,E,e,F,f,G,g,H,h,I,i,J,j,K,k,L,l,M,m,N,n,O,o,P,p,Q,q,R,r,S,s,T,t,U,u,V,v,W,w,X,x,Y]

The desired outputs are: [ [A,a,B,b,C,c,D], [a,B,b,C,c,D,d], [B,b,C,c,D,d,E], [b,C,c,D,d,E,e], . . . [A,C,c,D,d,E,e], [A,B,b,c,D,d,E], . . . ] How can I achieve this output? Below is my attempt based on advice received from stackoverflow:

let jar = ["A","a","B","b","C","c","D","d","E","e","F","f","G","g","H","h","I","i","J","j","K","k","L","l","M","m","N","n","O","o","P","p","Q","q","R","r","S","s","T","t","U","u","V","v","W","w","X","x","Y"];
 
const size = 7;

let result11 = [];

for(let i = 0; i <= (jar.length - size); i++){
     result11.push(jar.slice(i, size+i));
}
console.log(result11)

Each output should be unique without any repetition. For example, outputs like aaaaaaa, aaxxxYY, AAAAAAA, AABbcDe are not valid, but outputs like avWwXxY, bvWwXxY, cvWwXxY, among others, are acceptable.

Answer №1

Here is a functional code snippet that generates unique combinations from an array. The starting point is the initial draw vector v. This vector should have the same number of elements as the desired draws and must be in ascending order. Using the function nextDraw(), the next possible combination is selected from the available numbers between 0 and n-1.

The snippet is limited to 1000 draws to avoid overwhelming you with all possible combinations, which would be too many to handle.

function nextDraw(v,n){
 // generate a new vector w by copying v
 // set k to point to the last element of w:
 let w=v.slice(0),l=w.length,k=l-1;
 while (true){ // unconditional loop
  // Is the k-th element of w lower than n-l+k?
  if (w[k]<n-l+k) {
   // increment w[k]
   w[k]++;
   // and, in case k<l-1:
   // initialise all following elements of w with an increasing sequence:
   for (let j=k+1;j<l;j++) {
    w[j]=w[j-1]+1;
   }
   // return a valid draw vector!
   return w;
  }
  else {
   // as long as there is still a smaller k index available: decrement k
   // and continue with the while loop
   if(k) k--
   // else: we have reached the end of the series! 
   else return false;
  }
 }
}
function allDraws(v,n){
 const res=[];
 res.push(v);
 while (res.length<1000 && (v=nextDraw(v,n))) res.push(v)
 return res;
}

// Show first 1000 and last 121 draws:
[[0,1,2,3,4,5,6],[38,43,44,45,46,47,48]].forEach(v=>{
  let res=allDraws(v,49);
  console.log(res.length,res.map(r=>r.join(",")));
});

Although the snippet works with index numbers instead of arbitrary elements, you can easily use the calculated index vectors to retrieve actual values from an array of length n.

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

If function is called after x seconds

Here is a JavaScript code snippet that triggers different functions based on the number of clicks. For instance, clicking once triggers function1, while clicking twice triggers function2. Now, how can I modify this code so that if I am in the stop_autosli ...

Coloring a table in vue.js based on performance rankings

I'm facing an issue with sorting my data performance in vue js. Here is the script I have created so far: <template> <div> <div class="row"> <h2> Campaign Performance </h2> <table class=&q ...

Interacting with various cookies created from user-provided input (specifically from textboxes) simultaneously

I'm facing a challenging problem and I'm in need of some assistance. The task at hand is to create three text boxes for users to input values for cookies named: name, city, and hobby. Then, using a single button with an onclick event, a function ...

The combination of Node.js and a Telegram bot

I am trying to utilize a telegram bot to access a specific route on a website. Within the website's routes.js file, I have: app.get('/api/getalert', getAlert); and var getAlert = function(req, res) { var id = req.query.id; ...

Managing the "Accept Cookies" notification using Selenium in JavaScript

As I use Selenium to log in and send messages on a specific website, I am faced with a cookie popup that appears each time. Unfortunately, clicking the accept button to proceed seems to be quite challenging for me. Here is an image of the cookie popup Th ...

The art of selecting elements and attaching event listeners in a React environment

Currently, I am working on my portfolio website using Gatsby. The layout includes a sidebar on the left with navigational links (Home, About, Work, etc.), and the main content is displayed as one long strip of sections on the right. When a user clicks on a ...

Adding dynamically fetched JSON to an existing table

http://jsfiddle.net/mplungjan/LPGeV/ What could be improved in my approach to accessing the response data more elegantly? $.post('/echo/json/',{ "json": JSON.stringify({ "rows": [ { "cell1":"row 2 cell 1", "cel ...

Guide on displaying a document in react-doc-viewer from a protected API endpoint in either Next.Js or ReactJs

I am looking to display files in my Next.JS web application using a secure API. The API provides the following data: { "name": "Test1.docx", "contentUri": "https://api.mypurecloud.ie/api/v2/downloads/x ...

Is there a way to selectively load only the <head> content from AJAX data and update the current <head> element?

While attempting to retrieve the <head> content of data using AJAX and replace it with the current one, I am encountering errors and the code at the bottom is not functioning as expected. $('head').html($(data).find('head:first') ...

Implementing a custom arrow icon and adding functionality for closing on click in Kendo Multiselect

I'm looking to enhance the functionality of my Kendo Multiselect by giving it the appearance and behavior of a standard dropdown list. I'd like to include an arrow or triangle icon that toggles and closes the list when clicked. Can anyone provide ...

How can I show PHP retrieved data in separate text areas?

Struggling to retrieve values from the database? Simply select an employee ID using the 'selectpicker' and watch as the corresponding name and salary are displayed in the textarea. So far, I've managed to set up the following HTML Code: &l ...

Is there an easy method to verify if the local storage is devoid of any data?

Query is named aptly; seeking to verify in a conditional statement. ...

The mobile menu functions correctly on Jfiddle but is not functioning on the local server

I was working on a responsive mobile menu and used a toggleClass function to open the menu. It's functioning correctly in Jfiddle and below, but every time I click the nav icon in the live preview within brackets, nothing happens. I even tried it in a ...

The hunt is on for greater value within the index

My requirement is to check the text content of a box. If it matches any value stored in an ARRAY, then I have to execute a specific action. var ARRAY1 = ["Saab", "Volvo", "BMW"]; if (select[i].innerHTML.indexOf('ARRAY1') != -1){//code here} ...

managing associative array keys with special characters in php

Here is an example of my object. I am trying to access the object using an array, but I am unable to do so because there is a special character (@) as a prefix. Can anyone provide guidance on how to access the array in this scenario? SimpleXMLElement Ob ...

Exploring the potential of VSCode's RegEx search and replace

I am working on an Angular translation file and need to perform a search and replace operation in VScode for the translate key. The goal is to extract only the final key and use it in the replacement. The keys are structured with a maximum depth of 3 level ...

Stopping setTimeout when leaving the current page: Is it possible?

Good evening, I am looking for advice on how to cancel a setTimeout function when a user navigates to other pages (for example, by clicking other links or pressing the back button in the browser, but not by changing tabs). I have attempted to use the windo ...

JavaScript not displaying properly in Django application deployed on Heroku

Recently deployed a Django application on Heroku, and encountered an issue where the Javascript file hosted on Amazon S3 is not rendering on any page except for the home page. However, upon checking the Console in Inspect Element, it appears that everythin ...

Customize the behavior of jQuery cycle with an <a> tag

Can the jQuery cycle be accessed through a link in order to override the i variable? I've come across examples that can achieve this, but not in a scenario like this where the cycle() function is located within a variable: $(document).ready(function ...

I'm currently working on developing a chat system, but I'm facing an issue where I am unable to send multiple messages consecutively. It seems like there is a problem with the form

My chat application is not allowing me to post multiple messages. Here is the code snippet responsible for sending messages: window.typing = false; var posted = 0; var canPost = 1; var donotrefresh = 0; document.forms['send'].addEventListener(& ...