Open In App

How to make Moore’s Voting Algorithm Visualizer using HTML CSS & JavaScript ?

Last Updated : 24 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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=
          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:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads