What is the best way to display the output of a given input along with all its possible permutations?

Can anyone help me with showing all permutations of a value entered into an input field, with a maximum length of 5 characters?

I tried creating a Codepen example for this, but it's not working as expected.

Check out my Codepen here

This is the script I used:

<script>
     function permute(a) {
     if (a.length < 5) return [a];
     var c, d, b = [];
     for (c = 0; c < a.length; c++) {
      var e = a.splice(c, 1),
        f = permute(a);
      for (d = 0; d < f.length; d++) b.push([e].concat(f[d]));
      a.splice(c, 0, e[0])
      }
     return b

    }

   function permuteval() {
   var txtval = document.getElementById('permute_this').value;
   document.getElementById('results').innerHTML = 
   (permute([txtval]).join("\n"));

    }
</script>

Any assistance would be greatly appreciated. Thank you!

Answer №1

One approach you can try is utilizing a spread operator:

document.getElementById('results').innerHTML = (permute([...txtval]).join("\n"));

If this doesn't give you the desired output, it might need some tweaking.

Check out this link for more information

An alternative code snippet for permutations that I find useful is:

const permutations = arr => {
  if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
  return arr.reduce(
    (acc, item, i) =>
      acc.concat(
        permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val])
      ),
    []
  );
};
EXAMPLES
permutations([1, 33, 5]); // [ [ 1, 33, 5 ], [ 1, 5, 33 ], [ 33, 1, 5 ], [ 33, 5, 1 ], [ 5, 1, 33 ], [ 5, 33, 1 ] ]

Visit this site for more coding resources

Answer №2

By updating the innerHTML, you can incorporate new content.

let textValue = document.getElementById('permute_this').value + '<br>';    
document.getElementById('results').innerHTML += 
   (permute([textValue]));

This method should work effectively. Avoid using Array.prototype.join() and note that \n will not function the same in HTML.

Furthermore, this approach may seem overly complicated for displaying content. Consider a simpler solution like parsing the raw input instead.

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

Assistance needed with connecting MongoDB to Raspberry Pi

As I dive into the world of web development, I've been following Colt Steele's course on Udemy. The class is going smoothly, and I'm working on building my own website on the side that I want to host on a Raspberry Pi 4 (I have both the 32-b ...

Closing a live search box by tapping away from it

The link I found as the best example for this topic is: http://www.example.com In the example provided, if you enter a keyword in the search field, suggestions will drop down. I have implemented this code but would like to make a slight modification. I w ...

Retrieving a Date object from a JSON response

Hey there, I have a situation where I'm trying to convert a JSON response into a date object in order to display it in a different format. Here's the JSON response I'm working with: responseData: [{"id":10,"createdDate":"1 Sep, 2014 12:48:5 ...

Error: cannot assign 'int*' to 'int [0]', the types are incompatible and will not compile

Here's the code I'm working with: #include "../include/Enemy.h" Enemy::Enemy(int X[], int Y[], int Type ) { x=X; y=Y; type=Type; } Enemy::~Enemy() { //dtor } Header File: #ifndef ENEMY_H #define ENEMY_H class Enemy { p ...

When using the map function in NodeJS, it may result in an empty array being

I attempted to get results from a mssql database using the mssql npm package and store them in an array. However, I'm facing an issue where the response seems to return an empty array outside of the map function. Any assistance on this matter would be ...

Observing a global object's attribute in Angular JS

Imagine you have an object in the global scope (yes, I know it's not ideal but just for demonstration purposes) and you wish to monitor a property of that object using Angular JS. var person = { name: 'John Doe' }; var app = angular.mod ...

Ensure the latest item is stored in the browser's local storage

I'm currently working on developing a flipbook-type application using HTML canvas in React. One issue I've encountered is that when I save an object (drawing) from the canvas to local storage, it saves not only the current project but also the pr ...

Angular - Clear the selection of <select><option> if I opt out of accepting the change

I have created a dropdown menu using HTML <select> and <option> tags, along with a JavaScript function that triggers a confirmation dialogue when an option is selected. The confirmation offers a simple choice between "yes" or "no." If the user ...

Customize each Picker.Item element in React Native with unique styles

How can I style individual Picker.Items beyond just changing the text color? Additionally, what other props can be used for a Picker.Item? I am aware of "key", "value", "label", and "color". Are there any additional props available? I want to customize o ...

Iterate through each image within a specific div element and showcase the images with a blur effect applied

I have a div with multiple images like this: <div class="am-container" id="am-container"> <a href="#"><img src="images/1.jpg"></img></a> <a href="#"><img src="images/2.jpg"></img>< ...

Tips for triggering onclick before changing to a new page?

Currently, I am developing a React application and have encountered the following situation: <a href={link} variant="primary" onClick={this.onClickDoSomething}> here. </a> My goal is for the onClick event to trig ...

enabling input field while making asynchronous requests with jQuery

This is the code snippet from my index.php file: <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="ajax.js"></script> <script> $("input" ...

There appears to be a JavaScript validation error occurring on the current page, however, you are able

For my datepicker, I want an error message to display if the user selects a date more than 5 years in the future, saying "You are ineligible for our program". The user should not be able to proceed to the next step unless this error message is ad ...

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 ...

When node.js v6.11.2 is installed on Windows 7, it does not include the correct npm version

When trying to install node.js v6.11.2 on my Windows 7 computer, I am encountering an issue where it is installing the incorrect version of npm alongside it. Even after downloading the installer directly from node.js' website which claims that 6.11.2 ...

Pressing the Like Button triggers the transfer of a specific variable from PHP to jQuery

I have a piece of PHP code that I am using to display all users' posts, each with its own unique 'like' button: $sql = "SELECT * FROM posts"; $result = mysqli_query($con,$sql); while($row=mysqli_fetch_assoc($result)){ $post_content = $ro ...

Easily use Discord.JS 13 slash commands to generate an embed displaying a user's specific role within a server

Currently, I am in the process of creating a slash command that will reveal a user's specific roles when the command is triggered. run: async (client, interaction) => { try{ const { member, channelId, guildId, applicationId, comman ...

Is there a way to postpone the execution of a scheduled interval function?

Below is the setup of my function: setInterval(function () { get_fb(); }, 10000); If a user interacts with an element, such as hovering over it or clicking on it, I want to reset the timer back to 10 seconds. How can I instruct the program to achieve th ...

Convert a boolean value to a string using filter in AngularJS

I am working on an AngularJS app and need to create a filter. In my database, I have a string value that indicates whether the data is active or inactive. I use 'S' for active and 'N' for inactive. I added a checkbox button on my page t ...

Creating immersive visualizations using Three.js and WebGL, as well as leveraging 2D canvas for rendering graphics, involves passing the getImageData

Recently diving into WebGL (and 3D graphics in general) using three.js, I'm looking to create multiple textures from a 2D canvas for rendering various meshes, each with its own unique texture. Simply passing the canvas to a new THREE.Texture() causes ...