0% found this document useful (0 votes)
73 views81 pages

Jayawant Institute of Management & Studies Laboratory Workbo o K

The document describes a program to implement a stack using an array in JavaScript. The stack class contains methods like push(), pop(), peek(), isEmpty(), size() etc. to add and remove elements from the stack. The program demonstrates pushing and popping elements onto and from the stack and printing the stack elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views81 pages

Jayawant Institute of Management & Studies Laboratory Workbo o K

The document describes a program to implement a stack using an array in JavaScript. The stack class contains methods like push(), pop(), peek(), isEmpty(), size() etc. to add and remove elements from the stack. The program demonstrates pushing and popping elements onto and from the stack and printing the stack elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 81

JSPM’s

Jayawant Institute of Management &


Studies

Laboratory Workbook
Subject: Data Structure Programming Lab

Course: MCA I - [Sem: I]

Prepared by,
Jancy Jose
Roll No: 61291425
SPPU Exam Seat No: 26954

Program Index
Sr. No.
Program

1 Demonstrate singly and doubly linked list.

2 STACK implementation using Array with PUSH, POP operations.

3
Reverse a string using stack.

4 Check for balanced parentheses by using Stacks.

5 Implement Stack using Linked List.


Demonstration of Linear Queue.
6
Demonstration of Circular Queue.
7
Demonstration of Priority Queue.
8

9 Reverse stack using queue.

Practical based on binary search tree implementation with its operations.


10

11 Graph implementation and graph traversals.

12 Implementation of Hashing.

Implementation of Brute Force technique Linear Search.


13

14 Implementation of Brute Force technique


Rain Terraces.
Implementation of Brute Force technique Travelling Salesman Problem.
15
Implementation of Greedy Algorithm-Prim’s.
16

Implementation of Greedy Kruskal’s algorithm.


17

Implementation of Divide and Conquer Technique-Binary Search.


18

Implementation of Divide and Conquer Technique-Tower of Hanoi


19

Implementation of Dynamic Programming- LCS, Regular Expression Matching


20

Practical based on backtracking- N Queen’s problems.


21

Write JavaScript code for Maximum Sub Array.


22

Write JavaScript code for Recursive Staircase.


23

Program 1:- Demonstrate singly and doubly linked list.


Source code

<script>

