How to make Moore's Voting Algorithm Visualizer using HTML CSS & JavaScript ?
Last Updated :
22 Jul, 2024
This article will show how to make Moore's Voting Algorithm visualizer using HTML, CSS & JavaScript. This algorithm is used for an element that repeats more than n/2 times n is the size of the array for this element that has to repeat continuously so that is the key approach for this algorithm
Approach: We will use the same algorithm but we will be taking input of text and pattern and then we will be computing an LPS array and then we will compare text and pattern. The main intuition behind this algorithm is if an element is repeating then it will repeat N/2 times that it must have occurrences that will be left at the reference element at the end when iterated over the array. Now after that, we start traversing the array by adding a CSS title class to every element to the container while traversing the array and then we apply the Moores voting algorithm logic if you don't know the logic about the algorithm please read the following article https://www.geeksforgeeks.org/boyer-moore-majority-voting-algorithm/. The idea of the article is basically if in an array there are elements that repeat more than n/2 times where n is the size of the array then the element needs to be consecutive once in that particular array to come n/2 times
Step 1: Lets create the basic structure of the webpage using HTML.
index.html
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">Moores
</span>Voting Algorithm
</div>
<div id="container"></div>
<div class="container_2">
<div id="votes"></div>
<div id="candidate"></div>
<div id="count"></div>
<div id="message"></div>
<div id="start">Start</div>
</div>
</body>
</html>
Step 2: Now in the style.css file we will style the structure of the webpage.
style.css
CSS
* {
color: white;
}
#span {
font-weight: normal;
text-shadow: 0 0 10px cyan, 0 0 40px cyan, 0 0 80px cyan;
letter-spacing: 2px;
}
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;
align-items: center;
}
#container {
width: 100%;
margin-top: 15%;
display: flex;
justify-content: center;
flex-direction: row;
font-size: 5vmin;
letter-spacing: 2vmin;
font-weight: normal;
}
.tile {
display: flex;
align-items: center;
justify-content: center;
margin: 10px;
padding: 1vmin;
padding-left: 2vmin;
border: 2px solid black;
}
.onover {
color: cyan;
}
#candidate,
#count {
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;
}
#votes,
#candidate,
#count {
display: flex;
justify-content: center;
align-items: center;
padding: 1vmin;
font-size: 3vmin;
letter-spacing: 2px;
transition: all 0.5s ease-in-out;
}
#votes:hover,
#candidate:hover,
#count:hover {
transform: scale3d(1.5);
}
.header {
text-align: center;
padding: 1vmin;
width: 100%;
font-size: 6vmin;
letter-spacing: 2px;
border-bottom: 1px solid white;
}
input {
margin-top: 2vmin;
}
#message {
width: 50%;
height: 7vmin;
margin: 3vmin;
font-size: 5vmin;
display: flex;
align-items: center;
justify-content: center;
color: cyan;
font-size: 2vmin;
}
.cyans {
color: cyan;
border: 2px solid cyan;
transition: all 0.5s ease-in-out;
}
.greenyellow {
color: greenyellow;
border: 2px solid greenyellow;
transition: all 0.5s ease-in-out;
}
.normal {
color: white;
border: 2px solid black;
}
Step 3: Now we will see the code of the JS file for all the logic of the algorithm. We made an array when the window loads when the start is clicked we display an array we make it asynchronous so that when the message displays we make it wait for 7000 milliseconds so that people can see it we then make display none and then we append elements to the container using tile class now we have moores voting algorithm function which will find the majority element now we first show the initialized element and then we used async/await and promises to wait for it for the time and then we iterate it for iteration we use green, yellow border color and same font color and then if the number is present we use cyan color for border color and font color if numbers are equal to the candidate and we display votes and candidate continuously and we would display a message in message div if it is important that the only thing we do javascript file but to understand it we must have a brief knowledge of the algorithm.
script.js
JavaScript
function id(id) {
return document.getElementById(id);
}
var array = [1, 1, 2, 3, 1, 5, 1];
window.onload = () => {
id("start").addEventListener('click', async () => {
id("start").style.display = "none";
id("message").innerText = "Main intuition behind this algorithm is "
+ "if a element is repeating than it will repeat N / 2 times "
+ "that it must have occurrences which will be left at the "
+ "reference element at the end when iterated over the array "
+ "How let us see!"
await new Promise((resolve) =>
setTimeout(() => {
resolve();
}, 7000)
)
id("start").style.display = "none";
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];
id("container").appendChild(tile);
idcount++;
MooresVoting(array, array.length);
}
})
}
const MooresVoting = async (array, size) => {
// console.log("inside function")
var count = 0;
var candidate = -1;
var votes = 0;
id("message").innerText = "Watching the initializer elements first";
await new Promise((resolve) =>
setTimeout(() => {
resolve();
}, 2000)
)
id("votes").innerText = `Votes is ${votes}`;
id("candidate").innerText = `Present Candidate
is at index ${candidate}`;
// id("count").innerText = `Count is ${count}`;
await new Promise((resolve) =>
setTimeout(() => {
resolve();
}, 3000)
)
id("message").innerText = `iterating over the array now`
id("message").innerText = "Main intuition behind this algorithm "
+ "is if a element is repeating than it will repeat N / 2 "
+ "times that it must have occurrences which will be left at "
+ "the reference element at the end when iterated over the "
+ "array How let us see!"
await new Promise((resolve) =>
setTimeout(() => {
resolve();
}, 3000)
)
id("message").innerText = "";
for (let i = 0; i < size; i++) {
id(i).classList.add("greenyellow")
// id(i).style.color="greenyellow";
if (votes == 0) {
id("votes").style.color = "Red";
await new Promise((resolve) =>
setTimeout(() => {
resolve();
}, 3000)
)
id("votes").style.color = "white";
// id("candidate").style.color="cyan";
id("candidate").classList.add("cyan");
id("votes").classList.add("cyan");
// id("votes").style.color="cyan";
await new Promise((resolve) =>
setTimeout(() => {
resolve();
}, 2000)
)
candidate = i;
votes = 1;
id("candidate").innerText = `Present Candidate is
at index ${candidate}`;
id("votes").innerText = `Votes is ${votes}`;
await new Promise((resolve) =>
setTimeout(() => {
resolve();
}, 3000)
)
// id("candidate").style.color="white";
// id("votes").style.color="white";
id("candidate").classList.remove("cyan");
id("votes").classList.remove("cyan");
} else {
// console.log("inside else");
// console.log(`${i} ${candidate}`);
console.log(`inside else ${array[i]} and
cand ${candidate}`);
if (array[i] == array[candidate]) {
console.log("inside array[i]==candidate");
id(i).style.borderColor = "cyan";
id(i).style.color = "cyan";
id(candidate).style.borderColor = "cyan";
id(candidate).style.color = "cyan"
id("votes").style.color = "cyan";
await new Promise((resolve) => {
setTimeout(() => {
resolve();
}, 2000);
})
votes++;
id("votes").innerText = `Votes is ${votes}`;
await new Promise((resolve) => {
setTimeout(() => {
resolve();
}, 3000);
})
id("votes").style.color = "white";
id(i).style.borderColor = "black";
id(candidate).style.color = "white"
id(candidate).style.borderColor = "black";
}
else {
id("votes").style.color = "cyan";
await new Promise((resolve) => {
setTimeout(() => {
resolve();
}, 3000);
})
votes--;
id("votes").innerText = `Votes is ${votes}`
await new Promise((resolve) => {
setTimeout(() => {
resolve();
}, 2000);
})
id("votes").style.color = "white";
}
}
id(i).style.color = "white";
id(i).style.borderColor = "black"
}
id("message").innerText = `Now we gonna check element we
found was actually occurring more than N/2 times
and that candidate is ${candidate}`;
await new Promise((resolve) => {
setTimeout(() => {
resolve();
}, 3000);
})
id("message").innerText = "";
id("votes").innerText = "";
id("candidate").innerText = "";
for (let i = 0; i < size; i++) {
id(i).style.borderColor = "greenyellow";
id(i).style.color = "greenyellow";
await new Promise((resolve) => {
setTimeout(() => {
resolve();
}, 3000);
})
// console.log(`array of candidate ${array[candidate]} and ${ array[i] } `);
if (array[i] == array[candidate]) {
id("count").style.color = "cyan";
await new Promise((resolve) => {
setTimeout(() => {
resolve();
}, 3000);
})
count++;
id("count").innerText = `Count is now ${count} `
id("count").style.color = "white";
}
id(i).style.color = "white";
id(i).style.borderColor = "black"
}
await new Promise((resolve) => {
setTimeout(() => {
resolve();
}, 3000);
})
// console.log(`count is ${ count } and size is ${ size / 2 } `);
if (count > size / 2) {
id("message").innerText = `Found the Majority element
which is ${array[candidate]} `;
} else {
id("message").innerText = `Didn't found the
Majority Element`;
}
}
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