Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 139

MCA-I

Sem-I
Subject

Java [IT11L]

For Academic Year 2020-2021


Department of Master of Computer
Application

Zeal Education Society’s


Zeal Institute of Business Administration, Computer Application & Research (ZIBACAR)
Sr. No. 39, Narhe, Pune -411041, Phone No.:67206031
(Approved by A.I.C.T.E., Recognized by DTE (Govt. of Maharashtra) and Affiliated to Savitribai Phule Pune University)
CERTIFICATE
This is to certify that Mr. / Miss _____ of Class MCA (SEM-I),
Roll No. _FMC202113_, Exam Seat No. has completed all the
Term Work / Practical work in the subject “Java Practical”
(IT11L) satisfactorily in the Department of MCA as prescribed by
Savitribai Phule Pune University in the academic year 2020-2021.

Coordinator Director

Zeal Education Society’s


Zeal Institute of Business Administration, Computer Application & Research (ZIBACAR)
Sr. No. 39, Narhe, Pune -411041, Phone No.:67206031
(Approved by A.I.C.T.E., Recognized by DTE (Govt. of Maharashtra) and Affiliated to Savitribai Phule Pune University)

INDEX
Subject: - [IT11L] Java Practical
Sr. Page Sign of
No. Practical Date
No.
Remark
Faculty

Installation of jdk enviorment &


1 22/02/2021
following utilities. What is javac , javap
and javadoc
Design an application by using array.
2 24/02/2021
Programing
3 Implementation of package, Interface and
10/03/2021
abstract class
4 Design application using String,
16/03/2021
StringBuilder, StringTokenizer
5 Test any five of standard exception and user
18/03/2021
Defined Custom Exceptions in java
6 Threads creation and design applications
24/03/2021
by using Extending the Thread class/
Implementing the Runnable
Design java application Interface.in
using Collection
7 05/04/2021
java such as Array List, Link List
8 Design GUI based java application using 18/4/21
AWT, Swing with Event Handling.
9 Design a and implement JDBC applications. 04/5/21

10 Design and implement servlet applications. 11/5/21

11 Design and implement JSP applications 11/5/21

Assignment: 01

TITLE : Installation of jdk enviorment & following utilities. What is javac , javap
Class : MCA -I
Roll No. : FMC202113
Date :22/02/2021
Remark :

Program:
Program
Install the JDK software.

1.Go to www.oracle.com
2.click on “jdk download” under oracle jdk
3.run the downloaded installer accept the default and follow
instruction on screen.
4.run the file which will be downloaded on your screen.
5.verify the jdk installation. Launch the cmd
6.set the path
7.issue the Following command to verify the installation.
- path //to list the content of path.
-javac version // to display JDK version
-java version //to display JRE version
8.the system is ready to run java program.
Javac :
The javac tool reads class and interface definitions, written in
the Java programming language, and compiles them into
bytecode class files. It can also process annotations in Java source
files and classes.
Javap:
The javap tool is used to get the information of any class or
interface. The javap command (also known as the Java
Disassembler) disassembles one or more class files.
Assignment: -2
Title : write a java program find Max,Min,Avg values in given array
34,56,23,56,78,54,87,98,43,67
Class : MCA-I
Name : chirag manoj baldota.
Roll No.: 13
Date : 24/02/2021
Remark :

class MaxMinAvg
{
public static void main(String [] args)
{
int a[]={34,56,23,56,78,54,87,98,43,67};
int len=a.length;
int sum=0;
float avg;
int i=0;
int max=a[0];
int min=a[0];
for(i=0;i<len;i++)
{
System.out.print(+a[i]+" ");
}
for(i=1;i<len;i++)
{
if(a[i]>max)
{
max=a[i];
}
else if(min<a[i])
{
min=a[i];
}
//System.out.println("\nLength of array is:\t"+len);
}
System.out.println("\nMax number is:\t"+max);
System.out.println("\nMin number is:\t"+min);
for(i=0;i<=len;i++)
{
sum=(a[i]+(a[i]+1));
}
//avg = sum/len;

System.out.println("\nAverage is:\t"+sum);
}
}
Title : Write a java program for multiplication of two matrix.
Class : MCA-I
Name : chirag manoj baldota
Roll No.: 13
Date : 24/02/2021
Remark :

import java.util.*;

import java.lang.*;

class Matrices

public static void main(String [] args)

Scanner sc =new Scanner(System.in);

System.out.println("Enter the Row for both");

int Row=sc.nextInt();

System.out.println("Enter the Column for both");

int Col=sc.nextInt();

int arr1[][]=new int[Row][Col];

int arr2[][]=new int[Row][Col];

System.out.println("Enter the Elements for First Array");

for(int i=0;i<Row;i++)

for(int j=0;j<Col;j++)

{
arr1[i][j]=sc.nextInt();

System.out.println("Enter the Elements for Second Array");

for(int i=0;i<Row;i++)

for(int j=0;j<Col;j++)

arr2[i][j]=sc.nextInt();

System.out.println("First Array");

for(int i=0;i<Row;i++)

for(int j=0;j<Col;j++)

System.out.print(arr1[i][j]+"\t");

System.out.println();

System.out.println("Second Array");

for(int i=0;i<Row;i++)

for(int j=0;j<Col;j++)

System.out.print(arr2[i][j]+"\t");

System.out.println();

for(int i=0;i<Row;i++)
{

for(int j=0;j<Col;j++)

for(int k=0;k<Row;k++)

arr1[i][j]=arr1[i][j]*arr2[i][j];

System.out.println("After Multiplication Of Both Arrays:\n");

for(int i=0;i<Row;i++)

for(int j=0;j<Col;j++)

System.out.print(arr1[i][j]+"\t");

System.out.println();

System.out.println();

}
Title : Write a program store student record using array.
Operation:1)Add Record 2)Delete Record 3)Search Record 4)Display Record 5)Update
Record
Class : MCA-I
Name : chirag manoj baldota.
Roll No.: 13
Dfbfbfbsbsbffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
Date : 24/02/2021
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
Remark :
ffff

