How to make Kadanes Algorithm visualizer using HTML CSS & Javascript ?
Last Updated :
13 Mar, 2024
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=
"https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap"
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:
Â
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Introduction of Firewall in Computer Network A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa
10 min read