In Sem 1 Key - Set 1 - AOOP - 21CS2116AA-16-38

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

10.

Methods in Sets and Maps interface : (8 Marks)


Evaluation:
4 marks for write any four methods in Sets with sample code and 4 marks for
write any 8 methods in maps with sample code: total 8 marks
Sets:
A Set is a Collection that cannot contain duplicate elements.
The methods declared by Set are summarized in the following table −

Sr.No. Method & Description

1 add( ) Adds an object to the collection.

2
clear( ) Removes all objects from the collection.

3 contains( ) Returns true if a specified object is an element within the collection.

4 isEmpty( ) Returns true if the collection has no elements.

5 iterator( ) Returns an Iterator object for the collection, which may be used to
retrieve an object.

6 remove( ) Removes a specified object from the collection.

7 size( ) Returns the number of elements in the collection.

Example

Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. Following
is an example to explain Set functionality

import java.util.*;
public class SetDemo {

public static void main(String args[]) {


int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try {
for(int i = 0; i < 5; i++) {
set.add(count[i]);
}
System.out.println(set);

TreeSet sortedSet = new TreeSet<Integer>(set);


System.out.println("The sorted list is:");
System.out.println(sortedSet);

System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());


System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
}
catch(Exception e) {}
}
}
This will produce the following result −

Output

[34, 22, 10, 60, 30]


The sorted list is:
[10, 22, 30, 34, 60]
The First element of the set is: 10
The last element of the set is: 60

Maps:
The map interface is present in java.util package represents a mapping between a key and a
value.

Method Action Performed

This method is used to clear and remove all of the


clear()
elements or mappings from a specified Map collection.

This method is used to check whether a particular key


is being mapped into the Map or not. It takes the key
containsKey(Object)
element as a parameter and returns True if that
element is mapped in the map.

This method is used to check whether a particular value


is being mapped by a single or more than one key in
containsValue(Object) the Map. It takes the value as a parameter and returns
True if that value is mapped by any of the key in the
map.
Method Action Performed

This method is used to create a set out of the same


elements contained in the map. It basically returns a
entrySet()
set view of the map or we can create a new set and
store the map elements into them.

This method is used to check for equality between two


maps. It verifies whether the elements of one map
equals(Object)
passed as a parameter is equal to the elements of this
map or not.

This method is used to retrieve or fetch the value


mapped by a particular key mentioned in the
get(Object)
parameter. It returns NULL when the map contains no
such mapping for the key.

This method is used to generate a hashCode for the


hashCode()
given map containing keys and values.

This method is used to check if a map is having any


isEmpty() entry for key and value pairs. If no mapping exists, then
this returns true.

This method is used to return a Set view of the keys


contained in this map. The set is backed by the map, so
keySet()
changes to the map are reflected in the set, and vice-
versa.

This method is used to associate the specified value


put(Object, Object)
with the specified key in this map.

This method is used to copy all of the mappings from


putAll(Map)
the specified map to this map.

This method is used to remove the mapping for a key


remove(Object)
from this map if it is present in the map.

This method is used to return the number of key/value


size()
pairs available in the map.

This method is used to create a collection out of the


values() values of the map. It basically returns a Collection view
of the values in the HashMap.
Method Action Performed

Returns the value to which the specified key is mapped,


getOrDefault(Object key, V
or defaultValue if this map contains no mapping for the
defaultValue)
key.

merge(K key, V value, If the specified key is not already associated with a
BiFunction<? super V,? super V,? value or is associated with null, associates it with the
extends V> remappingFunction) given non-null value.

If the specified key is not already associated with a


value (or is mapped to null) associates it with the given
putIfAbsent(K key, V value)
value and returns null, else returns the
curassociaterent value.

Sample program:

public class GFG {

public static void main(String[] args)


{
Map<String, Integer> map = new HashMap<>();
map.put("vishal", 10);
map.put("sachin", 30);
map.put("vaibhav", 20);

for (Map.Entry<String, Integer> e : map.entrySet())


System.out.println(e.getKey() + " "
+ e.getValue());
}
}

Output
vaibhav 20
vishal 10
sachin 30

11 . AVL tree : (12.5 Marks)


Evaluation:
6 .5 marks for draw balancing AVL tree with given elements
6 Marks for Algorithm(Procedure) AVL tree Rotations:
Algorithm:

Let the newly inserted node be w

• Perform standard BST insert for w.


• Starting from w, travel up and find the first unbalanced node. Let z be the first
unbalanced node, y be the child of z that comes on the path from w to z and x be the
grandchild of z that comes on the path from w to z.
• Re-balance the tree by performing appropriate rotations on the subtree rooted with
z. There can be 4 possible cases that need to be handled as x, y and z can be
arranged in 4 ways.
• Following are the possible 4 arrangements:
o y is the left child of z and x is the left child of y (Left Left Case)
o y is the left child of z and x is the right child of y (Left Right Case)
o y is the right child of z and x is the right child of y (Right Right Case)
o y is the right child of z and x is the left child of y (Right Left Case)

Following are the operations to be performed in above mentioned 4 cases. In all of the
cases, we only need to re-balance the subtree rooted with z and the complete tree becomes
balanced as the height of the subtree (After appropriate rotations) rooted with z becomes
the same as it was before insertion.

Follow the steps mentioned below to implement the idea:

• Perform the normal BST insertion.