import java.util.*;
import java.lang.*;
class Array
{
public int Rollno[];
public String[] name;
public int Age[];
public String[] Cor;
public int Fee[];
int icnt=1;
int Display=0;

void Accept(int no)


{
Scanner sobj=new Scanner(System.in);

Rollno=new int[no];
name= new String[no];
Age=new int[no] ;
Cor=new String[no];
Fee=new int[no];

for(int i=0; i<name.length; i++)


{

System.out.println("Enter the rollno of "+ icnt+" Student :" );


Rollno[i]=sobj.nextInt();

sobj.nextLine();
System.out.println("Enter the Name of "+ icnt+" Student :" );
name[i]=sobj.nextLine();

System.out.println("Enter the Age of "+ icnt+" Student :" );


Age[i]=sobj.nextInt();

sobj.nextLine();
System.out.println("Enter the Course of "+ icnt+" Student :" );
Cor[i]=sobj.nextLine();

System.out.println("Enter the Fee of "+ icnt+" Student :" );


Fee[i]=sobj.nextInt();

System.out.println();

icnt++;
Display++;
}
}

void Delete(int Index)


{
int i=0;
for(i=0;i<Rollno.length; i++)
{
if(Index==Rollno[i])
{
for(int j=i; j<Rollno.length-1; j++)
{
Rollno[j]=Rollno[j+1];
name[j]=name[j+1];
Age[j]=Age[j+1];
Cor[j]=Cor[j+1];
Fee[j]=Fee[j+1];
}
Display--;
}
}
if(i>Rollno.length)
{
System.out.println("Rollno not found");
}
}

void Search(int rollno)


{
int i=0;
int iCnt=0;
for(i=0; i<Rollno.length; i++)
{
if(Rollno[i]==rollno)
{
System.out.println("Roll no: "+Rollno[i]);
System.out.println("Name: "+name[i]);
System.out.println("Age: "+Age[i]);
System.out.println("Course: "+Cor[i]);
System.out.println("Fee: "+Fee[i]);
System.out.println();
iCnt++;
}
}
if(iCnt>0)
{
System.out.println("Rollno Not Found");
}
}

void Update(int rollno, int choice)


{ Scanner sobj=new Scanner(System.in);

for(int i=0; i<Rollno.length; i++)


{
if(rollno==Rollno[i])
{
if(choice==1)
{
System.out.println("Enter the New Rollno u want to
update: ");

int nroll=sobj.nextInt();
Rollno[i]=nroll;
break;
}

else if(choice==2)
{
System.out.println("Enter the New Name u want to
update: ");
String nname=sobj.nextLine();
name[i]=nname;
break;
}

else if(choice==3)
{
System.out.println("Enter the New Age u want to
update: ");
int nAge=sobj.nextInt();
Age[i]=nAge;
break;
}

else if(choice==4)
{
System.out.println("Enter the New Course u want to
update: ");
String nCor=sobj.nextLine();
Cor[i]=nCor;
break;
}

else if(choice==5)
{
System.out.println("Enter the New Fees u want to
update: ");
int nfee=sobj.nextInt();
Fee[i]=nfee;
break;
}
}
}
}
void Display()
{
for(int i=0; i<Display ; i++)
{
System.out.println("Roll no: "+Rollno[i]);
System.out.println("Name: "+name[i]);
System.out.println("Age: "+Age[i]);
System.out.println("Course: "+Cor[i]);
System.out.println("Fee: "+Fee[i]);
System.out.println();
}
}
}
class Student
{
public static void main(String arg[])
{
Scanner sobj=new Scanner(System.in);
int choice=1;
int rollno=0;

Array aobj=new Array();

while(choice!=0)
{
System.out.println("1: Insert details");
System.out.println("2: Delete");
System.out.println("3: Display");
System.out.println("4: Search");
System.out.println("5: Update");
System.out.println("0: Exit");
choice=sobj.nextInt();

switch(choice)
{

case 1:
System.out.println("Enter Number of Students");
int no=sobj.nextInt();
aobj.Accept(no);
break;

case 2:
System.out.println("Enter the Rollno of the Student which is to be
deleted. ");
int Index=sobj.nextInt();
aobj.Delete(Index);
break;

case 3:
System.out.println("Entered Details are: \n");
aobj.Display();
break;

case 4:
System.out.println("Enter Rollno to search: \n");
rollno=sobj.nextInt();
aobj.Search(rollno);
break;

case 5:
System.out.println("Enter Rollno whose details are to be updated :
\n");
rollno=sobj.nextInt();

int Uchoice=1;

System.out.println("Select the choice which detail u want to


update: \n\n");
while((Uchoice<6)&&(Uchoice>0))
{
System.out.println("1: Update Rollno");
System.out.println("2: Update Name");
System.out.println("3: Update Age");
System.out.println("4: Update Course");
System.out.println("5: Update Fee");
System.out.println("6: Exit");
Uchoice=sobj.nextInt();

switch(Uchoice)
{
case 1:
aobj.Update(rollno, 1);
break;

case 2:
aobj.Update(rollno, 2);
break;

case 3:
aobj.Update(rollno, 3);
break;

case 4:
aobj.Update(rollno, 4);
break;

case 5:
aobj.Update(rollno, 5);
break;
}
}

break;
}
}
System.out.println("-----Thank You----- ");
}

}
Output –
ddd Assignment: 3
Title : Create a package compare values like max, min and equal.
Class : MCA-I
Name : chirag manoj baldota
Roll No.: 13
Date : 10/03/2021
Remark :
package com.core.java;
import java.util.*;
class Minimum
{
double a,b;
Minimum(double a,double b)
{
this.a=a;
this.b=b;
System.out.print("MINIMUM VALUE: "+Math.min(a,b));
}
}
class Maximum
{
double a,b;
Maximum(double a,double b)
{
this.a=a;
this.b=b;
System.out.print("MAXIMUM VALUE: "+Math.max(a,b));
}
}
class Equal
{
double a,b;
Equal(double a,double b)
{
this.a=a;
this.b=b;
if(a==b)
{
System.out.print("VALUE EQUAL");
}
else
{
System.out.print("VALUES ARE NOT EQUAL");
}
}
}
class MinMaxEqual
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
double a,b;
System.out.print("\nEnter Two Value: ");
a=sc.nextDouble();
b=sc.nextDouble();

while(true)
{

System.out.println("\n-----------------------------------------------------------------------------");
System.out.println("1.Check Maximum");
System.out.println("2.Check Minimum");
System.out.println("3.Check Equal");
System.out.println("0.Exit");
System.out.println("-----------------------------------------------------------------------------");
System.out.print("\nEnter your choice: ");
int ch=sc.nextInt();
switch(ch)
{

case 1:
Maximum mx=new Maximum(a,b);
break;
case 2:
Minimum mn=new Minimum(a,b);
break;
case 3:
Equal eq=new Equal(a,b);
break;
case 0:
return;
default:
System.out.println("Please Enter Correct Choice");
}
}
}
}
Output –

Title : Create interface Home loan in % use various bank like sbi.
Class : MCA-I
Name : chirag manoj baldota
Roll No.: 13
Date : 12/03/2021
Remark :
import java.util.*;
interface SBI
{
double CI(double p,double t);
}
class HomeLoan implements SBI
{
public double CI(double p,double t)
{
double r=6.5;
return p*(Math.pow((1+r/100),t));
}
}
class CarLoan implements SBI
{
public double CI(double p,double t)
{
double r=9.5;
return p*(Math.pow((1+r/100),t));
}
}
class SBILoan
{
public static void main(String[] args)
{
SBI h=new HomeLoan();
SBI c=new CarLoan();
int cnt=1;
Scanner sc=new Scanner(System.in);
System.out.println("Enter how much loan you want..?");
double p=sc.nextInt();
do
{
System.out.println("Enter years(condition min 4 years max 10 years): ");
double t=sc.nextDouble();
if(t>=4 && t<=10)
{
System.out.println("\nHome Loan: "+h.CI(p,t));
System.out.println("\nCar Loan: "+c.CI(p,t));
cnt--;

}
else
{
System.out.println("Please Enter Years Between 4 to 10");
cnt++;
}
}while(cnt>1);

}}
Output –
Title : Create a package of Health in under the folder of java/corejava/pack and calculate BMI.
Class : MCA-I
Name : chirag manoj baldota
Roll No.: 13
Date : 10/03/2021
Remark :

package core.corejava.pack;
import java.util.*;
import java.util.Scanner;
public class BMICalculate
{
public static void main(String [] args)
{
Scanner sc =new Scanner(System.in);
System.out.println("Enter Weight in kilogram:");
double w=sc.nextDouble();
System.out.println("Enter Hight in meters:");
double h=sc.nextDouble();
double bmi=w/(h*h);
System.out.println("The Body Mass Index(BMI) is :"+bmi+"kg");
}
}

Title : Create a package of find in under the folder of core/core java/pack and calculate EMI.
Class : MCA-I
Name : chirag manoj baldota
Roll No.: 13
Date : 12/03/2021
Remark :
package core.corejava.pack;

import java.util.Scanner.*;
import java.util.*;
class EMICalculate
{
double p,r,n;
EMICalculate(double p,double r,double n)
{
this.p=p;
this.r=r;
this.n=n;
double E=(p*r*Math.pow(1+r,n))/(Math.pow(1+r,n)-1);
System.out.println("EMI="+E);
}
}
class EMIWithMethod
{
public static void main(String [] args)
{
Scanner sc=new Scanner(System.in);
double p,r,n;
System.out.println("Enter The PrincipleAmt:\t");
p=sc.nextDouble();
System.out.println("Enter The Rate:\t");
r=sc.nextDouble();
System.out.println("Enter The Year:\t");
n=sc.nextDouble();
r=r/(12*100);
n=n*12;
EMICalculate amic= new EMICalculate(p,r,n);
}
}
Assignment: 5

Title: Design application using String, String builder, string tokenizer:


A) Write a java program check performance of String builder and String
buffer
B) Write a java program for String Builder using following methods.
C) Write a java program for String buffer using charAt(),substring().
D) Write a java program for String tokenizer user defined delimiter and string.
Class: MCA -I
Date:
16/03/2021

1) Write a java program check performance of String builder and String buffer.
import java.util.*;
import java.io.*;

public class StringTest


{
public static void main(String[] args)
{
long startTime =
System.currentTimeMillis(); StringBuffer sb
= new StringBuffer("String"); for (int i=0;
i<1000; i++)
{

sb.append("Test");
}
System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime)
+ "ms");
startTime = System.currentTimeMillis();
StringBuilder sb2 = new
StringBuilder("Java"); for (int i=0; i<10000;
i++)
{

sb2.append("Buffer");
}
System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() -
startTime)
+ "ms");
}
}

1. Write a java program for String Builder using following methods.

