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

What could be causing my router UI in angular.js to malfunction?

Having an issue with routing not functioning as intended, here is the relevant code: $urlRouterProvider. otherwise('/list'); $stateProvider. state('home', { abstract: true, views: { 'header': { templateUrl: &apos ...

How come the font size and div elements combine when I drag and drop the items?

Recently, I decided to create my own drag and drop game. The game is almost complete, but there's one issue. When I try to drop the items into the designated "Drop Items Here" area, their style changes abruptly to mimic the text. For example: Additi ...

Converting a string to a number is not functioning as expected

I am facing a problem with an input shown below. The issue arises when trying to convert the budget numeric property into thousands separators (for example, 1,000). <ion-input [ngModel]="project.budget | thousandsSeparatorPipe" (ngModelChange)="projec ...

"Effortlessly Engage Users with Rails and AJAX Comment Posting

Running a simple blog app dedicated to video game reviews, I encountered an issue with AJAX. As a self-taught student developer, I'm facing a challenge where posting comments on review pages triggers a full page refresh instead of dynamically updating ...

Tips for using NodeJS with a MySQL database

Hello everyone, I'm new to this community so please bear with me if my question seems too simplistic. I've been tasked with a basic web project for one of my courses and will be using NodeJS+MySQL along with VS Code which has caught my eye. Howe ...

Customize a div's background color with an Angular directive

Imagine having a div element: <div id="wrapper"> some text </div> How can you create an angular directive that changes the background based on user input? For instance, you might have tried: <div id="wrapper" color temperature="51"> ...

React is unable to identify the prop `controlID` when used on a DOM element in React-Bootstrap Forms

While constructing a form with React components sourced from react-bootstrap, and taking guidance directly from an example provided in its documentation: <Form.Group controlId="formBasicEmail"> <Form.Label>Email address</Form.Label> ...

What are the steps to create custom Typescript RecursiveOmit and RecursivePick declarations for efficient cloning routines?

For some time now, I have been attempting to create a declaration for RecursiveOmit and RecursivePick in cloning methods such as JSON.parse(JSON.stringify(obj, ['myProperty'])) type RecursiveKey<T> = T extends object ? keyof T | RecursiveKe ...

Nuxt.js transition issue: How to fix transitions not working

LOGIC: The pages/account.vue file consists of two child components, components/beforeLogin and components/afterLogin. The inclusion of child components is based on a conditional check within pages/account.vue using a string result ('x') stored in ...

Alternative method for handling web requests in case JavaScript is not enabled

Issue: i) I am developing a JSF2 application and need to implement a tab control on a page. When a user clicks on a tab, the content for the panel below should be loaded from an xhtml file on the server using an ajax call. ii) I want this functionality ...

Animated CSS Checkmark Design

How can I create an animated Check-mark using CSS with SVG animation? I attempted the following code but it doesn't seem to be working. Any suggestions? DEMO: https://jsfiddle.net/b7Ln0jns/ CSS: @import "bourbon"; $color--green: #7ac142; $curve: c ...

Is it possible to establish role-based access permissions once logged in using Angular 6?

Upon logging in, the system should verify the admin type and redirect them to a specific component. For example, an HOD should access the admi dashboard, CICT should access admin2 dashboard, etc. Below is my mongoose schema: const mongoose = require(&apo ...

The functionality of angular-ui's ui-utils and ui-scroll module is currently nonfunctional in version 0.1.0

I have been trying to implement the features from this Angular UI library: http://angular-ui.github.io/ui-utils/, particularly focusing on this aspect: https://github.com/angular-ui/ui-utils/blob/master/modules/scroll/README.md Unfortunately, despite my e ...

Optimizing HTML and Script loading sequences for efficient execution

I have a query regarding the loading order of scripts in web browsers. I am interested in knowing the most efficient way to redirect users to a mobile website on the client side. For example, if I place a mobile detection script within the <head> se ...

Use React to insert a leading zero next to a number in the input field if the number is greater than 10

I have scoured the web and consulted resources like this one but haven't found a solution that addresses my specific issue with adding padding to input numbers. My goal is to automatically add a leading zero whenever the number inside an input field i ...

inSession variable in express: set to false

i keep receiving inSession:false when attempting to log in, it is expected to return true. I am utilizing express session, in combination with postges and sequalize. I have logged the state values and they are being rendered correctly, so they are n ...

What is the process of memory allocation for variables in Javascript?

Can you explain to me how local variables are allocated memory in JavaScript? In languages like C and C++, local variables are typically stored on the stack. Is this also the case with JavaScript, or are all variables stored in the heap? ...

How to selectively load specific scripts in index.html with the use of angular.js

Let me address a problem I'm facing with a large development project. It seems that the current setup does not function properly on Internet Explorer. My idea is to only load files that are compatible and do not generate errors when accessed through I ...

Utilize Angular 8 to dynamically populate Input values with data pulled from an API

I need help with setting the input value dynamically using data from my API. Once I click send, I want it to be saved in the database. However, I am struggling to dynamically populate the input field. Can someone guide me on the right approach to achieve t ...

"Adjusting the position of series data container in Highcharts JS to optimize

Currently, I am utilizing highcharts along with highcharts-ng. My goal is to adjust the position of the container for series Data (where the number 80 is displayed below) slightly higher as it is currently overlapping with the numbers 200 and -200 in the t ...