Explore the wonders of generating number permutations using JavaScript recursion!

After providing the input of 85 to this function, I noticed that it only returns 85. I am confused as to why it is not recursively calling itself again with 5 as the first number.

console.log(PermutationStep(85));

function PermutationStep(num) { 
  var permutations = [];

  recursive(String(num), String(num).length, [], '');
  return permutations;

  function recursive(num, numLength, used, currentPermutation) {
    console.log(currentPermutation);
    if (currentPermutation.length === numLength) {
      permutations.push(num);
    }
    for (var j=0; j<numLength; j++) {
      if (used[j]) continue;
      else {
        used[j]=true;
        recursive(num, numLength, used, currentPermutation+num[j]);
      }
    }
  }
}

Answer №1

  1. When the length is reached, remember to push currPerm rather than num.

  2. Ensure that used[j] is reset once it has been tracked.

  3. Be cautious of generating duplicate results, such as 885; always check for repetitions before proceeding.

console.log(PermutationStep(85));
console.log(PermutationStep(885));

function PermutationStep(num) { 
  var perms = [];
  
  // Convert number to char array.
  var str = ('' + num).split('');
  var length = str.length;
  // Sort in alphabetical order.
  str.sort(function(a, b) {
    return a - b;
  });

  // Create used map.
  var used = str.map(function() {
    return false;
  });

  rec(str, '');
  return perms;

  // Note that JavaScript can access values from outer function scope,
  // So there's no need to pass length and used each time, similar to how you handle perms.
  function rec(num, currPerm) {
    console.log(currPerm);
    if (currPerm.length === length) {
      // Insert the constructed string here, not num
      perms.push(currPerm);
    }
    var prev = null, ch;
    for (var j = 0; j < length; j++) {
      if (used[j]) {
        continue;
      }
      ch = str[j];
      if (prev === ch) { 
        // If the current character matches the previous one, meaning there are at least 2 characters in the string with the same value,
        // Skip to prevent redundant results.
        continue;
      }
      used[j] = true;
      rec(num, currPerm + ch);
      // Reset the usability of the number.
      used[j]=false;
      prev = ch;
    }
  }
}

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

Guide: Implementing Vuex store within a plugin

I recently developed a custom Vue plugin which includes a customized instance method import Echo from 'laravel-echo'; import Vue from 'vue'; import config from '@/config'; const echor = { install(Vue){ Vue.prototy ...

Click on each item within the v-for loop to gather relevant information, and subsequently iterate through the collected data

Within a v-for loop, I have implemented a button that, when clicked, retrieves specific data. The objective is to display this data below or in place of the clicked button. <div v-for="(item, index) in items" :key="index"> <button @click="fetch ...

Dealing with numerous promises simultaneously using AngularJS Factory

I have created a code that makes multiple $http calls recursively and saves all the promises it returns in an array. Then, I resolve all of them and save the responses in another array. Now, my question is: How can I efficiently return this final array to ...

I noticed that the node_modules folder has mysteriously vanished from my

When I tried running npm install in the terminal of VS Code. PS D:\work\backEnd> npm install npm WARN old lockfile npm WARN old lockfile The package-lock.json file was created with an older version of npm, npm WARN old lockfile so ...

Tips to successfully utilize addEventListener on a submit action

Having issues getting this to work on submit, it functions properly when using document.getElementById("gets").addEventListener("click", b_button); but does not work when I try document.getElementById("gets").addEventListener ...

Stop capturing mouse and keyboard events within a specific div element on all web browsers

I manage a website with forms that have jquery autosave features and are updated using ajax. These forms include various types of input elements such as textboxes, jQuery UI datepickers, and time pickers... <div id="content"> <form id="line1"&g ...

pretending to make an ajax call using jQuery

To enhance the user experience of file upload, I have implemented a fake ajax request. When the user clicks submit, the form disappears, a loading graphic appears, and after a few seconds, the page refreshes to display the newly uploaded image. However, e ...

The response body from the HTTP request is consistently empty or undefined

While working with two containers managed by Docker Compose, I encountered an issue where the response body from a GET call made by a Node.js service in one container to an API in another container using the request module was consistently empty or undefin ...

The ng-click method on the checkbox input field in AngularJS is not being triggered

I'm trying to trigger a function in a toggle switch using ng-click, but the customerActiveDeactive function isn't being executed. <a title="Active/ Deactivate" > <input type="checkbox" class="js-switch" ng-init="status=True" ng-model ...

Attempting to grasp the concept of memory leakage in a more thorough manner

As I dive into the world of frontend development and start learning Vue.js, I came across a paragraph in the tutorial that caught my attention: Vue.js makes rendering a template seem simple, but under the hood it does a lot of work. The data and DOM are ...

What is the reason for not storing information from MySQL?

Looking to extract data from a website using this JavaScript code. var i = 0 var oldValue = -1 var interval = setInterval(get, 3000); function get(){ var x= $($('.table-body')[1]).find('.h-col-1') if(i!=5){ if(oldValue != x){ old ...

Differences in outcomes have been observed between the elementLocated and findElements functions

Currently, I am in the process of developing Webdriver automation for a specific web application. As part of this process, I have created a test that seems to be functioning well most of the time but occasionally encounters an issue. it('verifies pre ...

Having trouble retrieving data from the table with AJAX and CodeIgniter

I am currently developing a comprehensive HRM+CRM system (Human Resource Management and Customer Relation Management). I have encountered an issue while trying to generate an invoice for each customer. I am struggling to resolve this problem and would appr ...

What is the best way to create a command that updates the status in Discord using discord.js?

I'm currently working on a command for my Discord bot using discord.js. The purpose of this command is to change the bot's status whenever an admin of the server triggers it. I've attempted to create the command, but unfortunately, it's ...

What to do while waiting for MySQL query in an asynchronous function?

Having an issue with my asynchronous function that queries the database using the mysql library. It seems like the function is not waiting for the query to complete before moving on. Here's the code snippet: async (eventName, eventArgs, app) => { ...

Customizing Angular 2's Webpack environment setup dynamically

Currently, I have set up Webpack to compile my Angular project. Within my project, there is an important file called env.js: module.exports.ENV = { API_URL: "http://localhost:5001/", ... }; In the webpack.common.js file, I am referencing this file l ...

"Transforming a static navbar to a fixed position causes the page to jump

Having some difficulty figuring this out. I'm working on a bootstrap navbar that transitions from static to fixed when the user scrolls past the logo at the top. Everything seems to be working fine, except for when the navbar reaches the top, it sudde ...

Why does the outcome of running this code vary each time?

I've been working on a code project to create 10 bouncing balls of different colors, but I'm encountering an issue where only one or two balls appear with different colors or the animation works perfectly only 1 out of 10 times. Any thoughts on w ...

unable to use ref to scroll to bottom

Can someone explain to me why the scroll to bottom feature using ref is not functioning properly in my code below? class myComponent extends Component { componentDidMount() { console.log('test') // it did triggered this.cont ...

A helpful guide on integrating a Google font into your Next.js project using Tailwind CSS locally

I'm planning to use the "Work Sans" Font available on Google Fonts for a website I'm working on. After downloading the "WorkSans-Black.ttf" file, I created a subfolder named "fonts" within the "public" folder and placed the font file in there. Be ...