class Node {

constructor(data,next=null)

this.data=data;

this.next=next;

class Linkedlist

constructor()

this.head=null;

this.size=0;

insertFirst(data)

this.head=new Node(data,this.head)

this.size++;

insertLast(data)

let node=new Node(data)


if(!this.head)

this.head=node;

else

let temp=this.head;

while(temp.next)

temp=temp.next;

temp.next=node;

this.size++;

insertAtIndex(data,index)

if(index>0 & index>this.size)

return;

if(index===0)

{
this.head=new Node(data,this.head)

return;

let node=new Node(data)

let temp1,temp2;

temp1=this.head;

let count=0;

while(count<index)

temp2=temp1;

count++;

temp1=temp1.next;

node.next=temp1;

temp2.next=node;

this.size++;

getIndex(index)

var b=false;

let temp=this.head;

let count=0;
while(temp)

if(count==index)

document.write("data is= "+temp.data +""+ " index="+index);

document.write("</br>");

b=true;

count++;

temp=temp.next;

if(b==false)

document.write("null");

removeat(index)

let temp1=this.head;

let temp2;

let count=0;

if(index>0 & index>this.size)

return;
}

if(index===0)

this.head=temp1.next;

else

while(count<index)

count++;

temp2=temp1;

temp1=temp1.next;

temp2.next=temp1.next;

document.write("deleted data= "+temp1.data);

document.write("</br>");

this.size--;

clearlist()
{

this.head=null;

this.size=0;

printdatalist()

let temp=this.head;

while(temp)

document.write(temp.data);

document.write("</br>");

temp=temp.next

document.write("Singly Linked List")

document.write("</br>")

const ll=new Linkedlist();

ll.insertFirst(100)

ll.insertAtIndex(200,1)

ll.insertAtIndex(300,2)

ll.insertAtIndex(400,3)

ll.insertLast(500)

ll.printdatalist()
ll.removeat(0)

ll.printdatalist()

ll.getIndex(3)

document.write("Size:"+ll.size);

document.write("</br>")

document.write("Doubly Linked List")

document.write("</br>")

function doubleLinkedList() {

let Node = function(element) {

this.element = element;

this.next = null;

this.prev = null;

let length = 0;

let head = null;

let tail = null;

this.append = function(element) {

let node = new Node(element),

current = head,

previous;

if(!head){

head = node;
tail = node;

}else{

node.prev = tail;

tail.next = node;

tail = node;

length++;

this.insert = function(position, element) {

if(position >= 0 && position <= length){

let node = new Node(element),

current = head,

previous,

index = 0;

if(position === 0){

if(!head){

head = node;

tail = node;

}else{

node.next = current;

current.prev = node;

head = node;
}

}else if(position === length){

current = tail;

current.next = node;

node.prev = current;

tail = node;

}else{

while(index++ < position){

previous = current;

current = current.next;

node.next = current;

previous.next = node;

current.prev = node;

node.prev = previous;

length++;

return true;

}else{

return false;

}
this.removeAt = function(position){

if(position > -1 && position < length){

let current = head, previous, index = 0;

if(position === 0){

head = current.next;

if(length === 1){

tail = null;

}else{

head.prev = null;

}else if(position === length - 1){

current = tail;

tail = current.prev;

tail.next = null;

}else{

while(index++ < position){

previous = current;

current = current.next;

previous.next = current.next;

current.next.prev = previous;

length--;
return current.element;

}else{

return null;

this.indexOf = function(elm){

let current = head,

index = -1;

while(current){

if(elm === current.element){

return ++index;

index++;

current = current.next;

return -1;

};

this.isPresent = (elm) => {

return this.indexOf(elm) !== -1;

};

this.delete = (elm) => {

return this.removeAt(this.indexOf(elm));

};
this.deleteHead = function(){

this.removeAt(0);

this.deleteTail = function(){

this.removeAt(length-1);

this.toString = function(){

let current = head,

string = '';

while(current){

string += current.element + (current.next ? '\n' : '');

current = current.next;

return string;

};

this.disp = function(){

let arr = [],

current = head;

while(current){

arr.push(current.element);

current = current.next;

}return arr;

};
this.isEmpty = function(){

return length === 0;

};

this.size = function(){

return length;

this.getHead = function() {

return head;

this.getTail = function() {

return tail;

}}

let dll = new doubleLinkedList();

dll.append('Megha');

dll.append('Prasanna');

dll.append('Ashlesha');

document.write(dll.disp());

document.write("</br>");

dll.insert(1, 'Shashank');

document.write(dll.disp());

document.write("</br>");

dll.deleteHead();

document.write(dll.disp());

document.write("</br>");
dll.deleteTail();

document.write(dll.disp());

document.write("</br>");

</script>

Output:

Singly Linked List


100
200
300
400
500
deleted data= 100
200
300
400
500
data is= 500 index=3
Size:4
Doubly Linked List
Megha,Prasanna,Ashlesha
Megha,Shashank,Prasanna,Ashlesha
Shashank,Prasanna,Ashlesha
Shashank,Prasanna

Program 2:- STACK implementation using Array with PUSH, POP operations
Source code

<script>

class Stack {

constructor() {

this.items = [];

push(element) {

this.items.push(element);

pop() {

return this.items.pop();

peek() {

return this.items[this.items.length - 1];

isEmpty() {

return this.items.length === 0;

size() {
return this.items.length;

clear() {

this.items = [];

toArray() {

return this.items;

disp(){

for(let i=this.items.length-1;i>=0;i--)

document.write(this.items[i]);

document.write("</br>");

toString() {

return this.items.toString();

const stack = new Stack();


document.write('stack.isEmpty() => ', stack.isEmpty());

document.write("<br>");

stack.push(12);

stack.push(13);

stack.disp();

document.write('stack.peek() => ', stack.peek());document.write("<br>");

stack.push(14);

stack.disp();

document.write('stack.size() after push 14 => ', stack.size());

document.write("<br>");

document.write('stack.isEmpty() => ', stack.isEmpty());

document.write("<br>");

stack.push(15);

document.write('stack.size() after push 15 => ', stack.size());

document.write("<br>");

stack.disp();

stack.pop();

document.write("stack after pop </br>");

stack.disp();

stack.pop();

document.write("stack after pop </br>");

stack.disp();

document.write('stack.size() after push 15 and pop twice => ', stack.size());

</script>
Output:

stack.isEmpty() => true


13
12
stack.peek() => 13
14
13
12
stack.size() after push 14 => 3
stack.isEmpty() => false
stack.size() after push 15 => 4
15
14
13
12
stack after pop
14
13
12
stack after pop
13
12
stack.size() after push 15 and pop
twice => 2

Program 3:- Reverse a function using stack (String)


Source code

<script>

class Stack

constructor(){

this.data = [];

this. length = 0;

push(item){

this.length++;

return this.data.push(item);

pop (){

if (length <= 0) {

return null;

} else {

length--;

return data.pop();

peek() {

if (length <= 0) {

return null;

} else {
return data[length - 1];

disp()

for(let i=this.data.length-1;i>=0;i--)

document.write(this.data[i]);

isEmpty(){

return !length;

function reverseString(str) {

let result = "";

let stack = new Stack();

let strArr = str.split("");

strArr.forEach((element) => {

stack.push(element);

});

stack.disp();
while (!stack.isEmpty()) {

result += stack.pop();

return result;

let str = "Megha";

document.write("Original String:"+str+"</br>");

document.write("Reverse String: ");

document.write(reverseString(str));

</script>

Output:

Original String:Megha
Reverse String: ahgeM
Program 4:- Check for balanced parentheses by using Stacks

Source code

<script>

isMatchingBrackets = function(str) {

let stack = [];

let map = {

'(': ')',

'[': ']',

'{': '}'

for (let i = 0; i < str.length; i++) {

if (str[i] === '(' || str[i] === '{' || str[i] === '[') {

stack.push(str[i]);

else {

let last = stack.pop();

if (str[i] !== map[last]) {

return false

};

if (stack.length !== 0) {

return false

};
return true;

document.write(isMatchingBrackets("(){}"));

document.write("</br>");

document.write(isMatchingBrackets("({(()))}}"));

document.write("</br>");

</script>

Output:

true
false
Program 5:- Implement Stack using Linked List

Source code

<script>

function stackUsingLL(){

let Node = function(elm){

this.element = elm;

this.next = null;

let length = 0;

let head = null;

this.push = function(elm){

let node = new Node(elm),

current;

current = head;

node.next = current;

head = node;

length++;

this.pop = function(){
let current = head;

if(current){

let elm = current.element;

current = current.next;

head = current;

length--;

return elm;

return null;

this.peek = function(){

if(head){

return head.element;

return null;

this.toArray = function(){

let arr = [];

let current = head;

while(current){

arr.push(current.element);
current = current.next;

return arr;

this.isEmpty = function(){

return length === 0;

this.size = function(){

return length;

this.clear = function(){

head = null;

length = 0;

let stack = new stackUsingLL();

stack.push(1);

stack.push(2);

stack.push(3);

document.write(stack.peek());

document.write("<br>");
document.write(stack.isEmpty());

document.write("<br>");

document.write(stack.size());

document.write("<br>");

document.write(stack.pop());

document.write("<br>");

document.write(stack.toArray());

document.write("<br>");

document.write(stack.size());

document.write("<br>");

stack.clear();

document.write(stack.isEmpty());

document.write("<br>");

</script>

Output:

3
false
3
3
2,1
2
true
Program 6:- Demonstration of Linear Queue.

Source code

<script>

class Queue {

constructor() {

this.items = [];

enqueue(element) {

return this.items.push(element);

dequeue() {

if(this.items.length > 0) {

return this.items.shift();

peek() {

return this.items[this.items.length - 1];

isEmpty(){

return this.items.length == 0;

size(){
return this.items.length;

clear(){

this.items = [];

var str="Queue is Cleared";

return str

let queue = new Queue();

queue.enqueue(1);

queue.enqueue(2);

queue.enqueue(4);

queue.enqueue(8);

document.write(queue.items);

document.write("</br>");

queue.dequeue();

document.write(queue.items);

document.write("</br>");

document.write(queue.peek());

document.write("</br>");

document.write(queue.isEmpty());

document.write("</br>");

document.write(queue.size());

document.write("</br>");
var c=queue.clear();

document.write(c);

document.write("</br>");

</script>

Output:

1,2,4,8
2,4,8
8
false
3
Queue is Cleared
Program 7:- Demonstration of Circular Queue.

Source code

<script>

class CircularQueue {

constructor(size) {

this.element = [];

this.size = size

this.length = 0

this.front = 0

this.back = -1

print() {

document.write(this.element);

isEmpty() {

return (this.length == 0)

enqueue(element) {

if (this.length >= this.size) throw (new Error("Maximum length exceeded"))

this.back++

this.element[this.back % this.size] = element

this.length++

dequeue() {
if (this.isEmpty()) throw (new Error("No elements in the queue"))

const value = this.getFront()

this.element[this.front % this.size] = null

this.front++

this.length--

document.write(value);

getFront() {

if (this.isEmpty()) throw (new Error("No elements in the queue"))

return this.element[this.front % this.size]

clear() {

this.element = new Array()

this.length = 0

this.back = 0

this.front = -1

let cq=new CircularQueue(5);

cq.enqueue(100);

cq.enqueue(5);

cq.enqueue(20);

cq.enqueue(35);

cq.enqueue(45);
cq.print();

document.write("</br>");

cq.dequeue();

document.write("</br>");

cq.print();

</script>

Output:
Program 8:- Demonstration of Priority Queue

Source code

<script>

class QElement {

constructor(element, priority)

this.element = element;

this.priority = priority;

class PriorityQueue {

constructor()

this.items = [];

enqueue(element, priority)

var qElement = new QElement(element, priority);

var contain = false;

for (var i = 0; i < this.items.length; i++) {

if (this.items[i].priority > qElement.priority) {

this.items.splice(i, 0, qElement);

contain = true;

break;
}

if (!contain) {

this.items.push(qElement);

dequeue()

if (this.isEmpty())

return "Underflow";

return this.items.shift();

front()

if (this.isEmpty())

return "No elements in Queue";

return this.items[0];

rear()

if (this.isEmpty())

return "No elements in Queue";

return this.items[this.items.length - 1];


}

isEmpty()

return this.items.length == 0;

printPQueue()

var str = "";

for (var i = 0; i < this.items.length; i++)

str += this.items[i].element + " ";

return str;

var priorityQueue = new PriorityQueue();

document.write(priorityQueue.isEmpty());

document.write("</br>");

document.write(priorityQueue.front());

document.write("</br>");

priorityQueue.enqueue("Megha", 2);

priorityQueue.enqueue("Ketaki", 1);

priorityQueue.enqueue("Rasika", 1);

priorityQueue.enqueue("Shahida", 2);

priorityQueue.enqueue("Shivani", 3);
document.write(priorityQueue.printPQueue());

document.write("</br>");

document.write(priorityQueue.front().element);

document.write("</br>");

document.write(priorityQueue.rear().element);

document.write("</br>");

document.write(priorityQueue.dequeue().element);

document.write("</br>");

priorityQueue.enqueue("Shashank", 2);

document.write(priorityQueue.printPQueue());

document.write("</br>");

</script>

Output:

true
No elements in Queue
Ketaki Rasika Megha Shahida Shivani
Ketaki
Shivani
Ketaki
Rasika Megha Shahida Shashank Shivani
Program 9:- Reverse stack using queue

Source code

<script>

class Stack {

constructor(){

this.elements = [];

push(element){

this.elements.push(element);

pop(){

if(this.isEmpty()) return "Underflow situation";

else return this.elements.pop();

isEmpty(){

return this.elements.length == 0;

print(){

return this.elements;

}
}

class Queue {

constructor(){

this.elements = [];

enqueue(element){

this.elements.push(element)

dequeue() {

if(!this.isEmpty()) {

return this.elements.shift();

} else {

return 'Underflow situation';

isEmpty() {

return this.elements.length == 0;

function reverse(stack){
const queue = new Queue();

while(!stack.isEmpty()){

queue.enqueue(stack.pop());

while(!queue.isEmpty()){

stack.push(queue.dequeue());

const stack = new Stack();

stack.push('Megha');

stack.push('is');

stack.push('Student');

document.write('Printing stack before reversal: ', stack.print());

document.write("</br>");

reverse(stack);

document.write('Printing stack after reversal: ', stack.print());

document.write("</br>");

</script>

Output:

Printing stack before reversal: Megha,is,Student


Printing stack after reversal: Student,is,Megha
Program 10:- Practical based on binary search tree implementation with its operations.

Source code

<script>

class Node

constructor(data)

this.data = data;

this.left = null;

this.right = null;

class BinarySearchTree

constructor()

this.root = null;

insert(data)

var newNode = new Node(data);

if(this.root === null)

this.root = newNode;

else
this.insertNode(this.root, newNode);

insertNode(node, newNode)

if(newNode.data < node.data)

if(node.left === null)

node.left = newNode;

else

this.insertNode(node.left, newNode);

else

if(node.right === null)

node.right = newNode;

else

this.insertNode(node.right,newNode);

remove(data)

this.root = this.removeNode(this.root, data);


}

removeNode(node, key)

if(node === null)

return null;

else if(key < node.data)

node.left = this.removeNode(node.left, key);

return node;

else if(key > node.data)

node.right = this.removeNode(node.right, key);

return node;

else

if(node.left === null && node.right === null)

node = null;

return node;

}
if(node.left === null)

node = node.right;

return node;

else if(node.right === null)

node = node.left;

return node;

var aux = this.findMinNode(node.right);

node.data = aux.data;

node.right = this.removeNode(node.right, aux.data);

return node;

inorder(node)

if(node !== null)

this.inorder(node.left);
document.write(node.data);

document.write(" ");

this.inorder(node.right);

preorder(node)

if(node !== null)

document.write(node.data);

document.write(" ");

this.preorder(node.left);

this.preorder(node.right);

postorder(node)

if(node !== null)

this.postorder(node.left);

this.postorder(node.right);

document.write(node.data);

document.write(" ");

}
}

findMinNode(node)

if(node.left === null)

return node;

else

return this.findMinNode(node.left);

getRootNode()

return this.root;

search(node, data)

if(node === null)

return null;

else if(data < node.data)

return this.search(node.left, data);

else if(data > node.data)

return this.search(node.right, data);

else

return node;

}
var BST = new BinarySearchTree();

BST.insert(15);

BST.insert(25);

BST.insert(10);

BST.insert(7);

BST.insert(22);

BST.insert(17);

BST.insert(13);

BST.insert(5);

BST.insert(9);

BST.insert(27);

var root = BST.getRootNode();

BST.inorder(root);

BST.remove(5);

var root = BST.getRootNode();

document.write("</br>");

BST.inorder(root);

BST.remove(7);
var root = BST.getRootNode();

document.write("</br>");

BST.inorder(root);

BST.remove(15);

var root = BST.getRootNode();

document.write("</br>");

document.write("inorder traversal");

document.write("</br>");

BST.inorder(root);

document.write("</br>");

document.write("postorder traversal");

document.write("</br>");

BST.postorder(root);

document.write("</br>");

document.write("preorder traversal");

document.write("</br>");

BST.preorder(root);

document.write("</br>");

</script>
Output:
Program 11:- Graph implementation and graph traversals.

Source code

<script>

class Graph {

constructor() {

this.AdjList = new Map();

console.log('Di-graph');

addVertex(vertex) {

if (!this.AdjList.has(vertex)) {

this.AdjList.set(vertex, []);

} else {

throw 'Already Exist!!!';

addEdge(vertex, node) {

if (this.AdjList.has(vertex)) {

if (this.AdjList.has(node)){

let arr = this.AdjList.get(vertex);

if(!arr.includes(node)){

arr.push(node);

}else{
throw `Can't add '${node}', it already exists`;

}else {

throw `Can't add non-existing vertex ->'${node}'`;

} else {

throw `You should add '${vertex}' first`;

print() {

document.write(this.AdjList);

document.write("</br>")

for (let [key, value] of this.AdjList) {

document.write(key, value);

document.write("</br>")

createVisitedObject(){

let arr = {};

for(let key of this.AdjList.keys()){

arr[key] = false;

}
return arr;

bfs(startingNode){

document.write('\nBFS')

document.write("</br>")

let visited = this.createVisitedObject();

let q = [];

visited[startingNode] = true;

q.push(startingNode);

while(q.length){

let current = q.pop()

document.write(current);

let arr = this.AdjList.get(current);

for(let elem of arr){

if(!visited[elem]){

visited[elem] = true;

q.unshift(elem)

}
}

dfs(startingNode){

document.write('\nDFS')

document.write("</br>");

let visited = this.createVisitedObject();

this.dfsHelper(startingNode, visited);

dfsHelper(startingNode, visited){

visited[startingNode] = true;

document.write(startingNode);

let arr = this.AdjList.get(startingNode);

for(let elem of arr){

if(!visited[elem]){

this.dfsHelper(elem, visited);

}
}

doesPathExist(firstNode, secondNode){

let path = [];

let visited = this.createVisitedObject();

let q = [];

visited[firstNode] = true;

q.push(firstNode);

while(q.length){

let node = q.pop();

path.push(node);

let elements = this.AdjList.get(node);

if(elements.includes(secondNode)){

document.write(path.join('->'))

return true;

}else{

for(let elem of elements){

if(!visited[elem]){

visited[elem] = true;

q.unshift(elem);

}
}

return false;

function test (arg1, arg2){

if(arg1 === arg2){

document.write(`${arg1} = ${arg2} \t-> passing`)

document.write("</br>");

}else{

throw 'Not passing';

let g = new Graph();

let arr = ['A', 'B', 'C', 'D', 'E', 'F'];

for (let i = 0; i < arr.length; i++) {

g.addVertex(arr[i]);

g.addEdge('A', 'B');

g.addEdge('A', 'D');

g.addEdge('A', 'E');

g.addEdge('B', 'C');
g.addEdge('D', 'E');

g.addEdge('E', 'F');

g.addEdge('E', 'C');

g.addEdge('C', 'F');

g.print();

g.bfs('A');

document.write("</br>");

g.dfs('A');

document.write("</br>");

</script>

<!-- edit your html here -->

Output:
Program 12:- Implementation of Hashing.

Source code

<script>

class HashTable {

constructor() {

this.values = {};

this.length = 0;

this.size = 0;

calculateHash(key) {

return key.toString().length % this.size;

add(key, value) {

const hash = this.calculateHash(key);

if(!this.values.hasOwnProperty(hash))

this.values[hash] = {};

if (!this.values[hash].hasOwnProperty(key)) {

this.length++;

this.values[hash][key] = value;

search(key) {
const hash = this.calculateHash(key);

if (this.values.hasOwnProperty(hash) && this.values[hash].hasOwnProperty(key)) {

document.write(key+" has its hash value of: ")

return this.values[hash][key];

} else {

return null;

}}}

const ht = new HashTable();

ht.add("Canada", "300");

ht.add("Germany", "100");

ht.add("Italy", "50");

document.write(ht.search("Canada"));

</script>

Output:
Program 13:- Implementation of Brute Force technique Linear Search.

Source code

<script>

function linearSearch(arr, key){

var b=false;

for(let i = 0; i < arr.length; i++){

if(arr[i] === key){

document.write(key+" found at: ")

document.write((i+1)+" position");

b=true;}

if(b==false){

document.write("Key Not Found");}

arr=[1,3,5,8,9]

key=3

linearSearch(arr,key)

</script>

Output:
Program 14:- Implementation of Brute Force technique Rain Terraces.

Source code

<script>

function trapWaterUsingBrute(bars) {

len = bars.length;

trappedWater = 0;

for (i= 1; i< len - 1; i++) {

Imax = 0; rmax = 0;

for (j =i- 1; j >= 0; j--)

Imax = Math. max(Imax, bars[j]);

for (j =i + 1; j < len; j++)

rmax = Math.max(rmax, bars[j]);

trappedWater += Math.max(0, Math.min(Imax, rmax) -

bars[i]);

return trappedWater;

bars = new Array(0, 1, 0, 2, 1,0, 1, 3,2, 1, 2,1)

document.write(bars);

document.write("<br>Water trapped:" +trapWaterUsingBrute(bars))

</script>

Output:

0,1,0,2,1,0,1,3,2,1,2,1
Water trapped:6
Program 15:- Implementation of Brute Force technique Travelling Salesman Problem.
Source code

<script>

function generatePermutations(Arr){

var permutations = [];

var A = Arr.slice();

function swap(a,b){

var tmp = A[a];

A[a] = A[b];

A[b] = tmp;

function generate(n, A){

if (n == 1){

permutations.push(A.slice());

} else {

for(var i = 0; i <= n-1; i++) {

generate(n-1, A);

swap(n % 2 == 0 ? i : 0 ,n-1);

generate(A.length, A);

document.write(" ")

return permutations;

}function generateCityRoutes(cities){
var pems = generatePermutations(cities.slice(1));

for (var i = 0; i < pems.length; i++){

pems[i].unshift(cities[0]);

pems[i].push(cities[0]);

return pems;

document.write("</br>");

}document.write("Permutations are: ")

document.write(generatePermutations([1,2,3]));

document.write("</br>");

document.write("City routes are: ")

document.write(generateCityRoutes([0,2,3]));

document.write("</br>");

</script>

Output:

Program 16:- Implementation of Greedy Algorithm-Prim’s.


Source code

<script>

function createAdjMatrix(V, G) {

var adjMatrix = [];

for (var i = 0; i < V; i++) {

adjMatrix.push([]);

for (var j = 0; j < V; j++) { adjMatrix[i].push(0); }

for (var i = 0; i < G.length; i++) {

adjMatrix[G[i][0]][G[i][1]] = G[i][2];

adjMatrix[G[i][1]][G[i][0]] = G[i][2];

return adjMatrix;

function prims(V, G) {

var adjMatrix = createAdjMatrix(V, G);

var vertex = 0;

var MST = [];

var edges = [];

var visited = [];


var minEdge = [null,null,Infinity];

while (MST.length !== V-1) {

visited.push(vertex);

for (var r = 0; r < V; r++) {

if (adjMatrix[vertex][r] !== 0) {

edges.push([vertex,r,adjMatrix[vertex][r]]);

for (var e = 0; e < edges.length; e++) {

if (edges[e][2] < minEdge[2] && visited.indexOf(edges[e][1]) === -1) {

minEdge = edges[e];

edges.splice(edges.indexOf(minEdge), 1);

MST.push(minEdge+"</br>")

vertex = minEdge[1];

minEdge = [null,null,Infinity];

document.write(MST);

var a = 0, b = 1, c = 2, d = 3, e = 4, f = 5;

var graph = [

[a,b,2],

[a,c,3],
[b,d,3],

[b,c,5],

[b,e,4],

[c,e,4],

[d,e,2],

[d,f,3],

[e,f,5]

];

prims(6, graph);

</script>

Output:

Program 17:- Implementation of Greedy Kruskal’s algorithm.


Source code

<script>

var kruskal = function(points) {

const n = points.length;

const dist = [];

const graph = [...Array(n)].map((_, i) => i);

let totalDist = 0;

for(let i = 0; i < n; i++) {

for(let j = i+1; j < n; j++) {

const [x1, y1] = points[i];

const [x2, y2] = points[j];

const distance = Math.abs(x1 - x2) + Math.abs(y1 - y2);

dist.push([distance, i, j]);

dist.sort((a, b) => a[0] - b[0]);

function find(id) {

if(graph[id] === id) return id;

graph[id] = find(graph[id]);

return graph[id];

}
for(let [d, u, v] of dist) {

const rootU = find(u);

const rootV = find(v);

if(rootU === rootV) continue;

graph[rootV] = rootU

totalDist += d;

document.write("Minimum Cost is: ")

document.write(totalDist)

};

var points = [[3,12],[-2,5],[-4,1]]

kruskal(points)

</script>

Output:

Program 18:- Implementation of Divide and Conquer Technique-Binary Search.


Source code

<script>

let recursiveFunction = function (arr, x, start, end) {

if (start > end) return false;

let mid=Math.floor((start + end)/2);

if (arr[mid]===x)

document.write("Element found at: "+(mid+1))

document.write("</br>");

return true;

if(arr[mid] > x)

return recursiveFunction(arr, x, start, mid-1);

else

return recursiveFunction(arr, x, mid+1, end);

let arr = [1, 3, 5, 7, 8, 9];

let x = 5;

if (recursiveFunction(arr, x, 0, arr.length-1))

document.write();

else document.write("Element not found!<br>");

x = 6;

if (recursiveFunction(arr, x, 0, arr.length-1))
document.write();

else document.write("Element not found!<br>");

</script>

Output:

Program 19:- Implementation of Divide and Conquer Technique-Tower of Hanoi


Source code

<script>

function towerOfHanoi(n, from_rod, to_rod, aux_rod)

if (n == 1)

document.write("Move disk 1 from rod " + from_rod + " to rod " + to_rod+"<br/>");

return; }

towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);

document.write("Move disk " + n + " from rod " + from_rod +" to rod " + to_rod+"<br/>");

towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);}

var n = 3;

towerOfHanoi(n, 'A', 'C', 'B')

</script>

Output:

Program 20:- Implementation of Dynamic Programming- LCS, Regular Expression Matching.


Source code

<script>

let X, Y;

function lcs(i, j, count)

if (i == 0 || j == 0)

return count;

if (X[i - 1] == Y[j - 1]) {

count = lcs(i - 1, j - 1, count + 1);

count = Math.max(count,

Math.max(lcs(i, j - 1, 0),

lcs(i - 1, j, 0)));

return count;

let n, m;

X = "abcdxyez";

Y = "xyzabcyued";

n = X.length;
m = Y.length;

document.write("Lowest Common Subsequence is of: ");

document.write(lcs(n, m, 0)+" Characters");

function ValidateEmail(inputText)

var mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;

if(mailformat.test(inputText))

alert("Valid email address!");

return true;

else

alert("You have entered an invalid email address!");

return false;

var s="meghaughade1999@gmail.com";

ValidateEmail(s);

</script>

Output:
Program 21:- Practical based on backtracking- N Queen’s problems.

Source code

<script>

var iterations = 0
var print_board = function (columns) {

var n = columns.length, row = 0, col = 0

while (row < n) {

while (col < n) {

document.write(columns[row] === col ? 'Q ' : '# ')

col++

document.write('</br>')

col = 0

row++

var has_conflict = function (columns) {

var len = columns.length, last = columns[len - 1], previous = len - 2

while (previous >= 0) {

if (columns[previous] === last) return true

if (last - (len - 1) === columns[previous] - previous) return true

if (last + (len - 1) === columns[previous] + previous) return true

previous--

}
return false

var place_next_queen = function (total, queens, columns) {

if (queens === 0) return columns

columns = columns || []

for (var column = 0; column < total; column++) {

columns.push(column)

iterations++

if (!has_conflict(columns) &&

place_next_queen(total, queens - 1, columns)) {

return columns

columns.pop(column)

return null

print_board(place_next_queen(28, 28))

document.write('\niterations: ', iterations)

</script>
Output:

Q###########################
##Q#########################
####Q#######################
#Q##########################
###Q########################
########Q###################
##########Q#################
############Q###############
##############Q#############
################Q###########
######################Q#####
########################Q###
#####################Q######
###########################Q
#########################Q##
#######################Q####
##########################Q#
######Q#####################
###########Q################
###############Q############
#################Q##########
#######Q####################
#########Q##################
#############Q##############
###################Q########
#####Q######################
####################Q#######
##################Q#########
iterations: 84175966
Prpgram 22:-Write JavaScript code for Maximum Sub Array.

<script>

function maxSubarraySum(A,n) {

max_sum =0

for(i = 0;i<n;i++) {

sum=0

for(j =i ;j<n;j++) {

sum = sum + A[j]

if(sum > max_sum)

max_sum = sum }

return max_sum

A=new Array(3,2,6,8, -3,-4,6)

document. write("<br>Max Sum:"+maxSubarraySum(A,A.length))

</script>

OutPut:

Max Sum:19
Program 23:- Write JavaScript code for Recursive Staircase.

<script>

function climbStairs(N) {

if (N<2)

return 1

else

return climbStairs(N-1) + climbStairs(N-2)

N=prompt("Enter no. of staircase steps")

document. write("<br>No. of ways to climbstaircases are: "+climbStairs(N))

</script>

OutPut:

Enter no. of staircase steps

No. of ways to climbstaircases are: 8

***

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy