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:
How to make Moore's Voting Algorithm Visualizer using HTML CSS & JavaScript ?
Similar Reads
How to make KMP Algorithm visualizer using HTML,CSS & JavaScript ? The KMP matching algorithm uses degenerating property (pattern having the same sub-patterns appearing more than once in the pattern) of the pattern and improves the worst-case complexity to O(n). The basic idea behind KMPâs algorithm is: whenever we detect a mismatch (after some matches), we already
11 min read
How to make Kadanes Algorithm visualizer using HTML CSS & Javascript ? 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 v
5 min read
Create a Stack Visualizer using HTML CSS and Javascript In this article, we will see how to create a stack visualizer using HTML, CSS & Javascript, along with understanding its implementation through the illustration.Stack is a well-known linear data structure that may follow the order LIFO(Last In First Out) or FILO(First In Last Out). There are man
9 min read
Brick Sort Visualization using JavaScript This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phases. In the odd phase, we perform a bubble sort on odd-indexed elements, and in the even phase, we perform a bubble sort on even-indexed elements.To know more about it. Please refer to Brick Sort
5 min read
Gnome Sort Visualizer using JavaScript In this article, we are going to learn Gnome sort Visualizer using javascript, Gnome Sort also called Stupid sort, is based on the concept of a Garden Gnome sorting his flower pots. In order to know more about it. Please refer to Gnome Sort.An algorithm like Gnome Sort can be easily understood by vi
4 min read
Comb Sort Visualizer using JavaScript Comb Sort is mainly an improvement over Bubble Sort. Comb Sort improves on Bubble Sort by using a gap of the size of more than 1. In order to know more about it. Please refer to Comb Sort. An algorithm like Comb Sort can be easily understood by visualizing instead of long codes. In this article, Com
5 min read