Model Answer DAA
Model Answer DAA
It involves checking the logic, the inputs, the outputs, and the behavior of the
algorithm under different scenarios and conditions.
Ans :- :- The tightest upper bound that represents the number of swaps
required to sort n numbers using selection sort is O(n).
(O(n)) is represents the tightest upper bound for the number of swaps required
to sort n numbers using selection sort.
i. Liner problem.
ii. Optimization problem.
iii. Quadratic problem.
iv. Biquadratic problem.
DANDC (P)
{
if SMALL (P) then return S (p);
else
{
divide p into smaller instances p1, p2, …. Pk, k 1;
apply DANDC to each of these sub problems;
return (COMBINE (DANDC (p1) , DANDC (p2),…., DANDC
(pk));
}
}
Ans :-
Feasible solution :
A feasible solution is a set of values for the decision variables that satisfies all of
the constraints in an optimization problem. The set of all feasible solutions
defines the feasible region of the problem.
Optimal solution :
An optimal solution is a feasible solution where the objective function reaches its
maximum (or minimum) value.
The goal of code tuning is to enhance the program's execution speed, reduce its
memory usage, and generally optimize its resource utilization.
Q.2
a) Write short note on optimal merge pattern.
Ans :- Given n number of sorted files, the task is to find the minimum
computations done to reach the Optimal Merge Pattern.
When two or more sorted files are to be merged altogether to form a single file,
the minimum computations are done to reach this file are known as Optimal
Merge Pattern.
If more than 2 files need to be merged then it can be done in pairs. For
example, if need to merge 4 files A, B, C, D. First Merge A with B to get X1,
merge X1 with C to get X2, merge X2 with D to get X3 as the output file.
If we have two files of sizes m and n, the total computation time will be m+n.
Here, we use the greedy strategy by merging the two smallest size files among
all the files present.
Example :
After this, pick two smallest numbers and repeat this until we left with only one
number.
Step 1 : Insert 2, 3
Step 2 :
Step 3 : Insert 5
Step 4 : Insert 13
Step 5 : Insert 7 And 9
Step 6 :
Given a set of items with specific weights and values, the aim is to get as much
value into the knapsack as possible given the weight constraint of the knapsack.
This is a problem that has been studied for more than a century and is a
commonly used example problem in combinatorial optimization, where there is a
need for an optimal object or finite solution where an exhaustive search is not
possible.
The problem can be found real-world scenarios like resource allocation in
financial constraints or even in selecting investments and portfolios.
In the knapsack problem, the given items have two attributes at minimum – an
item’s value, which affects its importance, and an item’s weight or volume,
which is its limitation aspect.
Since an exhaustive search is not possible, one can break the problems into
smaller sub-problems and run it recursively. This is called an optimal sub-
structure. This deals with only one item at a time and the current weight still
available in the knapsack.
The problem solver only needs to decide whether to take the item or not based
on the weight that can still be accepted. However, if it is a program, re-
computation is not independent and would cause problems.
Q.3
a) Explain binary search? Write algorithm for it. Consider the following
elements of array A.
Index 1 2 3 4 5 6 7 8 9 10
Ans :-
Step 1 : Sort the given activities in ascending order according to their finishing
time.
Step 2 : Select the first activity from sorted array act[] and add it to sol[] array.
Step 4 : If the start time of the currently selected activity is greater than or
equal to the finish time of previously selected activity, then add it to
the sol[] array.
Q.4
a) What is minimum spanning tree ? Explain Kruskal’s algorithm with
following example.
Ans :-
A minimum spanning tree (MST) is defined as a spanning tree that has the
minimum weight among all the possible spanning trees
The minimum spanning tree has all the properties of a spanning tree with an
added constraint of having the minimum possible weights among all possible
spanning trees. Like a spanning tree, there can also be many possible MSTs for a
graph.
i. Sort all the edges in non-decreasing order of their weight.
ii. Pick the smallest edge. Check if it forms a cycle with the spanning tree
formed so far. If the cycle is not formed, include this edge. Else, discard
it.
iii. Repeat step#2 until there are (V-1) edges in the spanning tree.
The graph contains 9 vertices and 14 edges. So, the minimum spanning tree
formed will be having (9 – 1) = 8 edges.
After sorting :
Step 7 : Pick edge 7-8. Since including this edge results in the cycle, discard
it. Pick edge 0-7. No cycle is formed, include it.
Step 8 : Pick edge 1-2. Since including this edge results in the cycle, discard
it. Pick edge 3-4. No cycle is formed, include it.
Note : Since the number of edges included in the MST equals to (V – 1), so the
algorithm stops here
Q.5
a) Write a code to design login form (user name and password) and also
check valid user.
Ans :-
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginFrame extends JFrame implements ActionListener
{
Container container = getContentPane();
JLabel userLabel = new JLabel("USERNAME");
JLabel passwordLabel = new JLabel("PASSWORD");
JTextField userTextField = new JTextField();
JPasswordField passwordField = new JPasswordField();
JButton loginButton = new JButton("LOGIN");
JButton resetButton = new JButton("RESET");
JCheckBox showPassword = new JCheckBox("Show Password");
LoginFrame()
{
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
}
public void setLayoutManager()
{
container.setLayout(null);
}
public void setLocationAndSize()
{
userLabel.setBounds(50, 150, 100, 30);
passwordLabel.setBounds(50, 220, 100, 30);
userTextField.setBounds(150, 150, 150, 30);
passwordField.setBounds(150, 220, 150, 30);
showPassword.setBounds(150, 250, 150, 30);
loginButton.setBounds(50, 300, 100, 30);
resetButton.setBounds(200, 300, 100, 30);
}
public void addComponentsToContainer()
{
container.add(userLabel);
container.add(passwordLabel);
container.add(userTextField);
container.add(passwordField);
container.add(showPassword);
container.add(loginButton);
container.add(resetButton);
}
public void addActionEvent()
{
loginButton.addActionListener(this);
resetButton.addActionListener(this);
showPassword.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == loginButton)
{
String userText;
String pwdText;
userText = userTextField.getText();
pwdText = passwordField.getText();
if (userText.equalsIgnoreCase("Rajpardeshi") &&
pwdText.equalsIgnoreCase("2231"))
{
JOptionPane.showMessageDialog(this, "Login Successful");
}
Else
{
JOptionPane.showMessageDialog(this, "Invalid Username or
Password");
}
}
if (e.getSource() == resetButton)
{
userTextField.setText("");
passwordField.setText("");
}
if (e.getSource() == showPassword)
{
if (showPassword.isSelected())
{
passwordField.setEchoChar((char) 0);
}
Else
{
passwordField.setEchoChar('*');
}
}
}
}
public class Login
{
public static void main(String[] a)
{
LoginFrame frame = new LoginFrame();
frame.setTitle("Login Form");
frame.setVisible(true);
frame.setBounds(10, 10, 370, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
}
}
Ans :- JList A component that displays a list of objects and allows the user to
select one or more items. A separate model, ListModel , maintains the contents
of the list. A ListModel can be supplied directly to a JList by way of a constructor
or the setModel method.
The object of JList class represents a list of text items. The list of text items can
be set up so that the user can choose either one item or multiple items. It
inherits JComponent class.
JList( ) : This Constructor in the JList class will create a List with a read-
only, empty, model.
JList( Array[ ] list data ) : This Constructor in the JList class will create
a list that will display the elements from the array specified within the
parameter.
JList( ListModel<Array> data model ) : This Constructor in the JList
class will create a list that will display the elements from the specified, no-
null, model.
JList( Vector <?> list data ) : This Constructor in the JList class will
create a list that will display the elements from the vector specified within
the parameter.
Example :
import javax.swing.*;
public class ListExample
{
ListExample()
{
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
}
Ans :- The JSP engine compiles the servlet into an executable class and
forwards the original request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and
executes it. During execution, the servlet produces an output in HTML format.
Ans :- A session bean represents a single client inside the Application Server. To
access an application that is deployed on the server, the client invokes the
session bean's methods.
The session bean performs work for its client, shielding the client from
complexity by executing business tasks inside the server.
Because the first software module performs the role of the client, and the
second, the role of the server, this mode is also referred to as client/server
interaction.
Ans :- web. xml defines mappings between URL paths and the servlets that
handle requests with those paths.
The web server uses this configuration to identify the servlet to handle a given
request and call the class method that corresponds to the request method.
Q.7
a) Describe servlet life cycle.
Ans :- The web container maintains the life cycle of a servlet instance.
As displayed in the above diagram, there are three states of a servlet: new,
ready and end. The servlet is in new state if servlet instance is created. After
invoking the init() method, Servlet comes in the ready state. In the ready state,
servlet performs all the tasks. When the web container invokes the destroy()
method, it shifts to the end state.
The web container calls the init method only once after creating the servlet instance. Th
method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Se
interface. Syntax of the init method is given below:
Ans :-
Forward() SendRedirect()
Q.8
a) Explain Custom tags of JSP.
Ans :- Custom tags are user-defined action tags that can be used within Java
Server Pages. A tag handler is associated with each tag to implement the
operations.
Therefore, it separates the business logic from JSP and helps avoid the use of
scriptlet tags.
The scriptlet tag embeds java code inside the JSP page itself rendering the page
difficult to understand therefore, it is better to avoid the use of scriptlet.
There are two ways to use the custom tag. They are given below:
1. Tag Handler :
It is a file saved with a .tld extension that contains a set of related tags mapped
to their respective tag handlers along with their description such as the name of
the tag, attributes of the tag, etc. The root tag of the TLD document is <taglib>
in which multiple tags can be encapsulated using <tag> tag. It is stored inside
the WEB-INF folder.
3. Taglib Directive :
Taglib directive is used to access a particular tag library within a JSP. It specifies
the URI of the tag library and its prefix.
Syntax:
b) How to create session in JSP? How to access it? Write a sample code.
For all these purposes, the JSP provides the "session implicit object". In this
chapter, you will learn about various methods and concepts used to create and
manage a session using JSP.
A session can be defined as an object associated with each user with a unique
session ID, and the user's data is based on the account they have registered.
Different forms of data can be set in a session;
These data related to each user of the site help the user and the website owner
in different ways. As you know, HTTP is a "stateless" protocol; Whenever a user
visits a web page, the user opens a separate connection with the webserver, and
the server does not keep a record of preceding client requests.
1. Creating a Session :
Implicitly : A session is created automatically when a user accesses a
JSP page for the first time.
Explicitly : Use the HttpSession object in a servlet or JSP page :
HttpSession session = request.getSession();
Q.9
a) Design a login form. Write a servlet to retrieve form values an display
whether user is valid or not.
Ans :-
b) Explain request and response implicit objects of JSP with any its two
methods.
Ans :-
Request :
o The request object is an instance of java.servlet.http.HttpServletRequest
and it is one of the argument of service method.
o It will be created by container for every request.
o It will be used to request the information like parameter, header
information , server name, etc.
o It uses getParameter() to access the request parameter.
o The request object provides methods to get the HTTP header information
including form data, cookies, HTTP methods etc.
o We can cover a complete set of methods associated with the request
object in a subsequent chapter − JSP - Client Request.
Commonly used methods :
o getParameter(String name) : Retrieves the value of a form parameter
or query string parameter.
Example: String userName = request.getParameter("username");
o getHeader(String name) : Retrieves the value of an HTTP header.
Example: String userAgent = request.getHeader("User-Agent");
Response :
o “Response” is an instance of class which implements HttpServletResponse
interface.
o Container generates this object and passes to _jspservice() method as
parameter.
o “Response object” will be created by the container for each request.
o It represents the response that can be given to the client.
o The response implicit object is used to content type, add cookie and
redirect to response page.
o The response object also defines the interfaces that deal with creating
new HTTP headers. Through this object the JSP programmer can add new
cookies or date stamps, HTTP status codes, etc.
o We will cover a complete set of methods associated with the response
object in a subsequent chapter − JSP - Server Response.
Commonly used methods :
o setContentType(String type) : Sets the content type of the response
(e.g., "text/html", "application/json").
Example: response.setContentType("text/html");
o sendRedirect(String url) : Redirects the client to another URL.
Example: response.sendRedirect("welcome.jsp");
Q.10
a) Explain the life cycle of enterprise bean.
Ans :-
The Life Cycles of Enterprise Beans : An enterprise bean goes through
various stages during its lifetime, or life cycle. Each type of enterprise
bean--session, entity, or message-driven--has a different life cycle.
The stages that a session bean passes through during its lifetime. The client
initiates the life cycle by invoking the create method. The EJB container
instantiates the bean and then invokes.
The setSessionContext and ejbCreate methods in the session bean. The bean is
now ready to have its business methods invoked.
The stages that an entity bean passes through during its lifetime. After the EJB
container creates the instance, it calls the setEntityContext method of the entity
bean class. The setEntityContext method passes the entity context to the bean.
After instantiation, the entity bean moves to a pool of available instances. While
in the pooled stage, the instance is not associated with any particular EJB object
identity. All instances in the pool are identical. The EJB container assigns an
identity to an instance when moving it to the ready stage.
3. The Life Cycle of a Message-Driven Bean :
At the end of the life cycle, the container calls the ejbRemove method. The
bean's instance is then ready for garbage collection.
Ans :-
Message Driven Bean :
A message driven bean (MDB) is a bean that contains business logic. But, it is
invoked by passing the message. So, it is like JMS Receiver.
A message driven bean receives message from queue or topic, so you must have
the knowledge of JMS API.
The messages can be sent by any Java EE component (an application client,
another enterprise bean, or a web component) or by a JMS application or system
that does not use Java EE technology. Message-driven beans can process JMS
messages or other kinds of messages.
In eclipse ide, create EJB Project then create a class as given below:
package com.javatpoint;
import javax.ejb.MessageDriven;
import javax.jms.*;
@MessageDriven(mappedName="myTopic")
public class MyListener implements MessageListener{
@Override
public void onMessage(Message msg) {
TextMessage m=(TextMessage)msg;
try{
System.out.println("message received: "+m.getText());
}catch(Exception e){System.out.println(e);}
}
}