Easiest homemade variations and pairings

Imagine having a basic array like

["apple", "banana", "lemon", "mango"];
.

For example, if we were to find the straightforward hand-rolled combinations of this array, selecting 3 items, but allowing for repetition:

let array = ["apple", "banana", "lemon", "mango"];

for (let i = 0; i < array.length; i++)
  for (let j = 0; j < array.length; j++)
    for (let k = 0; k < array.length; k++)
      console.log(`${array[i]} ${array[j]} ${array[k]}`);

Similarly, creating permutations with no repetition from this array, choosing 3 elements:

let array = ["apple", "banana", "lemon", "mango"];

for (let i = 0; i < array.length - 2; i++)
  for (let j = i + 1; j < array.length - 1; j++)
    for (let k = j + 1; k < array.length; k++)
      console.log(`${array[i]} ${array[j]} ${array[k]}`);

Now the question arises: is there a similarly straightforward method to generate:

  • Permutations with no repetition
  • Combinations allowing for repetition

In essence, is there a simple, non-recursive or intricate iterative way, akin to the examples above, to produce these other two variations?

Answer №1

When dealing with combinations that involve repetition, it is as simple as adjusting the starting points of your loops to allow for repeating elements without restrictions. Instead of starting the second loop from i+1, start it from i, and similarly, begin the third loop from j instead of j+1.

Permutations, on the other hand, require a bit more attention, especially for small cases like the one you presented. You can explicitly check for repetitions within nested loops:

for (let i=0; i<n; i++) {
    for (let j=0; j<n; j++) {
       if (i !== j) {
           for (let k=0; k<n; k++) {
               if (i !== k && j !== k) {
                   ...
               }
           }
       }
    }
}

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 is the method for obtaining the socket object for individual users who are connected in Node.js?

I am currently using socket.io to send notifications to users. I have set up a listener that is monitoring for a specific event. myEvent.watch ((res,err)=> { if (!err) { let id = res.userID; let msg = res.msg; //to imple ...

The form post request cannot recognize the undefined variable

When attempting to send values through an HTML form and retrieve it in console.log, I encounter an error that says "TypeError: Cannot read property 'fName' of undefined," despite declaring it in the form name. signin.html : <!doctype html> ...

Retrieve the highest value from 4 different JSON source URLs

After retrieving values from a JSON URL, using the following code: $(document).ready(function () { function price(){ $.getJSON('https://poloniex.com/public?command=returnTicker', function(data){ document.getElementById('Polon ...

Injecting an attribute with the forbidden character "@" into the Document Object Model (DOM

Scenario I find myself needing to update some existing HTML using JavaScript, but I'm limited in that the server side is out of my control. This means that any changes must be made client-side only without altering the original HTML document. To acc ...

Combining multidimensional arrays in PHP

I have been pondering about how to merge two multidimensional arrays together. While I have come across similar solutions, they don't quite match what I am aiming for. Perhaps one of you could lend me a hand. Yes, I understand that the title is somewh ...

Retrieve error messages from API while utilizing Next-auth

Is it possible for Next-auth to handle API errors and pass them to the client-side? For example, our mobile app successfully handles API responses indicating incorrect email or password. However, on our website using Next-auth, we want to modify the retur ...

"Error: Unable to access the property '$emit' of an undefined value" - VueJS

I'm currently working on implementing a basic authentication system in vuejs. I have a set of objects containing valid usernames and passwords. I am looping through this list to validate the entered username and password. If there is a match, I trigge ...

Unexpected behavior encountered with JQueryUI modal functionality

Today marks my first experience with JqueryUI. I am attempting to display a conditional modal to notify the user. Within my ajax call, I have this code snippet: .done(function (result) { $('#reportData').append(result); ...

From the hue of mossy green to the fiery shade of ruby red,

I managed to create a simple green circle using THREE.Shape. Now, I am interested in changing the color of the circle so that it transitions from green in the middle to red at the border. Although I found an example on this website, I'm struggling t ...

Experiencing a problem with the localhost connection

I've been trying to work on this issue using React and local host, but it keeps showing the direct file instead of the website. I've been stuck on this problem for the past 3-4 hours and still haven't been able to find a solution. I'm h ...

Unable to capture user input text using $watch in AngularJS when applied on ng-if condition

I have developed a cross-platform application using AngularJS, Monaca, and OnsenUI. In my login view, I check if the user has previously logged in by querying a SQLite database. Depending on whether there is data in the database, I either display a welcom ...

Exception: Closing the database connection failed: db.close is not a callable

I have this Node.js application that utilizes MongoDb: const MongoClient = require('mongodb').MongoClient; const demoPerson = { name:'Jane', lastName:'Doe' }; const findKey = { name: 'Jane' }; MongoClient.connect( ...

Incorporate JavaScript to enable the transfer of text from one textarea to another upon clicking a button, while simultaneously clearing the original textarea

After working on the provided code, I have managed to create a functionality where text from one textarea is copied to another textarea when a button is clicked using JavaScript. <head> <script type="text/javascript"> function displayOut(){ ...

Retrieve specific information using the identifier from the URL parameters during server-side rendering

I am trying to fetch data with a parameter from the URL using Nextjs. However, I am facing an issue where the parameter value is undefined. Here is the code snippet: const Room = () => { let fetchData; let roomId; const getID = () => { con ...

Converting Xpath into a CSS selector

Having a difficult time converting the Xpath "//form[@id='giftcard-form']/div[3]/div/button" to CSS. I've tried using it for my Selenium JS but it's not working for some reason. Managed to convert an easier one successfully and use it i ...

Is there a way to improve the efficiency of this jQuery function that toggles the image source?

I have implemented a functionality that seems to work, but I'm unsure if it's the most efficient solution. I couldn't find a ready-made 'copy-paste' solution online, so I ended up writing this code myself. I am sticking with the &l ...

How to use node.js to add JSON data to a JSON file without using an array?

I'm trying to update a JSON file without using an array with FS. The desired format of the file should be: { "roll.705479898579337276.welcomemessage": "There is a welcome message here", "roll.726740361279438902.welcome ...

Exploring data elements using iteration in JavaScript

Here is some code that is functioning properly: Morris.Bar({ element: 'barchart', axes: true, data: [ json.bar.bar1 ], xkey: 'x', ykeys: ['y', 'z', ' ...

Tips for invoking the ajax pagination feature

Although I have successfully displayed the desired data based on the select box, my pagination feature seems to be malfunctioning. Why is that? The index.php display with broken pagination This snippet shows my ajax script for loading data and setting up ...

Convert the button element to an image

Can someone please explain how to dynamically change a button element into an image using javascript when it is clicked? For instance, changing a "Submit" button into an image of a check mark. ...