public class StringBuilderExample{


public static void main(String args[]) {

StringBuilder sb = new StringBuilder ("Welcome");

sb.append("java");
System.out.println(sb);

sb.insert(1,"mca");
System.out.println(sb);

sb.replace(1,5,"mca");
System.out.println(sb);

sb.delete(1,5);
System.out.println(sb);
sb.reverse();
System.out.println(sb);

StringBuilder sb1 = new StringBuilder();

System.out.println(sb1.capacity());
sb1.append("firstyear");
System.out.println(sb1.capacity()); sb1.append("java is
programming language");
System.out.println(sb1.capacity());

}
}

1. Write a java program for String buffer using charAt(),substring().

import java.io.*;

public class StringBufferExample


{
public static void main(String args[])
{
String obj1 = "Java
Programming"; char ch =
obj1.charAt(2);
System.out.println(obj1);
System.out.println(obj1.substring(1,2));

1. Write a java program for String tokenizer user defined delimiter and string.

import java.util.*;

public class Delimiter


{
public static void main(String[] args)
{
StringTokenizer st = new StringTokenizer("my,name,is,khan");
// printing next token.
System.out.println("Next token is : " + st.nextToken(","));
}
}
Assignment: 6
a
Title : Application of multithreading in java

Class : MCA-I

Name : chirag manoj baldota

Roll No.: FMC202113

Date : 18/03/2021

Que 1: Design a traffic Signal using java.

 signal.html
<html>

<applet code = "signal.class" height =400 width=300>


</applet>
</html>

 signal.java
import java.awt.*;
public class signal extends java.applet.Applet implements Runnable
{
Thread t; int
r,g,y,i;
public void init()
{
t=new Thread(this);
t.start();
r=0;
g=0;
y=0;
i=0;
}

public void run()


{
try{
for(i=24;i>=1;i--)
{
if(i>16 && i<=24)
{
T sleep(200);

r=1;
repaint();
}

if (i>16&&i<=24)
{
t.sleep(200);
r=1;
repaint();
}
if (i>8&&i<=16)
{
t.sleep(200);
y=1;
repaint();
}
if (i>1&&i<=8)
{
t.sleep(200);
g=1;
repaint();
}
}

if(i==0)
{
run();
}
}
catch(Exception e)
{

}
}

public void paint(Graphics gr)


{
gr.drawRect(100,100,100,300); if(r==1)

{
gr.setColor(Color.red);
gr.fillOval(100,100,100,100);
gr.setColor(Color.black);
gr.drawOval(100,200,100,100);
gr.drawOval(100,300,100,100); r=0;
}

if(y==1)
{
gr.setColor(Color.black);
gr.drawOval(100,100,100,100);
gr.drawOval(100,300,100,100);
gr.setColor(Color.yellow);
gr.fillOval(100,200,100,100);
y=0;
}

if (g==1)
{
gr.setColor(Color.black); gr.drawOval(100,100,100,100);
gr.drawOval(100,200,100,100);
gr.setColor(Color.green);
gr.fillOval(100,300,100,100); g=0;
}
}

}
Que 2: Bank transaction using synchronization.
Int amount = 10000;
synchronized void withdraw(int amount)
{
System.out.println("Going to withdraw");
if(this.amount<amount)
{
System.out.println("less balance"); try
{
wait();
}
catch(Exception e)
{

}
}

this.amount-=amount;
System.out.println("withdraw completed");
}

synchronized void deposite(int amount)


{
System.out.println("Going to deposite");
this.amount+=amount;
System.out.println("withdraw completed");
notify();
}
}

class banktransaction
{
public static void main(String args[])
{
final customer c= new customer(); new
Thread()
{
31
public void run()
{
c.withdraw(20000);

}
}.start();

new Thread()
{
public void run()
{
c.deposite(500000);
}
}.start();
}
}

Assignment - 7
Title : Design java application using collection in java such as Array List, link list.
Class : MCA-I
Name : chirag manoj baldota
Roll No.: 13
Date : 12/03/2021 32
Remark :
1) Design an application for Book Record using arrayList

import java.util.*;
import java.lang.*;

class Book
{
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity)
{
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class BookShelf
{
public static void main(String[] args)
{
List<Book> list=new ArrayList<Book>();

Book b1=new Book(101,"Harry Potter and the Prisnor of


Azkaban","J. K. Rowling","Bloomsbury",1);
Book b2=new Book(102,"Harry Potter and the Order of the
Phoenix","J. K. Rowling","Bloomsbury",2);
Book b3=new Book(103,"A Song of Ice and Fire","George Raymond
Richard Martin","Bantam Spectra",3);

list.add(b1);
list.add(b2);
list.add(b3);

for(Book b:list)
{

33
System.out.println("\nBook id :"+b.id+"\n Book name :
"+b.name+" \n Author :"+b.author+"\n Publisher : "+b.publisher+"\n Quantity :
"+b.quantity);

System.out.println("\n---------------------------------------------------------------------------
------------------");
}
}
}

Output:

2) Implementation of Student result record Stack using linkedlist.

import java.util.*;

class Node {

String result;
Node next;

34
class Stack {
private Node top;

public Stack() {
this.top = null;
}

public void push(String result) {


Node node = new Node();

if (node == null) {
System.out.println("Heap Overflow");
return;
}
node.result = result;
node.next = top;
top = node;
}

public boolean isEmpty() {


return top == null;
}

public String peek() {


if (!isEmpty()) {
return top.result;
} else {
System.out.println("The stack is empty");
return "";
}
}

public void pop() {


if (top == null) {
System.out.println("\nStack Underflow");
return;
}
if (isEmpty()) {
System.out.println("The stack is empty");
}

top = (top).next;
}

35
public void printStack(Stack s) {

if (s.isEmpty())
return;

String result = s.peek();


System.out.println(result);
s.pop();
printStack(s);
s.push(result);

}
}

class StackMain {
public static Stack stack;
public static void main(String[] args) {
stack = new Stack();

showOption();

public static void showOption() {

System.out.println("***************************************************
**************");
System.out.println("1. Add result");
System.out.println("2. Delete last added result");
System.out.println("3. Show All Record");
System.out.println("4. Exit ");

Scanner sc = new Scanner(System.in);


System.out.println("Enter your choice: ");
int option = Integer.parseInt(sc.nextLine());
if (option > 0 && option <= 4) {
switch (option) {
case 1:
System.out.print("Enter student roll number: ");

36
String rollNum = sc.nextLine();
System.out.print("Enter student name: ");
String sName = sc.nextLine();

System.out.print("Enter student percentage: ");


String percentage = sc.nextLine();
System.out.print("Enter student grade: ");
String grade = sc.nextLine();
stack.push(" | " + rollNum + " | " + sName + " | " + grade + "
| " + percentage + " | ");
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$");
break;
case 2:
stack.pop();

System.out.println("***************************************************
**********");
break;
case 3:
stack.printStack(stack);

System.out.println("***************************************************
***********");
break;
case 4:
System.exit(0);
break;
}

showOption();
} else {
System.out.println("Your choice is invalid");
}
if (stack.isEmpty()) {
System.out.println("The stack is empty");
} else {
System.out.println("The stack is not empty");
}
showOption();
}

37
3) Implementation of Student result record Queue using linkedlist.

import java.util.*;

class Node {

String data;

Node next;

public Node(String data) {

this.data = data;

this.next = null;

class Queue {

private static Node rear = null, front = null;

38
public static String dequeue()

if (front == null)

System.out.print("\nQueue Underflow");

System.exit(1);

Node temp = front;

front = front.next;

if (front == null)

rear = null;

String item = temp.data;

return item;

public static void enqueue(String item)

Node node = new Node(item);

if (front == null)

front = node;

rear = node;

else

39
rear.next = node;

rear = node;

public static String peek()

if (front != null)

return front.data;

else

System.exit(1);

return "";

public static boolean isEmpty()

return rear == null && front == null;

public void printQueue(Queue q)

40
if (q.isEmpty())

return;

String result = q.peek();

System.out.println(result);

q.dequeue();

printQueue(q);

q.enqueue(result);

class QueueMain

public static Queue queue;

public static void main(String[] args) {

queue = new Queue();

showOption();

public static void showOption() {

System.out.println("*******************************************");

System.out.println("1. Add result");

System.out.println("2. Delete last added result");

41
System.out.println("3. Show All Record");

System.out.println("4. Exit ");

Scanner sc = new Scanner(System.in);

System.out.println("Enter your choice: ");

int option = Integer.parseInt(sc.nextLine());

if (option > 0 && option <= 4) {

switch (option) {

case 1:

System.out.print("Enter student roll number: ");

String rollNum = sc.nextLine();

System.out.print("Enter student name: ");

String sName = sc.nextLine();

System.out.print("Enter student percentage: ");

String percentage = sc.nextLine();

System.out.print("Enter student grade: ");

String grade = sc.nextLine();

queue.enqueue(" | " + rollNum + " | " + sName + " | "+


grade + " | " + percentage + " | ");

System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$");

break;

case 2:

queue.dequeue()
System.out.println("***************************************************
*********");

break;

case 3:

queue.printQueue(queue);

42
System.out.println("***************************************************
**********");

break;

case 4:

System.exit(0);

break;

showOption();

} else {

System.out.println("Your choice is invalid");

if (queue.isEmpty()) {

System.out.println("The queue is empty");

} else {

System.out.println("The queue is not empty");

showOption();

43
4) Hash Set Example
import java.util.*;

public class SetEx

public static void main(String[] args)

Set<String> hash_Set = new HashSet<String>();

hash_Set.add("Azhar");

hash_Set.add("Rajat");

44
hash_Set.add("Gaurav");

hash_Set.add("Sayog");

hash_Set.add("Ismail");

System.out.println(hash_Set);

Output –

Assignment 8
Title : Design Registration form for Covid 19 patient using java.
Class : MCA-I
Name : chirag manoj baldota.
Roll No.: 13
Date : 04/18/2021
Remark :

Q:- Design Registration form for Covid-19 Paitent using


Java

45
Program:

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

class MyFrame extends JFrame implements ActionListener

// Components of the Form

private Container c;

private JLabel title;

private JLabel name;

private JTextField tname;

private JLabel add;

private JTextArea tadd;

private JLabel mno;

private JTextField tmno;

private JLabel adhar;

private JTextField tadhar;

private JLabel gender;

private JRadioButton male;

private JRadioButton female;

private JRadioButton other;

private ButtonGroup gengp;


46
private JLabel dob;

private JComboBox date;

private JComboBox month;

private JComboBox year;

private JCheckBox term;

private JButton sub;

private JButton reset;

private JTextArea tout;

private JLabel bg;

private JTextField tbg;

private JLabel sym;

private JTextArea tsym;

private JLabel res;

47
private JTextArea resadd;

private String dates[]

= { "1", "2", "3", "4", "5",

"6", "7", "8", "9", "10",

"11", "12", "13", "14", "15",

"16", "17", "18", "19", "20",

"21", "22", "23", "24", "25",

"26", "27", "28", "29", "30",

"31" };

private String months[]

= { "Jan", "feb", "Mar", "Apr",

"May", "Jun", "July", "Aug",

"Sup", "Oct", "Nov", "Dec" };

private String years[]

= { "1995", "1996", "1997", "1998",

"1999", "2000", "2001", "2002",

"2003", "2004", "2005", "2006",

"2007", "2008", "2009", "2010",

"2011", "2012", "2013", "2014",

"2015", "2016", "2017", "2018",

"2019" };

48
// constructor, to initialize the components

// with default values.

public MyFrame()

setTitle("Registration Form");

setBounds(300, 90, 1000, 800);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setResizable(false);

c = getContentPane();

c.setLayout(null);

title = new JLabel("Registration Form for covid-19");

title.setFont(new Font("Arial", Font.PLAIN, 30));

title.setSize(400, 40);

title.setLocation(300, 30);

c.add(title);

name = new JLabel("Name");

name.setFont(new Font("Arial", Font.PLAIN, 20));

name.setSize(100, 20);

name.setLocation(100, 100);

c.add(name);

49
tname = new JTextField();

tname.setFont(new Font("Arial", Font.PLAIN, 15));

tname.setSize(190, 20);

tname.setLocation(200, 100);

c.add(tname);

add = new JLabel("Address");

add.setFont(new Font("Arial", Font.PLAIN, 20));

add.setSize(100, 20);

add.setLocation(100, 150);

c.add(add);

tadd = new JTextArea();

tadd.setFont(new Font("Arial", Font.PLAIN, 15));

tadd.setSize(200, 75);

tadd.setLocation(200, 150);

tadd.setLineWrap(true);

c.add(tadd);

mno = new JLabel("Mobile");

mno.setFont(new Font("Arial", Font.PLAIN, 20));

mno.setSize(100, 20);

mno.setLocation(100, 250);

c.add(mno);

50
tmno = new JTextField();

tmno.setFont(new Font("Arial", Font.PLAIN, 15));

tmno.setSize(150, 20);

tmno.setLocation(200, 250);

c.add(tmno);

adhar = new JLabel("Aadhar Number");

adhar.setFont(new Font("Arial", Font.PLAIN, 20));

adhar.setSize(150, 20);

adhar.setLocation(100, 300);

c.add(adhar);

tadhar = new JTextField();

tadhar.setFont(new Font("Arial", Font.PLAIN, 15));

tadhar.setSize(200, 20);

tadhar.setLocation(250, 300);

c.add(tadhar);

dob = new JLabel("Date of birth");

dob.setFont(new Font("Arial", Font.PLAIN, 20));

dob.setSize(150, 20);

dob.setLocation(100, 350);

c.add(dob);

51
date = new JComboBox(dates);

date.setFont(new Font("Arial", Font.PLAIN, 15));

date.setSize(50, 20);

date.setLocation(250, 350);

c.add(date);

month = new JComboBox(months);

month.setFont(new Font("Arial", Font.PLAIN, 15));

month.setSize(60, 20);

month.setLocation(300, 350);

c.add(month);

year = new JComboBox(years);

year.setFont(new Font("Arial", Font.PLAIN, 15));

year.setSize(60, 20);

year.setLocation(350, 350);

c.add(year);

gender = new JLabel("Gender");

gender.setFont(new Font("Arial", Font.PLAIN, 20));

gender.setSize(100, 20);

gender.setLocation(100, 400);

c.add(gender);

52
male = new JRadioButton("Male");

male.setFont(new Font("Arial", Font.PLAIN, 15));

male.setSelected(true);

male.setSize(75, 20);

male.setLocation(200, 400);

c.add(male);

female = new JRadioButton("Female");

female.setFont(new Font("Arial", Font.PLAIN, 15));

female.setSelected(false);

female.setSize(80, 20);

female.setLocation(275, 400);

c.add(female);

other= new JRadioButton("Other");

other.setFont(new Font("Arial", Font.PLAIN, 15));

other.setSelected(false);

other.setSize(85, 20);

other.setLocation(350, 400);

c.add(other);

gengp = new ButtonGroup();

gengp.add(male);

53
gengp.add(female);

gengp.add(other);

bg = new JLabel("Blood Group");

bg.setFont(new Font("Arial", Font.PLAIN, 20));

bg.setSize(150, 20);

bg.setLocation(100, 450);

c.add(bg);

tbg = new JTextField();

tbg.setFont(new Font("Arial", Font.PLAIN, 15));

tbg.setSize(190, 20);

tbg.setLocation(250, 450);

c.add(tbg);

sym = new JLabel("Symptoms");

sym.setFont(new Font("Arial", Font.PLAIN, 20));

sym.setSize(100, 20);

sym.setLocation(100, 500);

c.add(sym);

tsym = new JTextArea();

tsym.setFont(new Font("Arial", Font.PLAIN, 15));

tsym.setSize(200, 75);

54
tsym.setLocation(250, 500);

tsym.setLineWrap(true);

c.add(tsym);

term = new JCheckBox("Given information is true.");

term.setFont(new Font("Arial", Font.PLAIN, 15));

term.setSize(250, 20);

term.setLocation(150, 600);

c.add(term);

sub = new JButton("Submit");

sub.setFont(new Font("Arial", Font.PLAIN, 15));

sub.setSize(100, 20);

sub.setLocation(150, 650);

sub.addActionListener(this);

c.add(sub);

reset = new JButton("Reset");

reset.setFont(new Font("Arial", Font.PLAIN, 15));

reset.setSize(100, 20);

reset.setLocation(270, 650);

reset.addActionListener(this);

c.add(reset);

55
tout = new JTextArea();

tout.setFont(new Font("Arial", Font.PLAIN, 15));

tout.setSize(300, 400);

tout.setLocation(500, 100);

tout.setLineWrap(true);

tout.setEditable(false);

c.add(tout);

res = new JLabel("");

res.setFont(new Font("Arial", Font.PLAIN, 20));

res.setSize(500, 25);

res.setLocation(500, 600);

c.add(res);

resadd = new JTextArea();

resadd.setFont(new Font("Arial", Font.PLAIN, 15));

resadd.setSize(200, 75);

resadd.setLocation(580, 175);

resadd.setLineWrap(true);

c.add(resadd);

setVisible(true);

56
// method actionPerformed()

// to get the action performed

// by the user and act accordingly

public void actionPerformed(ActionEvent e)

if (e.getSource() == sub) {

if (term.isSelected()) {

String data1;

String data

= "Name : "+ tname.getText() + "\n"

+ "Mobile : "+ tmno.getText() + "\n"

+ "Blood Group: "+ tbg.getText() + "\n"

+"Aadhar Number : " + tadhar.getText() + "\n";

if (male.isSelected())

data1 = "Gender : Male"+ "\n";

else if (female.isSelected())

data1 = "Gender : Female"+ "\n";

else

data1 = "Gender : Other" + "\n";

String data2

= "DOB : "

+ (String)date.getSelectedItem()

+ "/" + (String)month.getSelectedItem()

57
+ "/" + (String)year.getSelectedItem()

+ "\n";

String data3 = "Address : " + tadd.getText()+"\n"

+"Symptoms: "+ tsym.getText()+"\n";

tout.setText(data + data1 + data2 + data3);

tout.setEditable(false);

res.setText("Registration Successfully..");

else {

tout.setText("");

resadd.setText("");

res.setText("Please accept the"

+ " terms & conditions..");

else if (e.getSource() == reset) {

String def = "";

tname.setText(def);

tadd.setText(def);

tmno.setText(def);

tbg.setText(def);

tsym.setText(def);

58
tadhar.setText(def);

res.setText(def);

tout.setText(def);

term.setSelected(false);

date.setSelectedIndex(0);

month.setSelectedIndex(0);

year.setSelectedIndex(0);

resadd.setText(def);

// Driver Code

public class Registration {

public static void main(String[] args) throws Exception

MyFrame f = new MyFrame();

59
Output:

Assignment – 9
Title : Design and Implement JDBC Application for Student table.
Class : MCA-I
Name : chirag manoj baldota
Roll No.: FMC202113
Date : 04/05/2021 60
Remark :
import java.sql.*;
import java.io.*;
class Mca
{
public static void main(String args[])throws Exception
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));

int sid ,sper,n;

String name;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con=DriverManager.getConnection("jdbc:odbc:dsnstudent2");

Statement stmt=con.createStatement();

stmt.executeUpdate("create table student(sid int,name varchar(25),sper int)");

System.out.println("Table created");

System.out.println("Enter how many record do you want to insert:");

n=Integer.parseInt(br.readLine());

for(int i=1;i<=n;i++)
{
PreparedStatement pstmt=con.prepareStatement("insert into student
values(?,?,?)");

System.out.println("Enter rno name per:");

sid=Integer.parseInt(br.readLine());

name=br.readLine();

sper=Integer.parseInt(br.readLine());

pstmt.setInt(1,sid);

pstmt.setString(2,name);

pstmt.setInt(3,sper);

61
pstmt.executeUpdate();

System.out.println(i+"Record Inserted");

pstmt.close();
}
ResultSet rs=stmt.executeQuery("select * from student");

System.out.println("student rno name per:");

while(rs.next())
{
System.out.println(" "+rs.getInt(1)+" "+rs.getString(2)+" "+rs.getInt(3)); } rs.close();

stmt.close(); con.close();
}
}

OUTPUT:
C:\Program Files\Java\jdk1.5.0_20\bin>java slip22Q2

Table created

Enter how many record do you want to insert:

Enter rno name per:

111 aaa

90 1Record Inserted

Enter rno name per:

222 bbb

89 2Record Inserted

Enter rno name per:


333 ccc

90 3Record Inserted student rno name per:

111 aaa 90
222 bbb 89
333 ccc 90

62
C:\Program Files\Java\jdk1.5.0_20\bin>

Assignment no.10
Design and implement servlet applications.
1)Addition of two number by using servlet.
#demo.html file

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Addition of two numbers</title>
</head>
<body>
63
<form action="Demo" method="post">
First Number:<input type="text" name="num1"><br>
Second Number:<input type="text" name="num2"><br>
<input type="submit" value="Add">
</form>
</body>
</html>

#Demo.java servlet file

package co.ganesh;

import java.io.IOException;
import java.io.PrintWriter;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

@WebServlet("/Demo")
public class Demo extends HttpServlet
{
    
    protected void doPost(HttpServletRequest request, HttpServletResponse re
sponse) throws ServletException, IOException 
    {
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        int a=Integer.parseInt(request.getParameter("num1"));
int b=Integer.parseInt(request.getParameter("num2"));
        int c=a+b;
        out.println("Addition of two number is  "+c);
    }}
    

64
Q2)Display emp records belong to pune and salery greater than 43000

Test.java servlet file

import java.sql.Connection;
import java.lang.*;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.*;

public class Test 
{
    public static void main(String args []) throws Exception
    {   String url="jdbc:mysql://localhost:3306/epavitram";
        String uname="root";
        String password="ganesh123";
        String userdata="";
        String str ="insert into employees values(115,'vishal','pune',36,500
00)";
        String strs="select * from employees where e_address='pune' AND e_sa
lary>43000 ";
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection(url,uname,password);
        PreparedStatement st=con.prepareStatement(str);

65
          st.executeUpdate();
        System.out.println("e_id "+"    e_name "+"     e_address"+"    e_age
"+"        e_salary");
        ResultSet rs=st.executeQuery(strs);
         while(rs.next())
        {
            userdata=rs.getInt(1)+"      "+rs.getString(2)+"     "+rs.getStr
ing(3)+"             "+rs.getInt(4)+"           "+rs.getInt(5);
            System.out.println(userdata);       
        } 
          st.close();
         con.close();

    }

Employee table:

66
Q3)Design servlet application for session tracking .

#login.html file

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Viewdetail" method="post">
Username:<input type="text" name="uname"><br><br>
Password:<input type="password" name="pass"><br><br>
<input type="submit"  value="submit">

</form>
</body>
</html>

#Servlet1.java file

import java.io.IOException;
import java.io.PrintWriter;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

@WebServlet("/Viewdetail")
public class Servlet1 extends HttpServlet {

67
     
    protected void doPost(HttpServletRequest request, HttpServletResponse re
sponse) throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        HttpSession session=request.getSession();
        String user=request.getParameter("uname");
        String pass=request.getParameter("pass");
        session.setAttribute("u", user);
        session.setAttribute("p", pass);
        out.println("<form action="+"Servlet2"+ " method="+"post><br><br> <c
enter><input type="+"submit value="+"Viewdetail></center>  </form>");
        //out.println("<a href="+"Servlet2"+">Viewdetail</a>");
    }

#Servlet2.java file

import java.io.IOException;
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

@WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
    
    protected void doPost(HttpServletRequest request, HttpServletResponse re
sponse) throws ServletException, IOException 
    {
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        HttpSession session=request.getSession();
        String uname=(String)session.getAttribute("u");
        String pass=(String)session.getAttribute("p");
        out.println("user name is :"+uname);
        out.println("<br>password is :"+pass);
        
        }

68
69
A SSIGMENT: 11

Title : Design And implemet JSP application.


Class : MCA-I
Name : chirag manoj baldota
Roll No: FMC202113
Date : 11/05/2021
Remark:

Addition.html file

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Sum.jsp" method="post">
First Number:<input type="text" name="num1"><br><br>
Second Number:<input type="text" name="num2"><br><br>
<input type="submit" value="Add">
</form>
</body>
</html>

#sum.jsp file

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


70
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
int a=Integer.parseInt(request.getParameter("num1"));
int b=Integer.parseInt(request.getParameter("num2"));
int sum=a+b;
out.println("Sum of two number is : "+sum);

%>
</body>
</html>

71
MCA-I
Sem-I
Subject

DSA(IT-11L)

For Academic Year 2020-2021


Department of Master of Computer
Application

Zeal Education Society’s


Zeal Institute of Business Administration, Computer Application & Research (ZIBACAR)
Sr. No. 39, Narhe, Pune -411041, Phone No.:67206031
(Approved by A.I.C.T.E., Recognized by DTE (Govt. of Maharashtra) and Affiliated to Savitribai Phule Pune University)

72
CERTIFICATE
This is to certify that Mr. Chirag Manoj Balota of Class MCA
(SEM-I), Roll No. FMC202113, Exam Seat No. 25865 , has
completed all the Term Work / Practical work in the
subject “DSA Practical” satisfactorily in the Department of
MCA as prescribed by Savitribai Phule Pune University in the
academic year 2020-2021.

Coordinator Director

Zeal Education Society’s


Zeal Institute of Business Administration, Computer Application & Research (ZIBACAR)
Sr. No. 39, Narhe, Pune -411041, Phone No.:67206031
(Approved by A.I.C.T.E., Recognized by DTE (Govt. of Maharashtra) and Affiliated to Savitribai Phule Pune University)

73
INDEX
Subject: - DSA Practical

Sr. Page Sign of


No. Practical Date
No.
Remark
Faculty

Demonstrate Singly and Doubly linked 4-10


1 23/02/2021
list
2 Stack implementation using array with 10-16
26/02/2021
push & pop operation
3 Reverse a String using stack 17-21
12/03/2021

4 Chech for balanced purchase using stack 22


18/03/2021

5 Implement stack using stack 22-23


20/03/2021

6 Demonstration of linear queue, circular 24-25


23/03/2021
queue, priority queue
7 Revenue stack using queue 25-26
03/4/2021

8 Practical based on bst implementation 20/04/20 27-30


with its operation 21
9 Graph implementation and graph 06/05/21 31-32
traversal
10 Implemetaion of hashing 12/5/21 32-35

11 Practical based on brute force technique 12/5/21 36-41

12 Practical based on greedy algorithm prims 13/5/21 42-44


krushkal algorithm
13 Practical based on divide conquer technique 13/05/21 45-48
binary search tower of hanoi
14 Implementation of dynamic programming . 49-52
13/5/21
LCS, Regular Expression
Practical based on backtracking – N Queens
15 13/5/21 53-56
problems

74
ASSIGNMENT 1
Q1. Registration form.
<html>
<head>
<titile>
</titile>
<style>
.alertText
{
color:red;
}
</style>
</head>
<body>
<div style="border:2px solid black; margin-left:20%;margin-right:20%">
<h2 style="text-align:center;"> Rregistration Form</h2>
<hr>
<br>
<table style="width:auto; margin-left:20%;">
<tr>
<td>First Name:</td>
<td>
<input id="fName" type="text" name="fname" value="">
</td>
<td><label id="errfName" class="alertText" value="Not Null"></label></td>
</tr>
<tr>
<td>Middale Name:</td>
<td>
<input id="mName" type="text" name="mname" value="">
</td>
<td><label id="errmName" value="Not Null" class="alertText"></label></td>
</tr>
<tr>
75
<td>Last Name:</td>
<td>
<input id="lName" type="text" name="lname" value="">
</td>
<td><label id="errlName" value="Not Null" class="alertText"></label></td>
</tr>
<tr>
<td>Phone Number:</td>
<td>
<input id="contryid" name="fname" style="Width:25px;">
<input id="phoneNo" style="Width:70%;">
</td>
<td> <label id="errpcontryid" value="Not Null" class="alertText"></label>
</br>
<label id="errphoneno" value="Not Null" class="alertText"></label></td>
</tr>
<tr>
<td>Course</td>
<td>
<select id="Course">
<option value="0" selected="true">-Select-</option>
<option value="1">MCA</option>
<option value="2">MBA</option>
<option value="3">BCA</option>
<option value="4">BBA</option>
</select>
</td>
<td><label id="errCourse" value="Not Null" class="alertText"></label></td>
</tr>
<tr>
<td>
Gender:</td>
<td>
<input type="radio" id="male" name="gender" value="male"/>

76
<label for="male">Male</label></br>
<input type="radio" id="female" name="gender" value="female"/>
<label for="female">Female</label></br>
<input type="radio" id="other" name="gender" value="other"/>
<label for="other">Other</label>
</td>
<td><label id="errgender" value="Not Null" class="alertText"></label></td>
</tr>
<tr>
<td>Address</td>
<td>
<textarea id="Address" value=""></textarea>
</td>
<td><label id="errAddress" value="Not Null" class="alertText"></label></td>
</tr>
<tr>
<td>Email Address</td>
<td>
<input id="Eamil" type="email" value=""/>
</td>
<td><label id="errEamil" value="Not Null" class="alertText"></label></td>
</tr>
<tr>
<td>Password</td>
<td>
<input id="Pwd" type="password" value=""/>
</td>
<td><label id="errPwd" value="Not Null" class="alertText"></label></td>
</tr>
<tr>
<td>Retype Password</td>
<td>
<input id="repwd" type="password" value=""/>
</td>

77
<td><label id="errrePwd" value="Not Null" class="alertText"></label></td>
</tr>
<tr>
<td></td>
<td>
<br>
<input id="submit" type="submit" onclick="validate();" value="Submit"/>
</td>
<td><label id="errrePwd" value="Not Null"></label></td>
</tr>
</table>
</div>
</body>
<script>
function validate()
{
document.getElementById("errfName").innerHTML ="";
document.getElementById("errmName").innerHTML ="";
document.getElementById("errlName").innerHTML ="";
document.getElementById("errCourse").innerHTML ="";
document.getElementById("errpcontryid").innerHTML ="";
document.getElementById("errEamil").innerHTML ="";
document.getElementById("errAddress").innerHTML ="";
document.getElementById("errPwd").innerHTML="";
document.getElementById("errrePwd").innerHTML ="";
document.getElementById("errgender").innerHTML ="";
document.getElementById("errphoneno").innerHTML ="";
if(""==document.getElementById("fName").value)
{
document.getElementById("errfName").innerHTML ="Not Null";
}
if(""== document.getElementById("mName").value)
{
document.getElementById("errmName").innerHTML ="Not Null";

78
}
if(""== document.getElementById("lName").value)
{
document.getElementById("errlName").innerHTML ="Not Null";
}
if(""==document.getElementById("fName").value)
{
document.getElementById("errfName").innerHTML ="Not Null";
}
if(0==(document.getElementById("contryid").value))
{
document.getElementById("errpcontryid").innerHTML ="Country code is rquired";
}
if(""==document.getElementById("phoneNo").value)
{
document.getElementById("errphoneno").innerHTML ="Phone no Not Null";
}
var male1=document.getElementById("male").checked;
var female2=document.getElementById("female").checked;
var other3=document.getElementById("female").checked;
if(false==(document.getElementById("male").checked ==
document.getElementById("female").checked ==
document.getElementById("other").checked))
{
document.getElementById("errgender").innerHTML ="Select Gender";
}
var phoneno= document.getElementById("phoneNo").value;
if((phoneno.length>0 && (phoneno.length<10 || phoneno.length>10)))
document.getElementById("errphoneno").innerHTML ="Phone no Must be 10 Digit
number";
if(""==document.getElementById("Course").value)
{
document.getElementById("errCourse").innerHTML ="Course Not Null";
}

79
if(0==document.getElementById("Course").value)
{
document.getElementById("errCourse").innerHTML ="Select Any one Course";
}
if(""==document.getElementById("Address").value)
{
document.getElementById("errAddress").innerHTML ="Address Is required";
}
if(""==document.getElementById("Eamil").value)
{
document.getElementById("errEamil").innerHTML ="Enter Email";
}
if(""==document.getElementById("Pwd").value)
{
document.getElementById("errPwd").innerHTML ="Password is Required";
}
if(document.getElementById("Pwd").value!=document.getElementById("repwd").value)
{
document.getElementById("errrePwd").innerHTML ="Password Not Match";
} }
</script>
</html>

80
Output:

81
ASSIGNMENT 2
Program: Q1: Singly Linked List Program Using Java Script

class Node{

constructor(val){

this.val = val

this.next = null

class SinglyLinkedList{

constructor(){

this.head = null

this.tail = null

this.length = 0

insert(val)

let newNode=new Node(val)

if(!this.head)

this.head=newNode;

this.tail=this.head;

82
else

this.tail.next=newNode;

this.tail=newNode;

console.log(this);

this.length++;

return this;

Delete()

if(!this.head)

return undefined;

var current=this.head;

var newTail=current;

while(current.next)

newTail=current;

current=current.next;

this.tail=newTail;

this.tail.next=null;

this.length--;

console.log(this);
83
if(this.length==0)

this.head=null;

this.tail=null;

return this;

let sll=new SinglyLinkedList();

sll.insert(10);

sll.insert(20);

sll.insert(30);

console.log("After deletion");

sll.Delete();

console.log("After deletion");

sll.Delete();

sll.insert(40);

sll.insert(45);

Q 2: Doubly Linked List Program Using Java Script

84
class Node{

constructor(data){

this.data = data;//data

this.next = null;//refrencde to the previous node

this.next = null;//refrence to the next node

class DoublyLinkedList{

constructor(){

this.head = null;

this.tail = null;

this.length = 0;

insert(data)

const node = new Node(data);

if(!this.head)

this.head=node;

this.tail=node;

else

node.prev =this.tail;
85
this.tail.next=node;

this.tail=node;

this.length++;

console.log(this);

Delete()

if(!this.head)

return null;

//tail is the last node so that the we take previous property fromthe tail

const prevNode =this.tail.prev

if(prevNode)

prevNode.next = null;

this.tail =prevNode;//updating the tail

else{

//if prev property is null

//it means there is only sigle node

this.head= null;

this.tail=null;

this.length--;//decrement the lenght


86
console.log(this);

let dll=new DoublyLinkedList();

dll.insert(10);

dll.insert(20);

dll.insert(30);

console.log(" deletion operation");

dll.Delete();

console.log(" deletion operation");

dll.insert(40);

dll.insert(50);

dll.insert(60);

Output:

87
ASSIGNMENT 3
Q1: Stack with Array Using Java Script

class Stack1

constructor()

this.items = [];

add(element)

return this.items.push(element)

remove()

if(this.items.length > 0)

return this.items.pop();

peek()

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

isEmpty()

return this.items.length == 0;

size(){

return this.items.length;

clear()

this.items =[];

let s = new Stack1();

s.add(1);

s.add(2);

s.add(3);

s.add(4);

console.log(s.items);

s.remove();

console.log(s.items);

console.log(s.peek());

console.log(s.isEmpty());
89
console.log(s.size());

s.clear();

console.log(s.items);

Q 2: Queue With Array Using Java Script

class Queue

constructor()

this.items = [];

enqueue(element)

// adding element to the queue

this.items.push(element);

dequeue()

// removing element from the queue

// returns underflow when called

// on empty queue

if(this.isEmpty())

return "Underflow";

return this.items.shift();

}
90
front()

// returns the Front element of

// the queue without removing it.

if(this.isEmpty())

return "No elements in Queue";

return this.items[0];

isEmpty()

// return true if the queue is empty.

return this.items.length == 0;

printQueue()

var str = "";

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

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

return str;

var queue = new Queue();

console.log(queue.dequeue());

// returns true
91
console.log(queue.isEmpty());

// Adding elements to the queue

// queue contains [10, 20, 30, 40, 50]

queue.enqueue(10);

queue.enqueue(20);

queue.enqueue(30);

queue.enqueue(40);

queue.enqueue(50);

queue.enqueue(60);

// returns 10

console.log(queue.front());

// removes 10 from the queue

// queue contains [20, 30, 40, 50, 60]

console.log(queue.dequeue());

// returns 20

console.log(queue.front());

// removes 20

// queue contains [30, 40, 50, 60]

console.log(queue.dequeue());

// printing the elements of the queue

// prints [30, 40, 50, 60]

console.log(queue.printQueue());

92
ASSIGNMENT 4
Q1.Reverse The String in stack Using Array

let name =['Y' , 'a', 's' , 'h' , 'a' , 's' , 'h', 'r', 'i'];

var p=[];

var i;

let len =name.length;

for(i=0;i<len;i++)

p=p+name.pop()

console.log(p);

ASSIGNMENT 5

Q2.Balance the Parenthesis using stack

const fixParentheses = (str) =>

let orig = str;

while (str.includes("()"))

str = str.replace(/\(\)/g, '');

let amtOpeningParensNeeded = (str.match(/\)/g) || []).length;

let amtClosingParensNeeded = (str.match(/\(/g) || []).length;


93
return "(".repeat(amtOpeningParensNeeded) + orig +

")".repeat(amtClosingParensNeeded);

};

const test = input => { console.log(`Input: ${input}`);

console.log(`Output: ${fixParentheses(input)}`)};

test("(((A+B)*C/(D-E)*F)")

94
ASSIGNMENT 6
Q1.Stack implementation using linkedlist.
Function Node (data) {

this.data = data;

this. next = null;

function Stack () {

this. top= null;

Stack.prototype.push = function (data) {

var newNode = new Node (data);

newNode. next = this. top;

this. top= newNode;

Stack. prototype. pop= function () {

if ( this. top! == null) {

var topItem = this. top. data ;

this. top=this.top.next;

return topItem ;

return null;

Stack. prototype. print = function () {

var curr= this. top ;

While (curr) {

console. log ( curr.data);

95
curr = curr. next ;

var stack = new Stack ();

stack. push (3);

stack. push(4);

stack. push(6);

stack. print ()

ASSIGNMENT 7
Q2. Demonstrate Linear Queue and Circular Queue – Enqueue, Dequeu
function Queue (){

this. head = null;

this. tail= null;

Queue.prototype.enqueue= function (data) {

var newNode = new Node (data) ;

if( this. head ===null) {

this. head = newNode ;

this. tail = newNode ;

} else {

this. tail. next = newNode ;

this. tail = newNode ;

Queue. prototype. dequeue = function () {

var newNode ;

96
if( this.head !== null) {

newNode = this. head. data ;

this. head = this. head. next ;

return newNode ;

Queue. prototype. print = function () {

var curr = this. head ;

while (curr) {

console. log (curr. data) ;

curr = curr. next ;

var queue = new Queue ();

queue. enqueue (3);

queue. enqueue (5);

queue. enqueue (8);

queue. print ();

queue. dequeue ();

queue. print ();

97
ASSIGNMENT 8
Que:

<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;
98
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];


99
}

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();

console.log(priorityQueue.isEmpty());

console.log(priorityQueue.front());

priorityQueue.enqueue("Sumit", 2);

priorityQueue.enqueue("Gourav", 1);

priorityQueue.enqueue("Piyush", 1);

priorityQueue.enqueue("Ram", 2);

priorityQueue.enqueue("Suresh", 3);

console.log(priorityQueue.printPQueue());

console.log(priorityQueue.front().element);

console.log(priorityQueue.rear().element);
100
console.log(priorityQueue.dequeue().element);

priorityQueue.enqueue("Sunil", 2);

console.log(priorityQueue.printPQueue());

101
ASSIGNMENT 9
Reverse stack :

<script>

Stack=[];

Queue=[];

function enQueue(value)

Queue.push(value);

function deQueue()

let v1=Queue.shift()

Stack.push(v1);

Stack.push(23);

Stack.push(24);

Stack.push(25);

Stack.push(26);

Stack.push(27);

console.log(`before reverse ${Stack}`);

let len=Stack.length;

for(let i=0;i<len;i++)

{
102
enQueue(Stack.pop());

let lenq=Queue.length;

for(let i=0;i<lenq;i++)

deQueue();

console.log(`After reverse ${Stack}`);

</script>

ASSIGNMENT 10

Q1. Implement Binary Search Tree – Insert and search operation

class Node

constructor(data)

this.data = data;

this.left = null;

this.right = null;

103
class BinarySearchTree

constructor()

// root of a binary seach tree

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);
104
}

else

if(node.right === null)

node.right = newNode;

else

this.insertNode(node.right,newNode);

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);
105
BST.insert(7);

BST.insert(22);

BST.insert(17);

BST.insert(13);

BST.insert(5);

BST.insert(9);

BST.insert(27);}

ASSIGNMENT 11
Q1. Delete and traverse operation

class Node

constructor(data)

this.data = data;

this.left = null;

this.right = null;

class BinarySearchTree

constructor()

{
106
// root of a binary seach tree

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;
107
else

this.insertNode(node.right,newNode);

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;

remove(data)

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

removeNode(node, key)

if(node === null)

return null;

else if(key < node.data)


108
{

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;
109
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);

console.log(node.data);

this.inorder(node.right);

preorder(node)

if(node !== null)

console.log(node.data);

this.preorder(node.left);

this.preorder(node.right);
110
}

postorder(node)

if(node !== null)

this.postorder(node.left);

this.postorder(node.right);

console.log(node.data);

getRootNode()

return this.root;

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);
111
BST.insert(9);

BST.insert(27);

BST.inorder(root);

BST.remove(5);

BST.inorder(root);

BST.remove(7);

var root = BST.getRootNode();

console.log("inorder traversal");

BST.inorder(root);

console.log("postorder traversal");

BST.postorder(root);

console.log("preorder traversal");

BST.preorder(root);

112
ASSIGNMENT 12
Q1. Implement Graph –Depth First Search traversal.

1.Implement the graph – Depth first search traversal.


class Graph
{
constructor(noOfVertices)
{
this.noOfVertices = noOfVertices;
this.AdjList = new Map();
}

addVertex(v)
{
this.AdjList.set(v, []);
}
addEdge(v, w)
{
this.AdjList.get(v).push(w);
this.AdjList.get(w).push(v);
}
printGraph()
{

var get_keys = this.AdjList.keys(); for


(var i of get_keys)
{
var get_values = this.AdjList.get(i); var
conc = "";
for (var j of get_values)
conc += j + " ";
console.log(i + " -> " + conc);
}
}
dfs(startingNode)
113
{
var visited = {};
this.DFSUtil(startingNode, visited);
}
DFSUtil(vert, visited)
{
visited[vert] = true;
console.log(vert);
var get_neighbours = this.AdjList.get(vert); for
(var i in get_neighbours)
{
var get_elem = get_neighbours[i]; if (!
visited[get_elem])
this.DFSUtil(get_elem, visited);
}

} var g = new Graph(6);


var vertices = [ 'A', 'B', 'C', 'D', 'E', 'F' ];
for (var i = 0; i < vertices.length; i++)
{g.addVertex(vertices[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.printGraph();
console.log("DFS");
g.dfs ('A');

114
115
ASSIGNMENT 13
1.Implement Graph-Breadth first search traversal.
class Queue

{
constructor()

this.items = [];

}
enqueue(element)
{

return this.items.push(element);
}
isEmpty()

{
return this.items.length == 0;

dequeue()
{

if(this.items.length > 0)

{
return this.items.shift();

}
}
}

class Graph
{

116
constructor(noOfVertices)

this.noOfVertices = noOfVertices;
this.AdjList = new Map();
}

addVertex(v)
{

this.AdjList.set(v, []);
}
addEdge(v, w)

{
this.AdjList.get(v).push(w);
this.AdjList.get(w).push(v);
}
printGraph()
{

var get_keys = this.AdjList.keys(); for (var


i of get_keys)
{

var get_values = this.AdjList.get(i); var conc


= "";
for (var j of get_values) conc
+= j + " ";
console.log(i + " -> " + conc);

}
}

117
bfs(startingNode)

var visited = {};

var q = new Queue();


visited[startingNode] = true;
q.enqueue(startingNode); while (!
q.isEmpty()){
var getQueueElement = q.dequeue();
console.log(getQueueElement);
var get_List = this.AdjList.get(getQueueElement); for (var i in
get_List)

{
var neigh = get_List[i]; if (!
visited[neigh])

{
visited[neigh] = true;
q.enqueue(neigh);

}
}

}
var g = new Graph(6);
var vertices = [ 'A', 'B', 'C', 'D', 'E', 'F' ];

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


{

118
g.addVertex(vertices[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.printGraph();
console.log("BFS");
g.bfs('B');

119
ASSIGNMENT 14
Q1.Implement hash function using separate chaining method and linear
probing method.

<script>

class HashTable {

constructor() {

this.table = new Array(10);

this.values = [];

hash(string) { const H = 37;

let total = 0;

total =string % this.table.length;

if (total < 1) {

this.table.length -1

return parseInt(total);

showDistro() {

for (const key in this.table) {

if(this.table[key] !== undefined) {

console.log(key, ' : ', this.table[key])

120
} put(data) {

const pos = this.hash(data);

this.table[pos] = data;

get(key) {

return this.table[this.hash(key)];

class HashTableChains extends HashTable {

constructor() {

super();

this.buildChains();

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

this.table[i] = new Array();

showDistro() {

for (const key in this.table) {

if(this.table[key][0] !== undefined) {

document.write(key, ' : ', this.table[key]+"<br/>");

121
}

put(key, data) {

const pos = this.hash(key);

let index = 0;

if(this.table[pos][index] === undefined) { this.table[pos][index] = data;

} else {

++index;

while (this.table[pos][index] !== undefined ) {

index++;

this.table[pos][index] = data;

get(key) {

const pos = this.hash(key);

let index = 0;

while (this.table[pos][index] != key) {

if(this.table[pos][index] !== undefined) {

return this.table[pos][index]

} else { return undefined;

index++;

122
}

var input=[8,3,13,6,4,10];

let hTable= new HashTable();

let hTable1= new HashTableChains();

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

hTable.put(input[i]);

hTable.showDistro();var input1=[10,22,86,12,42,20];

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

hTable1.put(input1[i],input1[i]);

hTable1.showDistro();

</script>

Output :-

123
ASSIGNMENT 15
Q1.Implement Linear Search algorithm using brute force technique.

Program:-

<script>

function HashTable(size) {

this.size = size;

this.keys = this.initArray(size);

this.values = this.initArray(size);

this.limit = 0;

}HashTable.prototype.put = function (key, value) {

if (this.limit >= this.size) throw 'hash table is full'

var hashedIndex = this.hash(key);

while (this.keys[hashedIndex] != null) {

hashedIndex++;

hashedIndex = hashedIndex % this.size;

this.keys[hashedIndex] = key;

this.values[hashedIndex] = value;

this.limit++;

console.log(this.keys, this.values);

HashTable.prototype.get = function (key) {

124
var hashedIndex = this.hash(key); while (this.keys[hashedIndex] != key) {

hashedIndex++;

hashedIndex = hashedIndex % this.size;

return this.values[hashedIndex]

HashTable.prototype.hash = function (key) {

if (!Number.isInteger(key)) throw 'must be int';

return key % this.size;

HashTable.prototype.initArray = function (size) {

var array = []; for (var i = 0; i < size; i++) {

array.push(null);

return array;

HashTable.prototype.showDistro=function() {

for (const key in this.keys) {

if(this.keys[key] !== undefined) {

document.write(key, ' : ', this.values[key]+"<br/>");

125
var exampletable = new HashTable(10);

exampletable.put(38,38);

exampletable.put(19,19);exampletable.put(8,8);

exampletable.put(79,79);

exampletable.put(10,10);

exampletable.showDistro();

</script>

Output : -

3.Implement traveling salesman problem using brute force technique.

Program:

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++) {

126
generate(n-1, A);

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

generate(A.length, A);

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;

console.log(generatePermutations([1,2,3]));console.log(generrateCityRoutes([0,1,2,3]
));

127
ASSIGNMENT 16
Q1. Implement Prim’s algorithm using greedy technique

<script>

class MST {

// Number of vertices in the graph

// A utility function to find the vertex with minimum key

// value, from the set of vertices not yet included in MST

minKey(key,mstSet,MAX_VALUE)

// Initialize min value

let min = MAX_VALUE, min_index = -1;

for (let v = 0; v < V; v++)

if (mstSet[v] == false && key[v] < min) {

min = key[v];

min_index = v;

return min_index;

// A utility function to print the constructed MST stored in

// parent[]

printMST(parent,graph)

console.log("Edge Weight");

for (let i = 1; i < V; i++)

document.write(parent[i] + " - " + i + " :" + graph[i][parent[i]]+"<br/>");

128
// Function to construct and print MST for a graph represented

// using adjacency matrix representation

primMST(graph,V)

// Array to store constructed MST

let parent = new Array(V);

// Key values used to pick minimum weight edge in cut

let key = new Array(V);

// To represent set of vertices included in MST

let mstSet = new Array(V);

// Initialize all keys as INFINITE

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

key[i] = MAX_VALUE;

mstSet[i] = false;

// Always include first 1st vertex in MST.

key[0] = 0; // Make key 0 so that this vertex is

// picked as first vertex

parent[0] = -1; // First node is always root of MST

// The MST will have V vertices

for (let count = 0; count < V - 1; count++) {

// Pick thd minimum key vertex from the set of vertices

// not yet included in MST

let u = this.minKey(key, mstSet,MAX_VALUE);

// Add the picked vertex to the MST Set

mstSet[u] = true;

129
// Update key value and parent index of the adjacent

// vertices of the picked vertex. Consider only those

// vertices which are not yet included in MST

for (let z = 0; z < V; z++)

// let ans=graph[u][v];

// console.log(ans.charCodeAt());

// graph[u][v] is non zero only for adjacent vertices of m

// mstSet[v] is false for vertices not yet included in MS

// Update the key only if graph[u][v] is smaller than key[v]

if (graph[u][z] != 0 && mstSet[z] == false && graph[u][z] < key[z])

parent[z] = u;

key[z] = graph[u][z];

// print the constructed MST

this.printMST(parent, graph);

let t = new MST();

let graph = [ [ 0, 2, 5, 3],

[ 2, 0, 2, 0],

[ 5, 2, 0, 3],

[ 3, 0, 3, 0]];

let V=4, MAX_VALUE=99999;

// Print the solution

document.write("Following are the edges in the constructed MST:<br/>");

130
t.primMST(graph,V,MAX_VALUE);

</script>

ASSIGNMENT 17
Q2. Implement Kruskal’s algorithm using greedy technique
<script>

const MAX_INTEGER = Number.MAX_SAFE_INTEGER; // No edge

const MIN_INTEGER = Number.MIN_SAFE_INTEGER; // No self-loop

const matrix= [

[MIN_INTEGER, 2, 5, 3],

[2, MIN_INTEGER, 2, MIN_INTEGER],

[5, 2, MIN_INTEGER, 3],

[3, MIN_INTEGER, 3, MIN_INTEGER]

];

function Edge(begin, end, weight) {

this.begin = begin;

this.end = end;

this.weight = weight;

Edge.prototype.getBegin = function () {

return this.begin;

};

Edge.prototype.getEnd = function () {

return this.end;

};

Edge.prototype.getWeight = function () {

return this.weight;

131
};

function changeMatrixToEdgeArray(matrix) {

const rows = matrix.length,

cols = rows,

result = [];

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

const row = matrix[i];

for(let j = 0 ; j < cols; j++) {

if(row[j] !== MIN_INTEGER && row[j] !== MAX_INTEGER) {

result.push(new Edge(i, j, row[j]));

matrix[i][j] = MAX_INTEGER;

matrix[j][i] = MAX_INTEGER;

result.sort((a, b) => a.getWeight() - b.getWeight());

return result;

function kruskal(matrix) {

const edgeArray = changeMatrixToEdgeArray(matrix),

result = [],

savedEdge = new Array(matrix.length).fill(0);

for (let i = 0, len = edgeArray.length-2; i < len; i++) {

const edge = edgeArray[i];

const n = findEnd(savedEdge, edge.getBegin());

const m = findEnd(savedEdge, edge.getEnd());

132
document.write(savedEdge+"------"+n+"--"+ m+"---"+edge.getWeight());

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

if (n !== m) {

result.push(edge);

savedEdge[n] = m;

return result;

function findEnd(arr, start) {

while (arr[start] > 0) {

start = arr[start];

} return start;

var grp=new kruskal(matrix);

</script>

133
ASSIGNMENT 18
Q1. Implement binary search using divide and conquer

<html>

<body>

</body>

<script>

var num1= [1,2,3,4,5,6,7,8,9,10], target1 = 9;

binarySearch(num1,9);

function binarySearch(arr, target){

//start will be the first index

let start = 0

//end will be last index

let end = arr.length-1

//guess is typically middle of array

let guessIndex = Math.floor((end - start) / 2)

while(end > start){

console.log(start, end)

if (arr[guessIndex] === target){

console.log("found at index")

return(guessIndex)

} else if (arr[guessIndex] > target){

console.log("guess too big && guessIndex", guessIndex)

end = guessIndex;

guessIndex = Math.floor((end + start)/2) -1

} else if (arr[guessIndex] < target){

134
console.log("guess too small && guessIndex", guessIndex)

start = guessIndex;

guessIndex = Math.ceil((end + start)/2)

} else { return "NOT FOUND"}

</script>

</html>

Output:

135
ASSIGNMENT 19
<html>

<body>

<script>

'use strict';

stepsToSolveHanoiT(3,'A' , 'B' , 'C');

function stepsToSolveHanoiT(height, srcP, desP, bufferP) {

if (height >= 1) {

stepsToSolveHanoiT(height - 1, srcP, bufferP, desP);

console.log('Move disk from Tower ', srcP, ' to Tower ', desP);

stepsToSolveHanoiT(height - 1, bufferP, desP, srcP);

return;

</script>

</body></html>

Output:-

Move disk from Tower A to Tower B

ass19.html:15 Move disk from Tower A to Tower C

ass19.html:15 Move disk from Tower B to Tower C

ass19.html:15 Move disk from Tower A to Tower B

ass19.html:15 Move disk from Tower C to Tower A

ass19.html:15 Move disk from Tower C to Tower B

ass19.html:15 Move disk from Tower A to Tower B

136
ASSIGNMENT 22
<html>

<body>

<script>

var iterations = 0;

var print_board = function (columns) {

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

while (row < n) {

while (col < n) {

////process.stdout.write(columns[row] === col ? 'Q ' : '# ')

console.log(columns[row] === col ? 'Q ' : '# ')

col++

//process.stdout.write('\n')

console.log('\n')

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

137
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(5, 5))

console.log('\niterations: ', iterations)

</script>

</body>

</html>

138
Output: -

139

You might also like