• The current node must be one of the ancestors of the newly inserted node. Update
the height of the current node.
• Get the balance factor (left subtree height – right subtree height) of the current
node.
• If the balance factor is greater than 1, then the current node is unbalanced and we
are either in the Left Left case or left Right case. To check whether it is left left case
or not, compare the newly inserted key with the key in the left subtree root.
• If the balance factor is less than -1, then the current node is unbalanced and we are
either in the Right Right case or Right-Left case. To check whether it is the Right Right
case or not, compare the newly inserted key with the key in the right subtree
root.

1. Left Left Case

T1, T2, T3 and T4 are subtrees.


z y
/\ / \
y T4 Right Rotate (z) x z
/\ - - - - - - - - -> / \ / \
x T3 T1 T2 T3 T4
/\
T1 T2
2. Left Right Case

z z x
/\ / \ / \
y T4 Left Rotate (y) x T4 Right Rotate(z) y z
/ \ - - - - - - - - -> / \ - - - - - - - -> / \ / \
T1 x y T3 T1 T2 T3 T4
/\ /\
T2 T3 T1 T2

3. Right Right Case

z y
/ \ / \
T1 y Left Rotate(z) z x
/ \ - - - - - - - -> / \ / \
T2 x T1 T2 T3 T4
/\
T3 T4

4. Right Left Case

z z x
/\ /\ / \
T1 y Right Rotate (y) T1 x Left Rotate(z) z y
/ \ - - - - - - - - -> / \ - - - - - - - -> / \ / \
x T4 T2 y T1 T2 T3 T4
/\ / \
T2 T3 T3 T4

12. Graph (12.5 Marks)


Evaluation:
4 marks for graph definition (1 mark) and representation (3marks):
8.5 marks for any two of following graph related algorithms (BFS, DFS, Prims,
Kruskal, Shortest path Algorithms
Graph Def: A graph is a data structure that stores connected data. In other words, a graph G
(or g) is defined as a set of vertices (V) and edges (E) that connects vertices.
Graph Representation (Visualization):
Kruskal Algorithm Java

Kruskal algorithm is another most important algorithm used for Minimum Spanning Tree.
MST is a spanning tree having a weight less than or equal to the weight of every spanning
tree.

Kruskal algorithm in Java takes a connected and undirected graph and returns the Minimum
Spanning Tree of it. The given diagram defines the working of Kruskal's algorithm.

These are the following steps that we use to implement Kruskal's algorithm:

1. Take connected and undirected graph from the user.


2. We then sort all the edges from low weight to high weight.
3. Take the edge with the lowest weight and add it to the spanning tree. If adding the
edge created a cycle, then reject this edge.
4. Keep adding edges until we reach all vertices.
Prim's algorithm Java

Prim's algorithm in Java is one of the most used algorithms for Minimum Spanning Tree

. Prim's algorithm starts with a spanning tree having no vertices. In prim's algorithm, we
maintain two sets of vertices in which first contains those vertices that are present in the
MSP and the second one contains those vertices that are not present in the MSP.

At each step, it considers all edges that combine the two sets and selects the minimum
weight edge from these edges. After selecting an edge, it sets the other end of the edge that
contains the MST.

Prim's Algorithm

• Create any collection that contains only unique elements keeps track of vertices
already included in MST.
• For all the vertices of the input graph, assign a key-value pair and set the value to
infinite. In order to pick the first vertex, we set its key value as 0.
• Select a vertex u that is not present in the setOfMST and having a minimum key
value.
• Add vertex u to the setOfMST.
• Change the key value of all adjacent vertices of u.

Note: In order to update the key-value of the adjacent vertices v, if the weight of edge u-v is
less than the previous key value of v, change the key value as the weight of u-v.

• Repeat steps 3, 4, and 5 until the setOfMST doesn't contain all vertices.

Travelling Salesman Problem:The traveling salesman problems abide by a salesman and a


set of cities. The salesman has to visit every one of the cities starting from a certain one
(e.g., the hometown) and to return to the same city. The challenge of the problem is that
the traveling salesman needs to minimize the total length of the trip.

• Suppose the cities are x1 x2..... xn where cost cij denotes the cost of travelling from
city xi to xj. The travelling salesperson problem is to find a route starting and ending
at x1 that will take in all cities with the minimum cost.
• Example: A newspaper agent daily drops the newspaper to the area assigned in such
a manner that he has to cover all the houses in the respective area with minimum
travel cost. Compute the minimum travel cost.


• Solution: The cost- adjacency matrix of graph G is as follows:
• costij =

• The tour starts from area H1 and then select the minimum cost area reachable from
H1


• Mark area H6 because it is the minimum cost area reachable from H1 and then select
minimum cost area reachable from H6.


• Mark area H7 because it is the minimum cost area reachable from H6 and then select
minimum cost area reachable from H7.






• Mark area H8 because it is the minimum cost area reachable from H8.


• Mark area H5 because it is the minimum cost area reachable from H5.

• Mark area H2 because it is the minimum cost area reachable from H2.


• Mark area H3 because it is the minimum cost area reachable from H3.


• Mark area H4 and then select the minimum cost area reachable from H4 it is H1.So,
using the greedy strategy, we get the following.
• 4 3 2 4 3 2 1 6
• H1 → H6 → H7 → H8 → H5 → H2 → H3 → H4 → H1.

• Thus the minimum travel cost = 4 + 3 + 2 + 4 + 3 + 2 + 1 + 6 = 25

You might also like