Open In App

How to make Kadanes Algorithm visualizer using HTML CSS & Javascript ?

Last Updated : 13 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to make a Kadanes Algorithm visualizer using HTML, CSS & Javascript.

Approach: 

Kadanes algorithm is used to calculate the largest sum in a contiguous subarray. We are basically gonna use the algorithm as same and we are gonna use JavaScript and CSS to show the visualization. When we are iterating over the array and we are gonna show it with a cyan color border and cyan font color and we show the current sum and maximum sum. To know more about kadanes algorithm refer to https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/

The simple idea of Kadane’s algorithm is to look for all positive contiguous segments of the array. And keep track of the maximum sum of contiguous segments among all positive segments. Each time we get a positive sum compare it with the maximum sum so far and update the maximum sum if it is greater than the previous. 

Step 1: In this step, we will first create the structure of the webpage using HTML. We made a header with an id of the header and inside of id we made a span element so that we can style it like a nice glowing text and header id won’t be glowing it will look good we made a container that will have the current sum of the array and then max sum as their children div then we have start button which when clicked shows you how kadanes algorithm works now let’s talk about CSS.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" 
          content="IE=edge">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <link href=
          rel="stylesheet" />
    <script src="script.js"></script>
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
  
<body>
    <div class="header">
          <span id="span">
              Kadanes
          </span
              Algorithm
     </div>
    <div id="container"></div>
    <div class="container_2">
        <div id="currentsum"></div>
        <div id="answer"></div>
        <!-- <input id="input" type="text" 
        placeholder="Enter the Array"> -->
        <!-- <div id="push">Push</div> -->
        <div id="start">Start</div>
    </div>
</body>
  
</html>


Step 2: We will have black background so we give the text color as white to every element so that it shows and then for the span we have to make it glow so we give a text-shadow we set our HTML background color and font family now for the body we make sure everything remains center and set flex-direction as a center and for container also we give it some position same goes for the container we give it a letter spacing so that it looks neat we make a tile and make sure every element displayed is with tile for symmetric we set onhover and change color to cyan then we style every element normally.

CSS




* {
    color: white;
}
  
#span {
    font-weight: normal;
    text-shadow: 0 0 10px cyan,
        0 0 40px cyan,
        0 0 80px cyan;
}
  
html {
    background-color: black;
    font-family: "Open sans", sans-serif;
}
  
body {
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 100vmin;
}
  
.container_2 {
    display: flex;
    flex-direction: column;
}
  
#container {
    width: 100%;
    margin-top: 15%;
    display: flex;
    justify-content: center;
    flex-direction: row;
    font-size: 5vmin;
    letter-spacing: 2vmin;
    font-weight: normal;
}
  
.tile {
    /* width: 5vmin; */
    height: 5vmin;
    margin: 10px;
    text-align: center;
    height: fit-content;
}
  
.onover {
    color: cyan;
}
  
#answer {
    font-size: 5vmin;
}
  
#start {
    align-self: center;
    background-color: black;
    font-size: 3vmin;
    box-sizing: border-box;
    padding: 1vmin;
    color: white;
    cursor: pointer;
    border: none;
    margin-top: 2vmin;
    transition: 0.5s ease-in-out;
    font-weight: bold;
    letter-spacing: 4px;
}
  
#start:hover {
    transform: scale(1.5);
    text-shadow: 0 0 10px cyan,
        0 0 20px cyan,
        0 0 40px cyan;
}
  
#array {
    display: flex;
    font-size: 10vmin;
}
  
#currentsum,
#answer {
    padding: 1vmin;
    font-size: 3vmin;
    letter-spacing: 2px;
}
  
.header {
    text-align: center;
    padding: 1vmin;
    width: 100%;
    font-size: 6vmin;
    letter-spacing: 2px;
    border-bottom: 1px solid white;
}
  
input {
    margin-top: 2vmin;
}


Step 3: Now script.js will contain its main logic of it. We made a function that returns an id. We made an array with negative and fewer elements so that viewer can understand and then we made a current sum and max sum we made a function current sum we ran a loop on our array we made a  promise with settimeout that runs a callback resolves after some time so it stops code for passed delay time which is for now 1 second and we stopped code for 1 second every time I change and then we add array[i] to current sum then we display the current sum.

Javascript




function id(id) {
    return document.getElementById(id);
}
var array = [5, 4, 6, -3, 4, -1];
var maxsumcontainer = [];
let curr_sum = 0; let max_sum = 0;
const kadanes = async (array, arrayLength) => {
    console.log("inside");
    for (let i = 0; i < arrayLength; i++) {
        await new Promise((resolve) =>
            setTimeout(() => {
                resolve();
            }, 1000)
        )
        curr_sum = curr_sum + array[i];
        id("currentsum").innerText = `Current Sum : ${curr_sum}`
        maxsumcontainer[i] = i;
        id(i).style.color = "cyan";
        // id(i).style.textAlign="center"
        id(i).style.border = "2px solid cyan"
        if (curr_sum > max_sum) {
            max_sum = curr_sum;
            id("answer").innerText = `Maximum Sum : ${max_sum}`;
        }
        if (curr_sum < 0) {
            curr_sum = 0
        }
    }
    // id("container").style.textShadow="0 0 10px cyan
    //,0 0 40px cyan, 0 0 80px cyan;"
    id("container").style.color = "red";
    id("container").innerText = "Ended"
    id("answer").innerText = `Maximum Sum : ${max_sum}`;
}
window.onload = () => {
    id("start").addEventListener('click', () => {
        id("start").style.display = "none";
        // id("input").style.display="none"
        console.log(array);
        let idcount = 0;
        for (let i = 0; i < array.length; i++) {
            let tile = document.createElement('span');
            tile.id = idcount;
            tile.classList.add("tile");
            tile.innerText = array[i];
            // tile.style.margin="2px";
            // tile.style.padding="1vmin"
            id("container").appendChild(tile);
            idcount++;
        }
        kadanes(array, array.length);
    })
  
}


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads