Building a webpage that helps users solve combination problems

avatar
(Edited)

In my last post, I worked on a function that helps a user determine the possible number of combinations we can get from a number of available options using a provided mathematical formula.

n!/r!(n−r)! = (n r)

Combination formula

Source

In case you'd like to check that out you can do that here.

This post is basically an extension of the last one so you might wanna check that out.

In this post we will be building a webpage that not only displays the number of possible combination but displays the actual possible combination themselves.

For example there are three possible combinations that can be derived from a combination of 3 and 2 where 3 is the number of available options to select from and 2 number of selections needed.

Our page is basically going to take two numbers through two text inputs and return the total number of possible combinations and all the combinations as well.

This tutorial is beginner friendly so anyone with a basic knowledge of how to run HTML and JavaScript on a webpage will be able to do this.

First we want to create a folder for our project and in that folder create a HTML file.

You could name the folder and the file anything you want. It doesn't matter as long as you are able to run HTML.

I will name my file combination.html.

In the file I will be using bootstrap for styling so our starter code should look like

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Mathematical combination tool</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    <script>
        function getAllCombinations (a, b) {
            function factorial(n){
              let answer = 1;
              if (n == 0 || n == 1){
                return answer;
              }else{
                for(var i = n; i >= 1; i--){
                  answer = answer * i;
                }
                return answer;
              }  
            }

            const upper = factorial(a)
            const lower = factorial(b) * factorial(a - b)
            return upper/lower
        }
    </script>
</body>
</html>

In case you are wondering where the getAllCombinations() function came from, you can check out my last post for an explanation, I left the link in the beginning of this post.

Now, we need to add the text inputs and a button that call the function which runs our operation for us.

In the <body> tag(just like every other HTML page) above the <script> tag add the following code.

<div class="container comb-form" style="margin: 5%;">
        
        <div class="input-group mb-3">
          <input type="number" class="form-control" placeholder="Total number of available options" id="availableOptions">
        </div>

        <div class="input-group mb-3">
          <input type="number" class="form-control" placeholder="Total number of selections needed" id="selectionsNeeded">
        </div>

        <div class="btn-area">
            <a href="javascript:void(0)" class="btn btn-primary" id="runCombinationOp">Get Combinations</a>
        </div>
</div>

If you save the page and load it, you should see something along this line

ipfs.png

We already have a function to call for getting total number of possible combinations(not the combinations themselves).

All we have to do now is have a function for listing out all the combinations and also displaying the total number of possible combinations.

Replce the function getAllCombinations with the following code

class Combinations {
          constructor (n, k) {
            this.n = n
            this.k = k
            this.current = [] // will be used for storing current combination
            this.combinations = []
          }

          findCombinations (high = this.n, total = this.k, low = 1) {
            if (total === 0) {
              this.combinations.push([...this.current])
              return this.combinations
            }
            for (let i = low; i <= high; i++) {
              this.current.push(i)
              this.findCombinations(high, total - 1, i + 1)
              this.current.pop()
            }
            return this.combinations
          }
        }


        function getAllCombinations (a, b) {
            function factorial(n){
              let answer = 1;
              if (n == 0 || n == 1){
                return answer;
              }else{
                for(var i = n; i >= 1; i--){
                  answer = answer * i;
                }
                return answer;
              }  
            }

            const upper = factorial(a)
            const lower = factorial(b) * factorial(a - b)
            console.log(upper/lower)
        }

In our code you can see we created a new class Combinations

The Combinations class was sourced from this repo on Github

What it does is it basically takes two numbers and returns all possible combinations of that number starting from 1.

So a combination of 3 and 2 for that number would return

ipfs.png

While a combination of 4 and 2 for that number would return

screenshot_2022_01_27_235412.png

Now we will create a new function outputCombinations which will be responsible for running the class Combinations and the function getAllCombinations , processing the returned data then displaying it.

Directly below the function getAllCombinations, add the following code

function outputCombinations (j, k) {
            if ($('#comb-data')) {
                $('#comb-data').remove()
            }
            $('#runCombinationOp').text('Loading...')
            const combinationsInit = new Combinations(j, k)
            const combinationsList = combinationsInit.findCombinations()
            const possibleCombinationsNumber =  getAllCombinations(j, k)
            let combinationsListHtml = ``
            combinationsList.forEach(c => {
                let oneCombination = ``
                c.forEach(t => {
                    oneCombination += t + ' '
                })
                combinationsListHtml += `
  • ${oneCombination}
  • ` }) $('.comb-data').html( `

    The total number of possible combinations between ${j} and ${k} is ${possibleCombinationsNumber}

                <div class="container" style="margin: 5%;">
                    <h5>List of all possible unique combinations</h5>
                    <ul class="list-group">
                        ${combinationsListHtml}
                    </ul>
                </div>`
            )
    
            $('#runCombinationOp').text('Get Combinations')
        }
    
        $('#runCombinationOp').click(function () {
            const availableOptions = $('#availableOptions').val()
            const selectionsNeeded = $('#selectionsNeeded').val()
        
            outputCombinations(availableOptions, selectionsNeeded)
        })
    

    What this code does is that whenever the button Get Combinations is clicked, the values of the parameters for the operation is gotten from the text inputs and when that is done the data gotten is passed to an instance of the Combinations class followed by the calling of the findCombinations() method in the class and finally the getAllCombinations function is called.

    The data gotten from calling the functions is then processed and passed into HTML elements which are then displayed.

    If you save your file, reload the page and run the code you should get a result similar to the ones below

    screenshot_2021_12_06_111921.png

    screenshot_2021_12_06_111921.png

    If you would like to try out the webpage live, you can find it here

    https://getcombinations.surge.sh/combination.html

    I hope you enjoyed this post half as much as I enjoyed writing it. Got any ideas on something cool that you feel would be a nice addition to our tool? Kindly share in the comments. Till next time bye.



    0
    0
    0.000
    3 comments
    avatar

    Congratulations @gotgame! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s):

    You distributed more than 110000 upvotes.
    Your next target is to reach 115000 upvotes.

    You can view your badges on your board and compare yourself to others in the Ranking
    If you no longer want to receive notifications, reply to this comment with the word STOP

    Check out the last post from @hivebuzz:

    Hive Power Up Month - Feedback from day 25
    Support the HiveBuzz project. Vote for our proposal!
    0
    0
    0.000