[go: up one dir, main page]

0% found this document useful (0 votes)
8 views116 pages

DSA Part-1

The document provides an overview of data structures, specifically focusing on arrays and linked lists. It includes code examples for inserting, deleting, and displaying elements in both arrays and linked lists, as well as searching for elements in a linked list. The document serves as a practical guide for implementing these data structures in programming.

Uploaded by

datascience9029
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views116 pages

DSA Part-1

The document provides an overview of data structures, specifically focusing on arrays and linked lists. It includes code examples for inserting, deleting, and displaying elements in both arrays and linked lists, as well as searching for elements in a linked list. The document serves as a practical guide for implementing these data structures in programming.

Uploaded by

datascience9029
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 116

*DATASTRUCTURES AND ALGORITHMS*

=============================
*DAY 1*
-------------
*ARRAYS*
------------------------
1. *INSERTING AN ELEMENT IN AN ARRAY TRYOUT*
---------
class ArrayTest {

public static void insert(char[] ar, int pos, char val){


//Traversing the array from the last position to the position where the element has to
be inserted
for(int i=ar.length-1;i>=pos;i--){
//Moving each element one position to its right
ar[i]=ar[i-1];
}

//Inserting the data at the specified position


ar[pos-1]=val;
}
}

class Tester{

public static void main(String args[]){


char arr[]=new char[6];
arr[0]='A';
arr[1]='B';
arr[2]='C';
arr[3]='D';
arr[4]='E';

//Make changes and try to insert elements at different positions


ArrayTest.insert(arr, 3, 'J');
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}

}
-------------------
2. *DELETING AN ELEMENT IN AN ARRAY- TRYOUT*
class ArrayTest {
public static void delete(char[] ar, int pos){
//Traversing the array from the position where the element has to be deleted to the
end
for(int i=pos-1;i<ar.length-1;i++){
//Moving each element one position to the left
ar[i]=ar[i+1];
}

//The space that is left at the end is filled with character '0'
ar[ar.length-1]='0';
}
}

class Tester{
public static void main(String args[]){
char arr[]=new char[6];
arr[0]='A';
arr[1]='B';
arr[2]='J';
arr[3]='C';
arr[4]='D';
arr[5]='E';

//Make changes and try to delete elements from different positions


ArrayTest.delete(arr, 3);
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}

}
---------------------
*LINKED LIST*
-----------------------
1. *ADDING AN ELEMENT TO A LINKED LIST(AT END)*/CREATE LIST
class Node {
private String data;
private Node next;

public Node(String data){


this.data=data;
}
public void setData(String data){
this.data = data;
}
public void setNext(Node node){
this.next = node;
}
public String getData(){
return this.data;
}
public Node getNext(){
return this.next;
}
}

class LinkedList {

private Node head;


private Node tail;

public Node getHead(){


return this.head;
}
public Node getTail(){
return this.tail;
}
public void addAtEnd(String data){
//Create a new node
Node node = new Node(data);

//Check if the list is empty,


//if yes, make the node as the head and the tail
if(this.head == null)
this.head=this.tail=node;
else{
//If the list is not empty, add the element at the end
this.tail.setNext(node);
//Make the new node as the tail
this.tail=node;
}

}
}

class Tester{
public static void main(String args[]){
LinkedList list = new LinkedList();
list.addAtEnd("Milan");
list.addAtEnd("Venice");
list.addAtEnd("Munich");
list.addAtEnd("Vienna");
System.out.println("Adding an element to the linked list");
}
}
-----------------------
2. *ADDING AN ELEMENT AT THE BEGINNING-TRYOUT*
class Node {
private String data;
private Node next;

public Node(String data){


this.data=data;
}
public void setData(String data){
this.data = data;
}
public void setNext(Node node){
this.next = node;
}
public String getData(){
return this.data;
}
public Node getNext(){
return this.next;
}
}

class LinkedList {

private Node head;


private Node tail;

public Node getHead(){


return this.head;
}
public Node getTail(){
return this.tail;
}
public void addAtEnd(String data){
//Create a new node
Node node = new Node(data);

//Check if the list is empty,


//if yes, make the node as the head and the tail
if(this.head == null)
this.head=this.tail=node;
else{
//If the list is not empty, add the element at the end
this.tail.setNext(node);
//Make the new node as the tail
this.tail=node;
}

public void addAtBeginning(String data){


//Implement your code here
Node node = new Node(data);
if(this.head == null)
this.head=this.tail=node;
else{
Node temp=head;
this.head=node;
this.head.setNext(temp);
}
}

class Tester{

public static void main(String args[]){


LinkedList list = new LinkedList();
list.addAtEnd("Milan");
list.addAtEnd("Venice");
list.addAtEnd("Munich");
list.addAtBeginning("Nice");
}
}
-------------------
3. *DISPLAYING A LINKED LIST*
class Node {
private String data;
private Node next;

public Node(String data) {


this.data = data;
}

public void setData(String data) {


this.data = data;
}

public void setNext(Node node) {


this.next = node;
}

public String getData() {


return this.data;
}

public Node getNext() {


return this.next;
}
}

class LinkedList {

private Node head;


private Node tail;

public Node getHead() {


return this.head;
}

public Node getTail() {


return this.tail;
}

public void addAtEnd(String data) {


// Create a new node
Node node = new Node(data);
// Check if the list is empty,
// if yes, make the node as the head and the tail
if (this.head == null)
this.head = this.tail = node;
else {
// If the list is not empty, add the element at the end
this.tail.setNext(node);
// Make the new node as the tail
this.tail = node;
}
}

public void addAtBeginning(String data) {


// Create a new node
Node node = new Node(data);

// Check if the list is empty,


// if yes, make the node as the head and the tail
if (this.head == null)
this.head = this.tail = node;
else {
// If the list is not empty, add the element at the beginning
node.setNext(this.head);
// Make the new node as the head
this.head = node;
}
}

public void display() {


// Initialize temp to the head node
Node temp = this.head;
// Traverse the list and print data of each node
while (temp != null) {
System.out.println(temp.getData());
temp = temp.getNext();
}
}

public static void main(String args[]) {


LinkedList list = new LinkedList();
list.addAtEnd("Milan");
list.addAtEnd("Venice");
list.addAtEnd("Munich");
list.addAtEnd("Vienna");
list.display();
}
}
--------------------
4. *SEARCHING FOR AN ELEMENT IN A LINKED LIST*
class Node {
private String data;
private Node next;

public Node(String data) {


this.data = data;
}

public void setData(String data) {


this.data = data;
}

public void setNext(Node node) {


this.next = node;
}

public String getData() {


return this.data;
}

public Node getNext() {


return this.next;
}
}

class LinkedList {

private Node head;


private Node tail;

public Node getHead() {


return this.head;
}

public Node getTail() {


return this.tail;
}
public void addAtEnd(String data) {
// Create a new node
Node node = new Node(data);

// Check if the list is empty,


// if yes, make the node as the head and the tail
if (this.head == null)
this.head = this.tail = node;
else {
// If the list is not empty, add the element at the end
this.tail.setNext(node);
// Make the new node as the tail
this.tail = node;
}

public void addAtBeginning(String data) {


// Create a new node
Node node = new Node(data);

// Check if the list is empty,


// if yes, make the node as the head and the tail
if (this.head == null)
this.head = this.tail = node;
else {
// If the list is not empty, add the element at the beginning
node.setNext(this.head);
// Make the new node as the head
this.head = node;
}

public void display() {


// Initialize temp to the head node
Node temp = this.head;
// Traverse the list and print data of each node
while (temp != null) {
System.out.println(temp.getData());
temp = temp.getNext();
}
}

public Node find(String data) {


Node temp = this.head;
// Traverse the list and return the node
// if the data of it matches with the searched data
while (temp != null) {
if (temp.getData().equals(data))
return temp;
temp = temp.getNext();
}
return null;
}

public static void main(String args[]) {


LinkedList list = new LinkedList();
list.addAtEnd("Milan");
list.addAtEnd("Venice");
list.addAtEnd("Munich");
list.addAtEnd("Vienna");
list.display();

if (list.find("Munich") != null)
System.out.println("Node found");
else
System.out.println("Node not found");
}
}
-----------------
5. *INSERTING AN ELEMENT IN A LINKED LIST*
class Node {
private String data;
private Node next;

public Node(String data) {


this.data = data;
}

public void setData(String data) {


this.data = data;
}

public void setNext(Node node) {


this.next = node;
}

public String getData() {


return this.data;
}

public Node getNext() {


return this.next;
}
}

class LinkedList {

private Node head;


private Node tail;

public Node getHead() {


return this.head;
}

public Node getTail() {


return this.tail;
}

public void addAtEnd(String data) {


// Create a new node
Node node = new Node(data);

// Check if the list is empty,


// if yes, make the node as the head and the tail
if (this.head == null)
this.head = this.tail = node;
else {
// If the list is not empty, add the element at the end
this.tail.setNext(node);
// Make the new node as the tail
this.tail = node;
}

public void addAtBeginning(String data) {


// Create a new node
Node node = new Node(data);

// Check if the list is empty,


// if yes, make the node as the head and the tail
if (this.head == null)
this.head = this.tail = node;
else {
// If the list is not empty, add the element at the beginning
node.setNext(this.head);
// Make the new node as the head
this.head = node;
}

public void display() {


// Initialize temp to the head node
Node temp = this.head;
// Traverse the list and print data of each node
while (temp != null) {
System.out.println(temp.getData());
temp = temp.getNext();
}
}

public Node find(String data) {


Node temp = this.head;
// Traverse the list and return the node
// if the data of it matches with the searched data
while (temp != null) {
if (temp.getData().equals(data))
return temp;
temp = temp.getNext();
}
return null;
}

public void insert(String data, String dataBefore) {


Node node = new Node(data);
// Check if the list is empty,
// if yes, make the node as the head and the tail
if (this.head == null)
this.head = this.tail = node;
else {
// Find the node after which the data has to be inserted
Node nodeBefore = this.find(dataBefore);
if (nodeBefore != null) {
// Insert the new node after nodeBefore
node.setNext(nodeBefore.getNext());
nodeBefore.setNext(node);
// If nodeBefore is currently the tail node,
// make the new node as the tail node
if (nodeBefore == this.tail)
this.tail = node;
} else
System.out.println("Node not found");
}
}

public static void main(String args[]) {


LinkedList list = new LinkedList();
list.addAtEnd("Milan");
list.addAtEnd("Venice");
list.addAtEnd("Munich");
list.addAtEnd("Vienna");
list.insert("Prague", "Munich");
list.display();

}
}
----------------
6. *DELETING AN ELEMENT FROM LINKED LIST*
class Node {
private String data;
private Node next;

public Node(String data) {


this.data = data;
}

public void setData(String data) {


this.data = data;
}

public void setNext(Node node) {


this.next = node;
}

public String getData() {


return this.data;
}

public Node getNext() {


return this.next;
}
}

class LinkedList {

private Node head;


private Node tail;

public Node getHead() {


return this.head;
}

public Node getTail() {


return this.tail;
}

public void addAtEnd(String data) {


// Create a new node
Node node = new Node(data);

// Check if the list is empty,


// if yes, make the node as the head and the tail
if (this.head == null)
this.head = this.tail = node;
else {
// If the list is not empty, add the element at the end
this.tail.setNext(node);
// Make the new node as the tail
this.tail = node;
}

public void addAtBeginning(String data) {


// Create a new node
Node node = new Node(data);

// Check if the list is empty,


// if yes, make the node as the head and the tail
if (this.head == null)
this.head = this.tail = node;
else {
// If the list is not empty, add the element at the beginning
node.setNext(this.head);
// Make the new node as the head
this.head = node;
}

public void display() {


// Initialize temp to the head node
Node temp = this.head;
// Traverse the list and print data of each node
while (temp != null) {
System.out.println(temp.getData());
temp = temp.getNext();
}
}

public Node find(String data) {


Node temp = this.head;
// Traverse the list and return the node
// if the data of it matches with the searched data
while (temp != null) {
if (temp.getData().equals(data))
return temp;
temp = temp.getNext();
}
return null;
}

public void insert(String data, String dataBefore) {


Node node = new Node(data);
// Check if the list is empty,
// if yes, make the node as the head and the tail
if (this.head == null)
this.head = this.tail = node;
else {
// Find the node after which the data has to be inserted
Node nodeBefore = this.find(dataBefore);
if (nodeBefore != null) {
// Insert the new node after nodeBefore
node.setNext(nodeBefore.getNext());
nodeBefore.setNext(node);
// If nodeBefore is currently the tail node,
// make the new node as the tail node
if (nodeBefore == this.tail)
this.tail = node;
} else
System.out.println("Node not found");
}
}

public void delete(String data) {


// Check if the list is empty,
// if yes, make the node as the head and the tail
if (this.head == null)
System.out.println("List is empty");
else {
// Find the node to be deleted
Node node = this.find(data);
// If the node is not found
if (node == null)
System.out.println("Node not found");
// If the node to be deleted is the head node
else if (node == this.head) {
this.head = this.head.getNext();
node.setNext(null);
// If the node to be deleted is also the tail node
if (node == this.tail)
tail = null;
} else {
// Traverse to the node present before the node to be deleted
Node nodeBefore = null;
Node temp = this.head;
while (temp != null) {
if (temp.getNext() == node) {
nodeBefore = temp;
break;
}
temp = temp.getNext();
}
// Remove the node
nodeBefore.setNext(node.getNext());
// If the node to be deleted is the tail node,
// then make the previous node as the tail
if (node == this.tail)
this.tail = nodeBefore;
node.setNext(null);
}
}
}

public static void main(String args[]) {


LinkedList list = new LinkedList();
list.addAtEnd("Milan");
list.addAtEnd("Venice");
list.addAtEnd("Munich");
list.addAtEnd("Prague");
list.addAtEnd("Vienna");
list.display();
System.out.println("--------------------------");
list.delete("Venice");
list.display();

/*
* if(list.find("Munich")!=null) System.out.println("Node found"); else
* System.out.println("Node not found");
*/
}
}
--------------
*LINKED LIST EXERCISE 1*
class Node {

private String data;


private Node next;

public Node(String data) {


this.data = data;
}
public void setData(String data) {
this.data = data;
}

public void setNext(Node node) {


this.next = node;
}

public String getData() {


return this.data;
}

public Node getNext() {


return this.next;
}
}

class LinkedList {

private Node head;


private Node tail;

public Node getHead() {


return this.head;
}

public Node getTail() {


return this.tail;
}

public void addAtEnd(String data) {


Node node = new Node(data);

if (this.head == null) {
this.head = this.tail = node;
} else {
this.tail.setNext(node);
this.tail = node;
}
}

public void addAtBeginning(String data) {


Node node = new Node(data);

if (this.head == null) {
this.head = this.tail = node;
}

else {
node.setNext(this.head);
this.head = node;
}
}

public void display() {


Node temp = this.head;

while (temp != null) {


System.out.println(temp.getData());
temp = temp.getNext();
}
}

public Node find(String data) {


Node temp = this.head;

while (temp != null) {


if (temp.getData().equals(data))
return temp;
temp = temp.getNext();
}
return null;
}

public void insert(String data, String dataBefore) {


Node node = new Node(data);

if (this.head == null)
this.head = this.tail = node;
else {
Node nodeBefore = this.find(dataBefore);
if (nodeBefore != null) {
node.setNext(nodeBefore.getNext());
nodeBefore.setNext(node);
if (nodeBefore == this.tail)
this.tail = node;
} else
System.out.println("Node not found");
}
}

public void delete(String data) {

if (this.head == null)
System.out.println("List is empty");
else {
Node node = this.find(data);

if (node == null)
System.out.println("Node not found");

if (node == this.head) {
this.head = this.head.getNext();
node.setNext(null);

if (node == this.tail)
tail = null;
}
else {
Node nodeBefore = null;
Node temp = this.head;
while (temp != null) {
if (temp.getNext() == node) {
nodeBefore = temp;
break;
}
temp = temp.getNext();
}

nodeBefore.setNext(node.getNext());

if (node == this.tail)
this.tail = nodeBefore;
node.setNext(null);
}
}
}
}
class Tester {

public static void main(String args[]) {

LinkedList linkedList = new LinkedList();


linkedList.addAtEnd("AB");
linkedList.addAtEnd("BC");
linkedList.addAtEnd("CD");
linkedList.addAtEnd("DE");
linkedList.addAtEnd("EF");

String elementToBeFound = "CD";


int position = findPosition(elementToBeFound, linkedList.getHead());
if (position != 0)
System.out.println("The position of the element is " + position);
else
System.out.println("The element is not found!");
}

public static int findPosition(String element, Node head) {


//Implement your code here and change the return value accordingly
Node temp=head; int position=0;
while(temp!=null)
{
position++;
if(element.equals(temp.getData())){
return position;
}

temp=temp.getNext();
}
return 0;
}
}
--------------
*LINKED LIST ASSIGNMENTS*
-----
1. class Node {

private String data;


private Node next;
public Node(String data) {
this.data = data;
}

public void setData(String data) {


this.data = data;
}

public void setNext(Node node) {


this.next = node;
}

public String getData() {


return this.data;
}

public Node getNext() {


return this.next;
}
}

class LinkedList {

private Node head;


private Node tail;

public Node getHead() {


return this.head;
}

public Node getTail() {


return this.tail;
}

public void addAtEnd(String data) {


Node node = new Node(data);

if (this.head == null) {
this.head = this.tail = node;
} else {
this.tail.setNext(node);
this.tail = node;
}
}

public void addAtBeginning(String data) {


Node node = new Node(data);

if (this.head == null) {
this.head = this.tail = node;
}

else {
node.setNext(this.head);
this.head = node;
}
}

public void display() {


Node temp = this.head;

while (temp != null) {


System.out.println(temp.getData());
temp = temp.getNext();
}
}

public Node find(String data) {


Node temp = this.head;

while (temp != null) {


if (temp.getData().equals(data))
return temp;
temp = temp.getNext();
}
return null;
}

public void insert(String data, String dataBefore) {


Node node = new Node(data);

if (this.head == null)
this.head = this.tail = node;
else {
Node nodeBefore = this.find(dataBefore);
if (nodeBefore != null) {
node.setNext(nodeBefore.getNext());
nodeBefore.setNext(node);
if (nodeBefore == this.tail)
this.tail = node;
}
else
System.out.println("Node not found");
}
}

public void delete(String data) {

if (this.head == null)
System.out.println("List is empty");
else {
Node node = this.find(data);

if (node == null)
System.out.println("Node not found");

if (node == this.head) {
this.head = this.head.getNext();
node.setNext(null);

if (node == this.tail)
tail = null;
}
else {
Node nodeBefore = null;
Node temp = this.head;
while (temp != null) {
if (temp.getNext() == node) {
nodeBefore = temp;
break;
}
temp = temp.getNext();
}

nodeBefore.setNext(node.getNext());
if (node == this.tail)
this.tail = nodeBefore;
node.setNext(null);
}
}
}
}

class Tester {

public static void main(String args[]) {


LinkedList linkedList1 = new LinkedList();
linkedList1.addAtEnd("ABC");
linkedList1.addAtEnd("DFG");
linkedList1.addAtEnd("XYZ");
linkedList1.addAtEnd("EFG");

LinkedList linkedList2 = new LinkedList();


linkedList2.addAtEnd("ABC");
linkedList2.addAtEnd("DFG");
linkedList2.addAtEnd("XYZ");
linkedList2.addAtEnd("EFG");

System.out.println("Initial List");
linkedList1.display();

System.out.println("\nList after left shifting by 2 positions");


shiftListLeft(linkedList1, 2);
linkedList1.display();

System.out.println("\nInitial List");
linkedList2.display();

System.out.println("\nList after right shifting by 2 positions");


shiftListRight(linkedList2, 2);
linkedList2.display();
}

public static void shiftListLeft(LinkedList linkedList, int n) {


//Implement your code here
Node temp= linkedList.getHead();
int size=0;
while(temp!=null){
size++;
temp=temp.getNext();
}
n=n%size;
for(int i=0; i<n; i++){
Node head= linkedList.getHead();
String data= head.getData();
linkedList.delete(data);
Node tail= linkedList.getTail();
linkedList.insert(data, tail.getData());
}
return;
}

public static void shiftListRight(LinkedList linkedList, int n) {


//Implement your code here
Node temp= linkedList.getHead();
int size=0;
while(temp!=null){
size++;
temp=temp.getNext();
}
n=n%size;
for(int i=0; i<n; i++){
Node tail= linkedList.getTail();
String data= tail.getData();
linkedList.delete(data);
Node head= linkedList.getHead();
linkedList.addAtBeginning(data);
}
return;

}
}

------------------------
2. class Node {

private String data;


private Node next;

public Node(String data) {


this.data = data;
}

public void setData(String data) {


this.data = data;
}

public void setNext(Node node) {


this.next = node;
}

public String getData() {


return this.data;
}

public Node getNext() {


return this.next;
}
}

class LinkedList {

private Node head;


private Node tail;

public Node getHead() {


return this.head;
}

public Node getTail() {


return this.tail;
}

public void addAtEnd(String data) {


Node node = new Node(data);

if (this.head == null) {
this.head = this.tail = node;
} else {
this.tail.setNext(node);

this.tail = node;
}
}

public void addAtBeginning(String data) {


Node node = new Node(data);

if (this.head == null) {
this.head = this.tail = node;
}

else {
node.setNext(this.head);
this.head = node;
}
}

public void display() {


Node temp = this.head;

while (temp != null) {


System.out.println(temp.getData());
temp = temp.getNext();
}
}

public Node find(String data) {


Node temp = this.head;

while (temp != null) {


if (temp.getData().equals(data))
return temp;
temp = temp.getNext();
}
return null;
}

public void insert(String data, String dataBefore) {


Node node = new Node(data);

if (this.head == null)
this.head = this.tail = node;
else {
Node nodeBefore = this.find(dataBefore);
if (nodeBefore != null) {
node.setNext(nodeBefore.getNext());
nodeBefore.setNext(node);
if (nodeBefore == this.tail)
this.tail = node;
}
else
System.out.println("Node not found");
}
}

public void delete(String data) {

if (this.head == null)
System.out.println("List is empty");
else {
Node node = this.find(data);

if (node == null)
System.out.println("Node not found");

if (node == this.head) {
this.head = this.head.getNext();
node.setNext(null);

if (node == this.tail)
tail = null;
}
else {
Node nodeBefore = null;
Node temp = this.head;
while (temp != null) {
if (temp.getNext() == node) {
nodeBefore = temp;
break;
}
temp = temp.getNext();
}

nodeBefore.setNext(node.getNext());

if (node == this.tail)
this.tail = nodeBefore;
node.setNext(null);
}
}
}
}

class Tester {

public static void main(String args[]) {

LinkedList linkedList = new LinkedList();


LinkedList reversedLinkedList = new LinkedList();

linkedList.addAtEnd("Data");
linkedList.addAtEnd("Structures");
linkedList.addAtEnd("and");
linkedList.addAtEnd("Algorithms");

System.out.println("Initial List");
linkedList.display();

System.out.println();

reverseList(linkedList.getHead(), reversedLinkedList);
System.out.println("Reversed List");
reversedLinkedList.display();
}

public static void reverseList(Node head, LinkedList reversedLinkedList) {


//Implement your code here
if(head==null)
return;
reverseList(head.getNext(), reversedLinkedList);
reversedLinkedList.addAtEnd(head.getData());
return;
}
}

------------------------
=====================
*DAY 2*
----------------
*PUSH OPERATION- TRYOUT*
class Stack {
private int top; // represents the index position of the top most element in the stack
private int maxSize; // represents the maximum number of elements that can be stored in
the stack
private int[] arr;

Stack(int maxSize) {
this.top = -1; // top is -1 when the stack is created
this.maxSize = maxSize;
arr = new int[maxSize];
}

// Checking if the stack is full or not


public boolean isFull() {
if (top >= (maxSize - 1)) {
return true;
}
return false;
}

// Adding a new element to the top of the stack


public boolean push(int data) {
if (isFull()) {
return false;
} else {
arr[++top] = data;
return true;
}
}

// Returning the top most element of the stack


public int peek() {
if (top < 0)
return Integer.MIN_VALUE;
else
return arr[top];
}

// Displaying all the elements of the stack


public void display() {
System.out.println("Displaying stack elements");
for (int index = top; index >= 0; index--) {
System.out.println(arr[index]); // accessing element at position index
}

class Tester {
public static void main(String args[]) {
Stack stack = new Stack(5);
System.out.println("Stack created.\n");

if (stack.push(1))
System.out.println("The element is pushed to the stack!\n");
else
System.out.println("Stack is full!\n");

if (stack.push(2))
System.out.println("The element is pushed to the stack!\n");
else
System.out.println("Stack is full!\n");

if (stack.push(3))
System.out.println("The element is pushed to the stack!\n");
else
System.out.println("Stack is full!\n");

if (stack.push(4))
System.out.println("The element is pushed to the stack!\n");
else
System.out.println("Stack is full!\n");

if (stack.push(5))
System.out.println("The element is pushed to the stack!\n");
else
System.out.println("Stack is full!\n");

stack.display();

if (stack.push(6))
System.out.println("The element is pushed to the stack!\n");
else
System.out.println("Stack is full!\n");
System.out.println("The top element is : " + stack.peek());

}
}
--------------------------------
*STACK COMPLETE TRYOUT*
class Stack {
private int top; // represents the index position of the top most element in the stack
private int maxSize; // represents the maximum number of elements that can be stored in
the stack
private int[] arr;

Stack(int maxSize) {
this.top = -1; // top is -1 when the stack is created
this.maxSize = maxSize;
arr = new int[maxSize];
}

// Checking if the stack is full or not


public boolean isFull() {
if (top >= (maxSize - 1)) {
return true;
}
return false;
}

// Adding a new element to the top of the stack


public boolean push(int data) {
if (isFull()) {
return false;
} else {
arr[++top] = data;
return true;
}
}

// Returning the top most element of the stack


public int peek() {
if (isEmpty())
return Integer.MIN_VALUE;
else
return arr[top];
}

// Displaying all the elements of the stack


public void display() {
if (isEmpty())
System.out.println("Stack is empty!");
else {
System.out.println("Displaying stack elements");
for (int index = top; index >= 0; index--) {
System.out.println(arr[index]); // accessing element at position
index
}
}
}

// Checking if the stack is empty or not


public boolean isEmpty() {
if (top < 0) {
return true;
}
return false;
}

// Removing the element from the top of the stack


public int pop() {
if (isEmpty())
return Integer.MIN_VALUE;
else
return arr[top--];
}
}

class Tester {
public static void main(String args[]) {
Stack stack = new Stack(5);
System.out.println("Stack created.\n");

if (stack.push(1))
System.out.println("The element is pushed to the stack!\n");
else
System.out.println("Stack is full!\n");

if (stack.push(2))
System.out.println("The element is pushed to the stack!\n");
else
System.out.println("Stack is full!\n");

if (stack.push(3))
System.out.println("The element is pushed to the stack!\n");
else
System.out.println("Stack is full!\n");

if (stack.push(4))
System.out.println("The element is pushed to the stack!\n");
else
System.out.println("Stack is full!\n");

if (stack.push(5))
System.out.println("The element is pushed to the stack!\n");
else
System.out.println("Stack is full!\n");

stack.display();

if (stack.push(6))
System.out.println("The element is pushed to the stack!\n");
else
System.out.println("Stack is full!\n");

System.out.println("The top element is : " + stack.peek());

int poppedElement = stack.pop();


if (poppedElement == Integer.MIN_VALUE)
System.out.println("Stack is empty\n");
else
System.out.println("The element popped out is : " + poppedElement +
"\n");

poppedElement = stack.pop();
if (poppedElement == Integer.MIN_VALUE)
System.out.println("Stack is empty\n");
else
System.out.println("The element popped out is : " + poppedElement +
"\n");

poppedElement = stack.pop();
if (poppedElement == Integer.MIN_VALUE)
System.out.println("Stack is empty\n");
else
System.out.println("The element popped out is : " + poppedElement +
"\n");

poppedElement = stack.pop();
if (poppedElement == Integer.MIN_VALUE)
System.out.println("Stack is empty\n");
else
System.out.println("The element popped out is : " + poppedElement +
"\n");

poppedElement = stack.pop();
if (poppedElement == Integer.MIN_VALUE)
System.out.println("Stack is empty\n");
else
System.out.println("The element popped out is : " + poppedElement +
"\n");

poppedElement = stack.pop();
if (poppedElement == Integer.MIN_VALUE)
System.out.println("Stack is empty\n");
else
System.out.println("The element popped out is : " + poppedElement +
"\n");
}
}
-------------------------
*ENQUEUE OPERATION-TRYOUT*
class Queue {

private int front; // front represents the index position of the first element in the queue
private int rear; // rear represents the index position of the last element in the queue
private int maxSize; // maxSize represent the maximum number of elements that can be
stored in the queue
private String arr[];

Queue(int maxSize) {
this.front = 0; // front is 0 when the queue is created
this.rear = -1; // rear is -1 when the queue is created
this.maxSize = maxSize;
this.arr = new String[maxSize];
}

//Checking if the queue is full or not


public boolean isFull() {
if (rear == maxSize - 1) {
return true;
}
return false;
}

//Adding a new element to the rear of queue


public boolean enqueue(String data) {
if (isFull()) {
return false;
} else {
arr[++rear] = data;
return true;
}
}

//Displaying all the elements in the queue


public void display() {
System.out.println("Displaying queue elements");
for (int index = front; index <= rear; index++) {
System.out.println(arr[index]);
}
}

class Tester {

public static void main(String[] args) {

Queue queue = new Queue(5);


System.out.println("Queue created.\n");

if (queue.enqueue("Joe"))
System.out.println("The element is enqueued to the queue!\n");
else
System.out.println("Queue is full!\n");

if (queue.enqueue("Jack"))
System.out.println("The element is enqueued to the queue!\n");
else
System.out.println("Queue is full!\n");

if (queue.enqueue("Eva"))
System.out.println("The element is enqueued to the queue!\n");
else
System.out.println("Queue is full!\n");

if (queue.enqueue("Mia"))
System.out.println("The element is enqueued to the queue!\n");
else
System.out.println("Queue is full!\n");

if (queue.enqueue("Luke"))
System.out.println("The element is enqueued to the queue!\n");
else
System.out.println("Queue is full!\n");

queue.display();

if (queue.enqueue("Emma"))
System.out.println("The element is enqueued to the queue!\n");
else
System.out.println("Queue is full!\n");

}
}
-------------------------
*QUEUE COMPLETE- TRYOUT*
class Queue {

private int front; // front represents the index position of the first element in the queue
private int rear; // rear represents the index position of the last element in the queue
private int maxSize; // maxSize represent the maximum number of elements that can be
stored in the queue
private String arr[];

Queue(int maxSize) {
this.front = 0; // front is 0 when the queue is created
this.rear = -1; // rear is -1 when the queue is created
this.maxSize = maxSize;
this.arr = new String[maxSize];
}

// Checking if the queue is full or not


public boolean isFull() {
if (rear == maxSize - 1) {
return true;
}
return false;
}

// Adding a new element to the rear of queue


public boolean enqueue(String data) {
if (isFull()) {
return false;
} else {
arr[++rear] = data;
return true;
}
}

// Displaying all the elements in the queue


public void display() {
if (isEmpty())
System.out.println("Queue is empty!");
else {
System.out.println("Displaying queue elements");
for (int index = front; index <= rear; index++) {
System.out.println(arr[index]);
}
}
}

// Checking if the queue is empty or not


public boolean isEmpty() {
if (front > rear)
return true;
return false;
}

// Removing an element from the front of queue


public String dequeue() {
if (isEmpty()) {
return "empty";
} else {
String data = arr[this.front++];

return data;
}
}
}

class Tester {

public static void main(String[] args) {

Queue queue = new Queue(5);


System.out.println("Queue created.\n");

if (queue.enqueue("Joe"))
System.out.println("The element is enqueued to the queue!\n");
else
System.out.println("Queue is full!\n");

if (queue.enqueue("Jack"))
System.out.println("The element is enqueued to the queue!\n");
else
System.out.println("Queue is full!\n");

if (queue.enqueue("Eva"))
System.out.println("The element is enqueued to the queue!\n");
else
System.out.println("Queue is full!\n");

if (queue.enqueue("Mia"))
System.out.println("The element is enqueued to the queue!\n");
else
System.out.println("Queue is full!\n");

if (queue.enqueue("Luke"))
System.out.println("The element is enqueued to the queue!\n");
else
System.out.println("Queue is full!\n");

queue.display();

if (queue.enqueue("Emma"))
System.out.println("The element is enqueued to the queue!\n");
else
System.out.println("Queue is full!\n");

String dequeuedElement = queue.dequeue();


if (dequeuedElement == "empty")
System.out.println("Queue is empty\n");
else
System.out.println("The element dequeued is : " + dequeuedElement +
"\n");

dequeuedElement = queue.dequeue();
if (dequeuedElement == "empty")
System.out.println("Queue is empty\n");
else
System.out.println("The element dequeued is : " + dequeuedElement +
"\n");

dequeuedElement = queue.dequeue();
if (dequeuedElement == "empty")
System.out.println("Queue is empty\n");
else
System.out.println("The element dequeued is : " + dequeuedElement +
"\n");

dequeuedElement = queue.dequeue();
if (dequeuedElement == "empty")
System.out.println("Queue is empty\n");
else
System.out.println("The element dequeued is : " + dequeuedElement +
"\n");

dequeuedElement = queue.dequeue();
if (dequeuedElement == "empty")
System.out.println("Queue is empty\n");
else
System.out.println("The element dequeued is : " + dequeuedElement +
"\n");

dequeuedElement = queue.dequeue();
if (dequeuedElement == "empty")
System.out.println("Queue is empty\n");
else
System.out.println("The element dequeued is : " + dequeuedElement +
"\n");
}
}
-------------------------
*STACK-EXERCISE 1*
class Stack {

private int top;


private int maxSize;
private int[] arr;

Stack(int maxSize) {
this.top = -1;
this.maxSize = maxSize;
arr = new int[maxSize];
}

public boolean isFull() {


if (top >= (maxSize - 1)) {
return true;
}
return false;
}

public boolean push(int data) {


if (isFull()) {
return false;
}
else {
arr[++top] = data;
return true;
}
}

public int peek() {


if (isEmpty())
return Integer.MIN_VALUE;
else
return arr[top];
}

public void display() {


if (isEmpty())
System.out.println("Stack is empty!");
else {
System.out.println("Displaying stack elements");
for (int index = top; index >= 0; index--) {
System.out.println(arr[index]); // accessing element at position index
}
}
}

public boolean isEmpty() {


if (top < 0) {
return true;
}
return false;
}

public int pop() {


if (isEmpty())
return Integer.MIN_VALUE;
else
return arr[top--];
}
}

class Tester {

public static void main(String args[]) {

Stack stack = new Stack(10);


stack.push(15);
stack.push(25);
stack.push(30);
stack.push(40);

stack.display();

if (checkTop(stack)) {
System.out.println("The top most element of the stack is an even number");
} else {
System.out.println("The top most element of the stack is an odd number");
}
}

public static boolean checkTop(Stack stack) {


//Implement your code here and change the return value accordingly
if(stack.peek()%2==0){
return true;
}
return false;
}
}
-----------------
*QUEUE EXERCISE 1*
class Queue {

private int front;


private int rear;
private int maxSize;
private int arr[];

Queue(int maxSize) {
this.front = 0;
this.rear = -1;
this.maxSize = maxSize;
this.arr = new int[this.maxSize];
}

public boolean isFull() {


if (rear == maxSize - 1) {
return true;
}
return false;
}

public boolean enqueue(int data) {


if (isFull()) {
return false;
} else {
arr[++rear] = data;
return true;
}
}

public void display() {


if(isEmpty())
System.out.println("Queue is empty!");
else {
for (int index = front; index <= rear; index++) {
System.out.println(arr[index]);
}
}
}

public boolean isEmpty() {


if (front > rear)
return true;
return false;
}

public int dequeue() {


if (isEmpty()) {
return Integer.MIN_VALUE;
} else {
int data = arr[this.front];
arr[front++] = Integer.MIN_VALUE;
return data;
}
}

public int getMaxSize() {


return maxSize;
}
}

class Tester {

public static void main(String[] args) {

Queue queue = new Queue(7);


queue.enqueue(2);
queue.enqueue(7);
queue.enqueue(9);
queue.enqueue(4);
queue.enqueue(6);
queue.enqueue(5);
queue.enqueue(10);
Queue[] queueArray = splitQueue(queue);

System.out.println("Elements in the queue of odd numbers");


queueArray[0].display();

System.out.println("\nElements in the queue of even numbers");


queueArray[1].display();

public static Queue[] splitQueue(Queue queue) {


//Implement your code here and change the return value accordingly
Queue[] numArray= new Queue[2];
Queue oddQueue= new Queue(queue.getMaxSize());
Queue evenQueue= new Queue(queue.getMaxSize());
while(!(queue.isEmpty())){
int val= queue.dequeue();
if(val%2==0){
evenQueue.enqueue(val);
}
else oddQueue.enqueue(val);
}
numArray[0]= oddQueue;
numArray[1]= evenQueue;
return numArray;
}
}
----------------------------
*ASSIGNMENTS*
---------
1. STACK 1

class Stack {

private int top;


private int maxSize;
private int[] arr;

Stack(int maxSize) {
this.top = -1;
this.maxSize = maxSize;
arr = new int[maxSize];
}

public boolean isFull() {


if (top >= (maxSize - 1)) {
return true;
}
return false;
}

public boolean push(int data) {


if (isFull()) {
return false;
}
else {
arr[++top] = data;
return true;
}
}

public int peek() {


if (isEmpty())
return Integer.MIN_VALUE;
else
return arr[top];
}

public void display() {


if (isEmpty())
System.out.println("Stack is empty!");
else {
System.out.println("Displaying stack elements");
for (int index = top; index >= 0; index--) {
System.out.println(arr[index]); // accessing element at position index
}
}
}

public boolean isEmpty() {


if (top < 0) {
return true;
}
return false;
}
public int pop() {
if (isEmpty())
return Integer.MIN_VALUE;
else
return arr[top--];
}
}

class Tester {

public static void main(String args[]) {

Stack stack = new Stack(10);


stack.push(15);
stack.push(20);
stack.push(30);
stack.push(40);

calculateSum(stack);

System.out.println("Updated stack");
stack.display();
}

public static void calculateSum(Stack stack) {


//Implement your code here
Stack newStack= new Stack(11);
int sum=0;
while(!(stack.isEmpty())){
int val= stack.pop();
sum=sum+val;
newStack.push(val);
}
newStack.push(sum);
while(!(newStack.isEmpty())){
int x= newStack.pop();
stack.push(x);
}
}
}
--------------
2. QUEUE 1
class Queue {

private int front;


private int rear;
private int maxSize;
private int arr[];

Queue(int maxSize) {
this.front = 0;
this.rear = -1;
this.maxSize = maxSize;
this.arr = new int[this.maxSize];
}

public boolean isFull() {


if (rear == maxSize - 1) {
return true;
}
return false;
}

public boolean enqueue(int data) {


if (isFull()) {
return false;
} else {
arr[++rear] = data;
return true;
}
}

public void display() {


if(isEmpty())
System.out.println("Queue is empty!");
else {
for (int index = front; index <= rear; index++) {
System.out.println(arr[index]);
}
}
}

public boolean isEmpty() {


if (front > rear)
return true;
return false;
}

public int dequeue() {


if (isEmpty()) {
return Integer.MIN_VALUE;
} else {
int data = arr[this.front];
arr[front++] = Integer.MIN_VALUE;
return data;
}
}

public int getMaxSize() {


return maxSize;
}
}

class Tester {

public static void main(String[] args) {

Queue queue = new Queue(7);


queue.enqueue(13983);
queue.enqueue(10080);
queue.enqueue(7113);
queue.enqueue(2520);
queue.enqueue(2500);

Queue outputQueue = findEvenlyDivisibleNumbers(queue);

System.out.println("Evenly divisible numbers");


outputQueue.display();

public static Queue findEvenlyDivisibleNumbers(Queue queue) {


Queue newoutputQueue = new Queue(queue.getMaxSize());
//Implement your code here and change the return value accordingly
while(!(queue.isEmpty())){
int a= queue.dequeue();
boolean b= true;
for(int i=1; i<=10; i++){
if(a%i!=0){
b= false;
break;
}
}
if(b==true){
newoutputQueue.enqueue(a);
}
}
return newoutputQueue;
}
}
--------------
===========================
DAY 3
==================
*GENERIC TYPES- TRYOUT*
class Container<T> {

private T t;

public void set(T t) {


this.t = t;
}

public T get() {
return t;
}
}

class Tester {

public static void main(String[] args) {

Container<Integer> integerContainer = new Container<>();


integerContainer.set(1);
//integerContainer.set("Jeo"); //Uncomment the code and check if String can be passed
to the set() method
System.out.println("Inside Integer Container : "+integerContainer.get());

Container<String> stringContainer = new Container<>();


//stringContainer.set(1); //Uncomment the code and check if Integer can be passed to the
set() method
stringContainer.set("Jeo");
System.out.println("Inside String Container : "+stringContainer.get());

}
---------------------------------
*GENERIC METHOD-TRYOUT*
class GenericDemo{

//Generic Method
public static <E> void display(E[] arr) {
for (E element : arr) {
System.out.println(element);
}
}

public static void main(String[] args) {

String[] names= { "Luke", "Mia", "Mathew" };


display(names);

System.out.println();

Integer[] numbers = { 1, 2, 3, 4, 5 };
display(numbers);

}
---------------------------
*ARRAYLIST TRYOUT-1*

\if needed as list\


import java.util.ArrayList; // Importing the ArrayList class
import java.util.List;

class Tester {
public static void main(String[] args) {
List<String> food = new ArrayList<String>(); // Creating a list of String elements
food.add("Pizza"); // Adding elements
food.add("Burger");
food.add("Pasta");
food.add("Sandwich");
food.add(1, "momos");
System.out.println("Food items: " + food);
}
}

\if needed as array\


import java.util.ArrayList; // Importing the ArrayList class
import java.util.List;

class Tester {
public static void main(String[] args) {
List<String> food = new ArrayList<String>(); // Creating a list of String elements
food.add("Pizza"); // Adding elements
food.add("Burger");
food.add("Pasta");
food.add("Sandwich");
for (String element : food) {
System.out.println("Food items: " + element);
}
}
}
-------------------------
*ARRATLIST-TRYOUT 2*
import java.util.ArrayList;
import java.util.List;

class Tester {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<Integer>(); // Creating an ArrayList
object
// Adding the elements to the list
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(6);
System.out.println("numbers list: " + numbers);

// Adding the number 15 at a particular index (index: 3) in the ArrayList


numbers.add(3, 15);
System.out.println("Observe the index position 3: " + numbers);

// Finding the size of the ArrayList


System.out.println("Size of the ArrayList: " + numbers.size());

// Retrieving the element at a specified index


System.out.println("The number present at the fifth index position is " +
numbers.get(5));

// Modifying the element at a specified index (index: 2)


numbers.set(2, 200);
System.out.println("The number at the 2nd index position is changed from 3 to
200" + numbers);

}
}
--------------------
*ARRAYLIST TRYOUT-3*
import java.util.ArrayList;
import java.util.List;

class Tester {

public static void main(String[] args) {


List<String> names = new ArrayList<String>();
names.add("Brian");
names.add("Ross");
names.add("Steve");
names.add("Rachel");
names.add("Steve");

//Checking whether any element is present or not


if (names.isEmpty()) {
System.out.println("No names are present!!");
}

//Displaying the number of names


System.out.println("Number Of names: " + names.size());

//Creating newNames list


List<String> newNames = new ArrayList<String>();
newNames.add("Emily");
newNames.add("Melissa");

// Adding elements of newNames list into names


names.addAll(newNames);

//Displaying all names


System.out.println("The list of names after adding all the names from newNames
to names: ");
System.out.println("========================================");
for (String name : names) {
System.out.println(name);
}
System.out.println("========================================");

// Checking whether the name Ross is present or not


if (names.contains("Ross")) {
System.out.println("This name is already present!");
} else {
System.out.println("This name is not present!");
}

//Converting list to array


Object[] namesArray = names.toArray();

// Deleting all the names from the names list


names.clear();
System.out.println("========================================");
System.out.println("Checking whether the names list is empty or not : ");
//Confirming whether all the elements are deleted or not
System.out.println(names.isEmpty());

}
}
------------------------
*ITERATING THROUGH ARRAYLIST USING FOR EACH- TRYOUT*
import java.util.ArrayList;
import java.util.List;

class Student {
private int studentId;
private String studentName;
private boolean courseRegistered;
public Student(int studentId, String studentName, boolean courseRegistered) {
this.studentId = studentId;
this.studentName = studentName;
this.courseRegistered = courseRegistered;
}

public int getStudentId() {


return studentId;
}

public void setStudentId(int studentId) {


this.studentId = studentId;
}

public String getStudentName() {


return studentName;
}

public void setStudentName(String studentName) {


this.studentName = studentName;
}

public boolean getCourseRegistered() {


return courseRegistered;
}

public void setCourseRegistered(boolean courseRegistered) {


this.courseRegistered = courseRegistered;
}

class Tester {
public static void main(String[] args) {
List<Student> students = new ArrayList<Student>();
students.add(new Student(1001, "Steve", true));
students.add(new Student(1002, "Rachel", false));
students.add(new Student(1003, "Monica", true));
students.add(new Student(1004, "David", true));

List<String> studentNames = new ArrayList<String>();


for (Student student : students) {
studentNames.add(student.getStudentName());
System.out.println("Student Id: " + student.getStudentId());
System.out.println("Student Name: " + student.getStudentName());
System.out.println("Course Registered: " +
student.getCourseRegistered());
}
System.out.println("===========================================");
System.out.println("Student Names: " + studentNames);

}
}
-------------------------
*ITERATOR METHOD TRYOUT*
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

class Student {
private int studentId;
private String studentName;
private boolean courseRegistered;

public Student(int studentId, String studentName, boolean courseRegistered) {


this.studentId = studentId;
this.studentName = studentName;
this.courseRegistered = courseRegistered;
}

public int getStudentId() {


return studentId;
}

public void setStudentId(int studentId) {


this.studentId = studentId;
}

public String getStudentName() {


return studentName;
}

public void setStudentName(String studentName) {


this.studentName = studentName;
}
public boolean isCourseRegistered() {
return courseRegistered;
}

public void setCourseRegistered(boolean courseRegistered) {


this.courseRegistered = courseRegistered;
}

class Tester {
public static void main(String[] args) {
List<Student> students = new ArrayList<Student>();
students.add(new Student(1001, "Steve", true));
students.add(new Student(1002, "Rachel", false));
students.add(new Student(1003, "Monica", true));
students.add(new Student(1004, "David", true));

ListIterator<Student> item = students.listIterator();


System.out.println("Student names");
while (item.hasNext()) {
System.out.println(item.next().getStudentName());
}

System.out.println();

System.out.println("Student names in reverse order");


while (item.hasPrevious()) {
System.out.println(item.previous().getStudentName());
}

}
}
---------------------------
*METHODS IN LINKED LIST-TRYOUT*
import java.util.List;
import java.util.LinkedList;

class EuropeTrip {

public static void main(String args[]) {


// Creating a LinkedList
List<String> cities = new LinkedList<String>();
// Adding elements
cities.add("Milan");
cities.add("Venice");
cities.add("Munich");
cities.add("Vienna");

// Displaying elements
System.out.println(cities);

// Inserting elements
cities.add(3, "Prague");
System.out.println(cities);

// Removing elements
cities.remove("Munich");
System.out.println(cities);

// Replacing element
cities.set(2, "Berlin");
System.out.println(cities);

// Displaying size
System.out.println(cities.size());

// Checking if an element is present


System.out.println(cities.contains("Paris"));

// Getting element at specific position


System.out.println(cities.get(0));

// Clearing the elements from the LinkedList


cities.clear();
System.out.println(cities);

// Try to test the other methods of the LinkedList class


}
}
-----------------
*ARRAYLIST EXERCISE-1*
import java.util.List;
import java.util.ArrayList;
class Order {
private int orderId;
private List<String> itemNames;
private boolean cashOnDelivery;

public Order(int orderId, List<String> itemNames, boolean cashOnDelivery) {


this.orderId = orderId;
this.itemNames = itemNames;
this.cashOnDelivery = cashOnDelivery;
}

public int getOrderId() {


return orderId;
}

public void setOrderId(int orderId) {


this.orderId = orderId;
}

public List<String> getItemNames() {


return itemNames;
}

public void setItemNames(List<String> itemNames) {


this.itemNames = itemNames;
}

public boolean isCashOnDelivery() {


return cashOnDelivery;
}

public void setCashOnDelivery(boolean cashOnDelivery) {


this.cashOnDelivery = cashOnDelivery;
}

@Override
public String toString() {
return "Order Id: "+getOrderId()+", Item names: "+getItemNames()+", Cash on
delivery: "+isCashOnDelivery();
}
}
class Tester {

public static List<String> getItems(List<Order> orders) {


//Implement your logic here and change the return statement accordingly
List<String> names = new ArrayList<>();
for(Order o: orders){
for(String str: o.getItemNames()){
names.add(str);
}
}
return names;
}

public static void main(String[] args) {


List<Order> orders = new ArrayList<Order>();

List<String> items1 = new ArrayList<String>();


items1.add("FriedRice");
items1.add("Pasta");
items1.add("Tortilla");
orders.add(new Order(101, items1, true));

List<String> items2 = new ArrayList<String>();


items2.add("Pizza");
items2.add("Pasta");
orders.add(new Order(102, items2, true));

List<String> items3 = new ArrayList<String>();


items3.add("Burger");
items3.add("Sandwich");
items3.add("Pizza");
orders.add(new Order(103, items3, true));

List<String> items = getItems(orders);


System.out.println("List of Items:");
for (String item : items) {
System.out.println(item);
}

}
-------------------------
*ARRAYLIST ASSIGNMENT-1*
import java.util.ArrayList;
import java.util.List;

class Participant {
private String participantName;
private String participantTalent;
private double participantScore;

public Participant(String participantName, String participantTalent, double


participantScore) {
this.participantName = participantName;
this.participantTalent = participantTalent;
this.participantScore = participantScore;
}

public String getParticipantName() {


return participantName;
}

public void setParticipantName(String participantName) {


this.participantName = participantName;
}

public String getParticipantTalent() {


return participantTalent;
}

public void setParticipantTalent(String participantTalent) {


this.participantTalent = participantTalent;
}

public double getParticipantScore() {


return participantScore;
}

public void setParticipantScore(double participantScore) {


this.participantScore = participantScore;
}

@Override
public String toString() {
return "Participant Name: "+getParticipantName()+", Participant Talent:
"+getParticipantTalent()+", Participant Score: "+getParticipantScore();
}

class Tester {

public static List<Participant> generateListOfFinalists(Participant[] finalists) {


// Implement your logic here and change the return statement accordingly
List<Participant> list = new ArrayList<>();
for(Participant p: finalists){
list.add(p);
}
return list;
}

public static List<Participant> getFinalistsByTalent(List<Participant> finalists, String


talent) {
// Implement your logic here and change the return statement accordingly
List<Participant> list = new ArrayList<>();
for(Participant p: finalists){

if(p.getParticipantTalent().equals(talent)){
list.add(p);
}
}
return list;
}

public static void main(String[] args) {


Participant finalist1 = new Participant("Hazel", "Singing", 91.2);
Participant finalist2 = new Participant("Ben", "Instrumental", 95.7);
Participant finalist3 = new Participant("John", "Singing", 94.5);
Participant finalist4 = new Participant("Bravo", "Singing", 97.6);

Participant[] finalists = { finalist1, finalist2, finalist3, finalist4 };

List<Participant> finalistsList = generateListOfFinalists(finalists);

System.out.println("Finalists");
for (Participant finalist : finalistsList)
System.out.println(finalist);
String talent = "Singing";
System.out.println("Finalists in " + talent + " category");

List<Participant> finalistsCategoryList = getFinalistsByTalent(finalistsList, talent);


for (Participant finalist : finalistsCategoryList)
System.out.println(finalist);
}

}
--------------------------
*LINKEDLIST EXERCISE-1*
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;

class Tester {

public static List<Object> concatenateLists(List<Object> listOne, List<Object> listTwo) {


// Implement your logic here and change the return statement accordingly
List <Object> catlist= new LinkedList<>();
for(Object o: listOne){
catlist.add(o);
}
for(int i= listTwo.size()-1; i>=0; i--){
catlist.add(listTwo.get(i));
}
return catlist;
}

public static void main(String args[]) {


List<Object> listOne = new LinkedList<Object>();
listOne.add("Hello");
listOne.add(102);
listOne.add(25);
listOne.add(38.5);

List<Object> listTwo = new LinkedList<Object>();


listTwo.add(150);
listTwo.add(200);
listTwo.add('A');
listTwo.add("Welcome");
List<Object> concatenatedList = concatenateLists(listOne, listTwo);

System.out.println("Concatenated linked list:");


for (Object value : concatenatedList) {
System.out.print(value+" ");
}
}
}
---------------------------
==========================
DAY 4
===========================
*HASH SET TRYOUT 1*
import java.util.HashSet;
import java.util.Set;
import java.util.Iterator;

class Tester {
public static void main(String[] args) {
// Creating HashSet
Set<String> food = new HashSet<String>();

// Checking if a HashSet is empty


System.out.println("Is the set empty? : " + food.isEmpty());

// Adding elements to the HashSet


food.add("Pasta");
food.add("Noodles");
food.add("Sandwich");
food.add("Pasta");
food.add("Burger");
food.add("Noodles");
System.out.print("Set output without the duplicates: ");
System.out.println(food);

// Finding the size of the HashSet


System.out.println("The number of food items in the set: " + food.size());

// Checking if the HashSet contains the given element


String foodItem = "Pasta";
if (food.contains(foodItem))
System.out.println(foodItem + " is already ordered");
else
System.out.println(foodItem + " is not ordered");

// Removing an element from the HashSet


if(food.remove("Burger"))
System.out.println("Output after removing Burger from the set:" + food);

// Traversing elements
Iterator<String> item = food.iterator();

while (item.hasNext())
System.out.println(item.next());

// Removing all the elements from the HashSet


food.clear();
System.out.println("After clear() => " + food);
}
}
----------------------
*HASHSET EQUALS() AND HASHCODE () METHODS- TRYOUT*
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;

class User {
private int userId;
private String userName;
private String emailId;

public User(int userId, String userName, String emailId) {


this.userId = userId;
this.userName = userName;
this.emailId = emailId;
}

public int getUserId() {


return userId;
}

public void setUserId(int userId) {


this.userId = userId;
}
public String getUserName() {
return userName;
}

public void setUserName(String userName) {


this.userName = userName;
}

public String getEmailId() {


return emailId;
}

public void setEmailId(String emailId) {


this.emailId = emailId;
}

@Override
public boolean equals(Object user) {
User otherUser = (User) user;
if (this.emailId.equals(otherUser.emailId))
return true;
return false;
}

@Override
public int hashCode() {
return emailId.hashCode();
}

@Override
public String toString() {
return "User Name: "+userName + ", Email Id: " + emailId;
}
}

class Tester {

public static void main(String[] args) {


List<User> userList = new ArrayList<User>();
userList.add(new User(1001, "Mike", "Mike@example.com"));
userList.add(new User(1002, "Ben", "User@example.com"));
userList.add(new User(1003, "Henry", "Henry@example.com"));
userList.add(new User(1004, "Hannah", "User@example.com"));
userList.add(new User(1005, "Ellie", "Henry@example.com"));
userList.add(new User(1006, "Ryan", "Ryan@example.com"));

Set<User> userSet = new HashSet<User>();


userSet.addAll(userList);
// for (User user : userSet)
System.out.println(userSet);
}
}
----------------------------
*METHODS IN HASHMAP- TRYOUT*
import java.util.Map;
import java.util.HashMap;

class Tester {

public static void main(String args[]) {


Map<String, Integer> books = new HashMap<String, Integer>();

//Adding key-value pairs to the map


books.put("Data Structures With Java", 50);
books.put("Operating System", 80);
books.put("Let Us C", 70);
books.put("Java Fundamentals", 40);

//Displaying all the key-value pairs present in the map


System.out.println(books);

//Traversing the map


//entrySet() method is used to retrieve all the key value pairs
for(Map.Entry<String, Integer> book:books.entrySet())
System.out.println(book.getKey()+", "+book.getValue());

//keySet() method returns the keys in the Map


for(String name:books.keySet())
System.out.println("key: "+name);

//values() method returns the values in the Map


for(int quantity:books.values())
System.out.println("value: "+quantity);

//Removing element based on key


books.remove("Let Us C");

//Removing element based on value


//Uncomment the code given below, execute and observe the output
//books.remove(70);

//Removing element based on key and value


//Uncomment the code given below, execute and observe the output
//books.remove("Let Us C", 70);

System.out.println(books);

//Replacing key-value pair in the map


books.replace("Operating System", 80, 100);
System.out.println(books);

//Getting a value from the map based on key


System.out.println(books.get("Java Fundamentals"));

//Printing size of the map


System.out.println(books.size());

//Removing all the key-value pairs from the map


books.clear();

//Checking if the map is empty


System.out.println(books.isEmpty());
}

}
-------------------------------
*QUEUE USING ARRAY DEQUE- TRYOUT*
import java.util.Deque;
import java.util.ArrayDeque;

class Tester{

public static void main(String[] args) {

Deque<String> queue = new ArrayDeque<String>(); // no restrictions in


capacity
queue.add("Joe");
queue.add("Jack");
queue.add("Eva");
queue.add("Mia");
queue.add("Luke");

System.out.println("People in queue - After addition of 5 people");


for (String str : queue) {
System.out.println(str);
}

queue.remove();
queue.remove();
queue.remove();

System.out.println("\nPeople in queue - After removal of 3 people");


for (String str : queue) {
System.out.println(str);
}

System.out.println();
System.out.println("Head of the queue using element() - "+queue.element());
System.out.println("Head of the queue using peek() - "+queue.peek());
queue.remove();
queue.remove();

// new person added to the empty queue using offer()


queue.offer("Emma");

// newly added person removed using poll()


queue.poll();

System.out.println();
System.out.println("Removing the head of the queue using poll when queue is
empty - "+queue.poll()); // returns null since queue is empty

System.out.println("Head of the queue using peek() when queue is empty -


"+queue.peek()); // returns null since queue is empty

/* Uncomment the lines of code given below one at a time and observe the output */
//System.out.println("Head of the queue using element() when queue is empty -
"+queue.element()); // throws NoSuchElementException since queue is empty

//System.out.println("Removing the head of the queue using remove() when queue is


empty");
//queue.remove(); // throws NoSuchElementException since queue is empty

}
}
------------------------
*STACK USING ARRAYDEQUE-TRYOUT*
import java.util.Deque;
import java.util.ArrayDeque;

class Tester {

public static void main(String[] args) {

Deque<Integer> stack = new ArrayDeque<Integer>(); // no restrictions in


capacity
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);

System.out.println("Numbers in stack - After addition of 5 values");


for (Integer val : stack) {
System.out.println(val);
}

stack.pop();
stack.pop();
stack.pop();

System.out.println("\nNumbers in stack - After removal of 3 values");


for (Integer val : stack) {
System.out.println(val);
}

System.out.println();
System.out.println("Top of the stack using peek() - "+stack.peek());

stack.pop();
stack.pop();
System.out.println(stack);
//Uncomment the below code and observe the output
//System.out.println("Trying to remove the element from the top of the stack using pop()
when stack is empty - "+stack.pop(){{//or use stack.poll() if you don't want exception//}}); //
throws NoSuchElementException since stack is empty

}
}
-----------------------
*SET INTERFACE EXERCISE 1*
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

class Student {

private int studentId;


private String studentName;
private int courseId;

public Student(int studentId, String studentName, int courseId) {


this.studentId = studentId;
this.studentName = studentName;
this.courseId = courseId;
}

public int getStudentId() {


return studentId;
}

public void setStudentId(int studentId) {


this.studentId = studentId;
}

public String getStudentName() {


return studentName;
}

public void setStudentName(String studentName) {


this.studentName = studentName;
}

public int getCourseId() {


return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}

@Override
public boolean equals(Object student) {
Student otherStudent = (Student) student;
if (this.studentId == otherStudent.studentId)
return true;
return false;
}

@Override
public int hashCode() {
return studentId;
}

@Override
public String toString() {
return "Student Id: "+studentId + ", Student Name: " + studentName;
}

class Tester {

public static Set<Student> findDuplicateEntries(List<Student> students) {


Set<Student> newstudents = new HashSet<>();
Set<Student> news = new HashSet<>();
for(Student student: students){
if(!newstudents.add(student)){
news.add(student);
}
}
return news;
}

public static void main(String[] args) {


List<Student> students = new ArrayList<Student>();

students.add(new Student(1001, "Dean", 111));


students.add(new Student(1002, "Harley", 112));
students.add(new Student(1003, "Franklin", 113));
students.add(new Student(1005, "Arden", 113));
students.add(new Student(1100, "Juliet", 112));
students.add(new Student(1003, "Franklin", 111));
students.add(new Student(1001, "Dean", 114));

Set<Student> duplicateStudents = findDuplicateEntries(students);


System.out.println("Students who have applied for re-evaluation in more than one
subject");
for(Student student: duplicateStudents)
System.out.println(student);
}
}
----------------------
*HASHMAP EXERCISE 1*
import java.util.Map;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

class Student {

public static Map<String, Double> findMaxMinScorers(Map<String, Double> studentMarks) {


//Implement your logic here and change the return statement accordingly
Double min= Double.MAX_VALUE, max= Double.MIN_VALUE;
for(Entry<String, Double> marks:studentMarks.entrySet()){
min= Math.min(min, marks.getValue());
max= Math.max(max, marks.getValue());
}
int before=0, after=-1;
while(after!=before){
after=0;
for(Entry<String, Double> marks:studentMarks.entrySet()){
if(!marks.getValue().equals(min) && !marks.getValue().equals(max)){
after++;
studentMarks.remove(marks.getKey());
break;
}
}

}
return studentMarks;
}

class Tester {

public static void main(String args[]) {


Map<String, Double> studentMarks = new HashMap<String, Double>();
studentMarks.put("Lily", 90.0);
studentMarks.put("Robin", 68.0);
studentMarks.put("Marshall", 76.5);
studentMarks.put("Neil", 67.0);
studentMarks.put("Ted", 92.0);

Map<String, Double> maxMinScorers =


Student.findMaxMinScorers(studentMarks);

System.out.println("Details of Top Scorers & Low


Scorers\n====================================");
for (Entry<String, Double> entry : maxMinScorers.entrySet()) {
System.out.println(entry.getKey()+" -- "+entry.getValue());
}

}
}
-------------------
*LINKED LIST ASSIGNMENT 1*
import java.util.LinkedList;
import java.util.List;

class Tester {

public static List<Integer> removeDuplicates(List<Integer> list) {


//Implement your logic here and change the return statement accordingly
for(int i=0; i<list.size()-1; i++){
int val1=list.get(i);
for(int j=i+1; j<list.size();j++){
int val2=list.get(j);
if(val1==val2){
list.remove(j);
j--;
}
}
}
return list;
}

public static void main(String args[]) {


List<Integer> list = new LinkedList<Integer>();
list.add(10);
list.add(15);
list.add(21);
list.add(15);
list.add(10);

List<Integer> updatedList = removeDuplicates(list);

System.out.println("Linked list without duplicates");


for (Integer value : updatedList) {
System.out.print(value+" ");
}
}

}
-------------------------
*LINKED LIST ASSIGNMENT 2*
import java.util.LinkedList;
import java.util.List;

class Tester {

public static List<Integer> findCommonElements(List<Integer> listOne, List<Integer>


listTwo){
//Implement your logic here and change the return statement accordingly
List <Integer> newlist= new LinkedList<>();
for(int i=0; i<listOne.size(); i++){
int val1=listOne.get(i);
for(int j=0; j<listTwo.size(); j++){
int val2= listTwo.get(j);
if(val1==val2){
newlist.add(val1);
}
}
}
return newlist;
}
public static void main(String arga[]){

List<Integer> listOne = new LinkedList<Integer>();


listOne.add(10);
listOne.add(12);
listOne.add(21);
listOne.add(1);
listOne.add(53);

List<Integer> listTwo = new LinkedList<Integer>();


listTwo.add(11);
listTwo.add(21);
listTwo.add(25);
listTwo.add(53);
listTwo.add(47);

System.out.println(findCommonElements(listOne, listTwo));
}
}
-------------------------
*LINKED LIST ASSIGNMENT 3*
import java.util.LinkedList;
import java.util.List;

class Tester {

public static List<Integer> mergeLists(List<Integer> listOne, List<Integer> listTwo) {


// Implement your logic here and change the return statement accordingly
if(listOne.size()==0){
return listTwo;
}
if(listTwo.size()==0){
return listOne;
}
List <Integer> newlist= new LinkedList<>();
while(listOne.size()!=0 && listTwo.size()!=0){
int a= listOne.get(0);
int b= listTwo.get(0);
if(a<b){
newlist.add(a);
listOne.remove(0);
}
else{
newlist.add(b);
listTwo.remove(0);
}
}
if(listOne.size()!=0){
while(listOne.size()!=0){
newlist.add(listOne.get(0));
listOne.remove(0);
}
}
if(listTwo.size()!=0){
while(listTwo.size()!=0){
newlist.add(listTwo.get(0));
listTwo.remove(0);
}
}
return newlist;
}

public static void main(String args[]) {


List<Integer> listOne = new LinkedList<Integer>();
listOne.add(10);
listOne.add(13);
listOne.add(21);
listOne.add(42);
listOne.add(56);

List<Integer> listTwo = new LinkedList<Integer>();


listTwo.add(15);
listTwo.add(20);
listTwo.add(21);
listTwo.add(85);
listTwo.add(92);

List<Integer> mergedList = mergeLists(listOne, listTwo);


System.out.println(mergedList);
}
}
-------------------------------
*LINKED LIST ASSIGNMENT 4*
import java.util.LinkedList;
class Queue {
// Implement your logic here
private int maxSize;
private LinkedList <String> queue;
public Queue(int maxSize){
this.maxSize= maxSize;
this.queue= new LinkedList<>();
}
public LinkedList<String> getQueue() {
LinkedList <String> sona= new LinkedList<>();
for(int i=0; i<this.queue.size(); i++){
sona.add(this.queue.get(i));
}
return sona;
}
public boolean isFull(){
return this.queue.size()== maxSize;
}
public boolean isEmpty(){
return this.queue.size()== 0;
}
public boolean enqueue(String data){
if(isFull()){
return false;
}
else{
this.queue.add(data);
return true;
}
}
public boolean dequeue(){
if(isEmpty()){
return false;
}
else{
this.queue.remove();
return true;
}
}
}

class Tester {

public static void main(String arga[]){


Queue queue= new Queue(5);

queue.enqueue("Emily");
queue.enqueue("Lily");
queue.enqueue("Rachel");
queue.enqueue("Rose");

queue.dequeue();
queue.dequeue();

System.out.println(queue.getQueue());
}
}
------------------
*SET INTERFACE ASSIGNMENT 1*
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

class Student {
private int studentId;
private String studentName;
private String emailId;
private String event;

public Student(int studentId, String studentName, String emailId, String event) {


this.studentId = studentId;
this.studentName = studentName;
this.emailId = emailId;
this.event = event;
}

public int getStudentId() {


return studentId;
}

public void setStudentId(int studentId) {


this.studentId = studentId;
}

public String getStudentName() {


return studentName;
}

public void setStudentName(String studentName) {


this.studentName = studentName;
}

public String getEmailId() {


return emailId;
}

public void setEmailId(String emailId) {


this.emailId = emailId;
}

public String getEvent() {


return event;
}

public void setEvent(String event) {


this.event = event;
}

@Override
public boolean equals(Object student) {
Student otherStudent = (Student) student;
if (this.emailId.equals(otherStudent.emailId))
return true;
return false;
}

@Override
public int hashCode() {
return emailId.hashCode();
}

@Override
public String toString() {
return "Student Id: " + studentId + ", Student Name: " + studentName + ", Email
Id: " + emailId;
}
}
class Tester {

public static Set<Student> findUnique(List<Student> students) {


//Implement your logic here and change the return statement accordingly
Set<Student> unique = new HashSet<>();
unique.addAll(students);
return unique;
}

public static Set<Student> findDuplicates(List<Student> students) {


//Implement your logic here and change the return statement accordingly
Set<Student> newstudents = new HashSet<>();
Set<Student> duplicate = new HashSet<>();
for(Student student: students){
if(!newstudents.add(student)){
duplicate.add(student);
}
}
return duplicate;
}

public static void main(String[] args) {


List<Student> students = new ArrayList<Student>();

students.add(new Student(5004, "Wyatt", "Wyatt@example.com","Dance"));


students.add(new Student(5010, "Lucy", "Lucy@example.com","Dance"));
students.add(new Student(5550, "Aaron", "Aaron@example.com","Dance"));
students.add(new Student(5560, "Ruby", "Ruby@example.com","Dance"));
students.add(new Student(5015, "Sophie", "Sophie@example.com","Music"));
students.add(new Student(5013, "Clara", "Clara@example.com","Music"));
students.add(new Student(5010, "Lucy", "Lucy@example.com","Music"));
students.add(new Student(5011, "Ivan", "Ivan@example.com","Music"));
students.add(new Student(5550, "Aaron", "Aaron@example.com","Music"));

Set<Student> studentNominations = findUnique(students);


System.out.println("Students who have submitted nominations");
for(Student student: studentNominations)
System.out.println(student);

Set<Student> duplicateStudents = findDuplicates(students);


System.out.println("Students who have submitted nominations for both the
events");
for(Student student: duplicateStudents)
System.out.println(student);
}
}
------------------
*HASHMAP ASSIGNMENT 1*
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Tester {

public static List<String> sortSales(Map<String, Integer> sales) {


ArrayList<String> names= new ArrayList<>();
for(String str: sales.keySet()){
if(names.size()==0){
names.add(str);
}
else{
int i= names.size();
int sale= sales.get(str);
for(int j= names.size()-1; j>=0; j--){
if(sale<= sales.get(names.get(j))){
break;
}
else i--;
}
names.add(i, str);
}
}
return names;
}

public static void main(String args[]) {


Map<String, Integer> sales = new HashMap<String, Integer>();
sales.put("Mathew", 50);
sales.put("Lisa", 76);
sales.put("Courtney", 45);
sales.put("David", 49);
sales.put("Paul", 49);

List<String> employees = sortSales(sales);


System.out.println("Employees in the decreasing order of their
sales\n=====================================");
for (String employeeName : employees) {
System.out.println(employeeName);
}
}

}
-------------------
*HASHMAP ASSIGNMENT 2*
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

class Tester {

public static Map<String, Integer> mergeMaps(Map<String, Integer> mapOne, Map<String,


Integer> mapTwo){
//Implement your logic here and change the return statement accordingly
for(Entry<String,Integer>entry: mapTwo.entrySet()){
if(mapOne.get(entry.getKey())==null){
mapOne.put(entry.getKey(), entry.getValue());
}
else if(mapOne.get(entry.getKey())!=entry.getValue()){
mapOne.put(entry.getKey()+ "New", entry.getValue());
}
else{
mapOne.put(entry.getKey(), entry.getValue());
}
}
return mapOne;
}

public static void main(String args[]) {


Map<String, Integer> mapOne = new HashMap<String, Integer>();
mapOne.put("Kelly", 10);
mapOne.put("Micheal", 20);
mapOne.put("Ryan", 30);

Map<String, Integer> mapTwo = new HashMap<String, Integer>();


mapTwo.put("Jim", 15);
mapTwo.put("Andy", 45);
Map<String, Integer> mergedMap = mergeMaps(mapOne, mapTwo);

System.out.println("Merged Map\n===========");
for (Entry<String, Integer> entry : mergedMap.entrySet()) {
System.out.println(entry.getKey()+" -- "+entry.getValue());
}

}
}
------------------------
*HASHMAP ASSIGNMENT 3*
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

class Tester {

public static Map<Character, Integer> findOccurrences(String input) {


//Implement your logic here and change the return statement accordingly
HashMap<Character, Integer> charCountMap
= new HashMap<Character, Integer>();
//remove all spaces
input= input.replaceAll("\\s","");

// Converting given string to char array

char[] strArray = input.toCharArray();

// checking each char of strArray


for (char c : strArray) {
if (charCountMap.containsKey(c)) {

// If char is present in charCountMap,


// incrementing it's count by 1
charCountMap.put(c, charCountMap.get(c) + 1);
}
else {

// If char is not present in charCountMap,


// putting this char to charCountMap with 1 as it's value
charCountMap.put(c, 1);
}
}
// Printing the charCountMap

return charCountMap;
}

public static void main(String args[]) {

String input = "occurrence";


Map<Character, Integer> occurrenceMap = findOccurrences(input);

System.out.println("Occurrences of characters\n=======================");
for (Entry<Character, Integer> entry : occurrenceMap.entrySet()) {
System.out.println(entry.getKey()+" -- "+entry.getValue());
}

}
----------------------
*QUEUE INTERFACE EXERCISE 1*
import java.util.Deque;
import java.util.ArrayDeque;

class Tester {

public static Deque<Object> mergeQueue(Deque<Integer> intQueue, Deque<Character>


charQueue) {
ArrayDeque<Object> outQueue= new ArrayDeque<Object>();
while(!intQueue.isEmpty()||!charQueue.isEmpty()){
if(!intQueue.isEmpty()){
Integer integerData= intQueue.poll();
outQueue.add(integerData);
}
if(!charQueue.isEmpty()){
Character characterData= charQueue.poll();
outQueue.add(characterData);
}
}
return outQueue;
}
public static void main(String[] args) {

Deque<Integer> integerQueue = new ArrayDeque<Integer>();


integerQueue.add(3);
integerQueue.add(6);
integerQueue.add(9);

Deque<Character> characterQueue = new ArrayDeque<Character>();


characterQueue.add('a');
characterQueue.add('e');
characterQueue.add('i');
characterQueue.add('o');
characterQueue.add('u');
characterQueue.add('b');

Deque<Object> mergedQueue = mergeQueue(integerQueue, characterQueue);

System.out.println("The elements in the merged queue are:");


for(Object element: mergedQueue)
System.out.println(element);

}
}
-------------------
*QUEUE INTERFACE EXERCISE 2*
import java.util.Deque;
import java.util.ArrayDeque;

class Tester {

public static Deque<Integer> changeSmallest(Deque<Integer> inputStack) {


int smallest= smallest(inputStack);
Deque<Integer> ans= new ArrayDeque<Integer>();
while(inputStack.size()!=0){
int element= inputStack.removeLast();
if(element==smallest)
ans.addLast(element);
else
ans.addFirst(element);
}

return ans;
}
public static int smallest(Deque<Integer> st){

if(st.size()==0)

return Integer.MAX_VALUE;

int crr= st.removeFirst();

int rv= smallest(st);

st.addFirst(crr);

return Math.min(crr,rv);

public static void main(String[] args) {

Deque<Integer> inputStack = new ArrayDeque<Integer>();


inputStack.push(10);
inputStack.push(8);
inputStack.push(5);
inputStack.push(12);
inputStack.push(5);

Deque<Integer> updatedStack = changeSmallest(inputStack);

System.out.println("Stack After Modification:");


for (Integer value : updatedStack)
System.out.println(value);
}
}
-------------------
*QUEUE INTERFACE ASSIGNMENT 1*
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

class Patient {

private String name;


private String gender;
private int age;

public Patient(String name, String gender, int age) {


this.name = name;
this.gender = gender;
this.age = age;
}

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "Name: "+this.name+", Gender: "+this.gender+", Age: "+this.age;
}
}

class Tester {

public static List<Deque<Patient>> splitQueue(Deque<Patient> patientsQueue) {


//Implement your logic here and change the return statement accordingly
ArrayList <Deque<Patient>> ans= new ArrayList<>();
Deque <Patient> senior= new ArrayDeque<>();
Deque <Patient> rest= new ArrayDeque<>();
while(patientsQueue.size()!=0){
Patient curr= patientsQueue.removeFirst();
if(curr.getAge()>=60)
senior.addLast(curr);
else rest.addLast(curr);
}
ans.add(senior);
ans.add(rest);
return ans;
}

public static void main(String[] args) {

Patient patient1=new Patient("Jack","Male",25);


Patient patient2=new Patient("Tom","Male",64);
Patient patient3=new Patient("Simona","Female",24);

Deque<Patient> patientsQueue = new ArrayDeque<Patient>();


patientsQueue.add(patient1);
patientsQueue.add(patient2);
patientsQueue.add(patient3);

List<Deque<Patient>> queuesList = splitQueue(patientsQueue);

int counter=0;
for (Deque<Patient> queue : queuesList) {
if(counter==0)
System.out.println("Patients in the senior
queue\n============================");
else
System.out.println("Patients in the normal
queue\n============================");

for (Patient patient : queue) {


System.out.println("Name : "+patient.getName());
System.out.println("Age : "+patient.getAge());
System.out.println();
}
counter++;
}
}

}
-------------------
*QUEUE INTERFACE ASSIGNMENT 2*
import java.util.ArrayDeque;
import java.util.Deque;

class Tester {

public static Deque<Character> updateStack(Deque<Character> inputStack) {


//Implement your logic here and change the return statement accordingly
for(int i=0; i<inputStack.size()-3;i++){
inputStack.addLast(inputStack.removeFirst());
}
return inputStack;
}

public static void main(String[] args) {

Deque<Character> inputStack = new ArrayDeque<Character>();


inputStack.push('E');
inputStack.push('D');
inputStack.push('C');
inputStack.push('B');
inputStack.push('A');

Deque<Character> resultStack = updateStack(inputStack);

System.out.println("The alphabets in updated stack are:");


for(Character alphabet: resultStack)
System.out.println(alphabet);
}
}
-------------------
========================
*DAY 5*
======================
*TIME COMPLEXITY COMPARISON TRYOUT*
class Tester {

public static double factorial(double n) {


double fact=1;
for(double i=1;i<=n;i++) {
fact=fact*i;
}
return fact;
}

public static void comparingComplexities(double n) {


System.out.println("Values of different complexities for n = "+n);
System.out.println("O(1) = "+1);
System.out.println("O(log(log(n))) = "+Math.log(Math.log(n)));
System.out.println("O(log(n)) = "+Math.log(n));
System.out.println("O(sqrt(n)) = "+Math.sqrt(n));
System.out.println("O(n) = "+n);
System.out.println("O(nlog(n)) = "+n*Math.log(n));
System.out.println("O(n^2) = "+Math.pow(n, 2));
System.out.println("O(n^3) = "+Math.pow(n, 3));
System.out.println("O(2^n) = "+Math.pow(2,n));
System.out.println("O(e^n) = "+Math.exp(n));
System.out.println("O(n!) = "+factorial(n));
}

public static void main(String args[]) {


comparingComplexities(10);
System.out.println("-------------------------------");
comparingComplexities(100);
//Try out with different values of n
}
}
---------------------------------------
*ANALYSIS OF ALGORITHMS EXERCISE 1*
public static int getCount(int arr[], int n) {
int count1 = 0;
int count2 = 0;
int index;
for (int index1 = 0; index1 < n - 1; index1++)
for (int index2 = index1 + 1; index2 < n; index2++)
if (arr[index1] > arr[index2])
count1++;
else {
index=index2;
count2=0;
while(index>i) {
count2++;
index--;
}
}
return Math.max(count1, count2);
}
ANSWER: O(N^3)
------------------------------
*ANALYSIS OF ALGORITHMS ASSIGNMENT 1*
public static int calculateGCD(int num1, int num2) {
int temp;
if (num1%num2 ==0)
return num2;
if (num1 < num2) {
temp=num1;
num1=num2;
num2=temp;
}
while (num2 > 0) {
num1 = num1%num2;
temp=num1;
num1=num2;
num2=temp;
}
return num1;
}
ANSWER: O(NUM2)
-------------------------
*ALSO CALLED BRUTEFORCING*
*LINEAR SEARCH- TRYOUT*
class Tester {

public static int search(int arrayOfElements[], int elementToBeSearched) {


for (int index = 0; index < arrayOfElements.length; index++) {
// Returning the index of the element if the element is found
if (arrayOfElements[index] == elementToBeSearched)
return index;
}
// Returning -1 if the element is not found
return -1;
}

public static void main(String[] args) {


int[] arrayOfElements = { 10, 39, 45, 47, 50, 15, 23, 32, 25, 49 };
int elementToBeSearched = 50;

int index = search(arrayOfElements, elementToBeSearched);


// Checking whether the element has been found or not
if (index == -1)
System.out.println("Element is not present in the array!");
else
System.out.println("Element is found at index position " + index+"!");
}
}
----------------------------
*LINEAR SEARCH EXERCISE 1*
class Tester {
public static int searchElement(int[] elements, int elementToBeSearched) {
//Implement your logic here and change the return statement accordingly

for (int index = 0; index < elements.length; index++) {


// Returning the pass of the element if the element is found
if (elements[index] == elementToBeSearched)
return index+1;
}
// Returning -1 if the element is not found
return -1;
}

public static void main(String[] args) {


int[] elements = { 76, 24, 78, 98, 1 };
int elementToBeSearched = 78;

int numberOfIterations = searchElement(elements, elementToBeSearched);

if (numberOfIterations == -1)
System.out.println("Element not found!");
else
System.out.println("Element found! Number of iterations required to find
the element : " + numberOfIterations);
}

}
---------------------------
*BINARY SEARCH TRYOUT 1*
class Tester {

public static int search(int arrayOfElements[], int elementToBeSearched) {


int low = 0;
int high = arrayOfElements.length -1 ;
int mid;
while (low <= high) {
mid = (low + high)/2;

//Checking if the element is present in the mid position


if (arrayOfElements[mid] == elementToBeSearched)
return mid;

// If the element is greater than the element in the mid position,


// low is updated
if (arrayOfElements[mid] < elementToBeSearched)
low = mid+1;

// Else high is updated


else
high = mid - 1;
}

//-1 is being returned when the element is not present in the array
return -1;
}

public static void main(String[] args) {


int[] arrayOfElements = {10,15,23,25,32,39,45,47,49,50};
int elementToBeSearched = 50;

int index = search(arrayOfElements, elementToBeSearched);


if (index == -1)
System.out.println("Element is not present in the array");
else
System.out.println("Element found at position : " + index);
}
}
------------------------
*BINARY SEARCH TRYOUT 2*// RECURSION USED
class Tester {

public static int search(int arrayOfElements[],int low,int high,int elementToBeSearched) {


if (low <= high) {
int mid = (low + high) / 2;

if (arrayOfElements[mid] == elementToBeSearched)
return mid;

else if (arrayOfElements[mid] < elementToBeSearched)


return search(arrayOfElements, mid + 1, high, elementToBeSearched);
else
return search(arrayOfElements, low, mid - 1, elementToBeSearched);
}
return -1;
}

public static void main(String[] args) {


int[] arrayOfElements = {10,15,23,25,32,39,45,47,49,50};
int elementToBeSearched = 50;
int low = 0;
int high = arrayOfElements.length - 1;
int index = search(arrayOfElements,low,high, elementToBeSearched);
if (index == -1)
System.out.println("Element is not present in the array");
else
System.out.println("Element found at position : " + index);
}
}
----------------------------
*BINARY SEARCH EXERCISE*
class Tester {

public static int iterations=0;

public static int searchElement(int elements[],int low,int high,int elementToBeSearched)


{
if (low <= high) {
int mid = (low + high) / 2;
iterations++;

if (elements[mid] == elementToBeSearched)
return mid;

else if (elements[mid] < elementToBeSearched)


return searchElement(elements, mid + 1, high, elementToBeSearched);
else
return searchElement(elements, low, mid - 1, elementToBeSearched);
}
return -1;
}

public static void main(String[] args) {


int[] elements = { 1, 23, 43, 46, 78, 90 };
int elementToBeSearched = 43;

int indexPosition=searchElement(elements, 0, elements.length-1,


elementToBeSearched);

if (indexPosition == -1)
System.out.println("Element not found!");
else
System.out.println("Element found at index position " + indexPosition+"!");

System.out.println("Number of iterations: "+iterations);


}

}
-------------------------
*LINEAR SEARCH ASSIGNMENT 1*
class Tester {

public static int searchEmployeeId(int[] employeeIds, int employeeIdToBeSearched) {


for (int index = 0; index < employeeIds.length; index++) {
// Returning the pass of the element if the element is found
if (employeeIds[index] == employeeIdToBeSearched)
return index+1;
}
// Returning -1 if the element is not found
return -1;
}

public static void main(String a[]) {


int[] employeeIds = { 8011, 8012, 8015, 8016, 8020, 8022, 8025 };
int employeeIdToBeSearched = 8022;

int numberOfIterations = searchEmployeeId(employeeIds,


employeeIdToBeSearched);

if (numberOfIterations == -1)
System.out.println("Employee Id " + employeeIdToBeSearched + " is not
found!");
else
System.out.println("Employee Id " + employeeIdToBeSearched + " is
found! Number of iterations : " + numberOfIterations);
}
}
---------------------------
*BINARY SEARCH ASSIGNMENT 1*
class Tester {

public static int searchCustomerId(int customerIds[], int customerIdToBeSearched) {


int low = 0;
int high = customerIds.length -1 ;
int mid;
while (low <= high) {
mid = (low + high)/2;

//Checking if the element is present in the mid position


if (customerIds[mid] == customerIdToBeSearched)
return mid;

// If the element is greater than the element in the mid position,


// low is updated
if (customerIds[mid] < customerIdToBeSearched)
low = mid+1;

// Else high is updated


else
high = mid - 1;
}

//-1 is being returned when the element is not present in the array
return -1;
}

public static void main(String[] args) {


int[] customerIds = { 80451, 80462, 80465, 80479, 80550, 80561, 80665, 80770
};
int customerIdToBeSearched = 80462;

int index = searchCustomerId(customerIds, customerIdToBeSearched);

if (index == -1)
System.out.println("Customer Id " + customerIdToBeSearched + " is not
found!");
else
System.out.println("Customer Id " + customerIdToBeSearched + " is
found at index position " + index+"!");
}

}
-----------------------------
=============================
DAY 6
=============================
*BUBBLE SORT*
> NO OF PASSESS DOESN'T DEPEND ON INPUT SIZE
> NO OF SWAPS AND PASSES ARE NOT EQUAL
> 1 EXTRA PASS IS REQUIRED EVEN AFTER SORTING
-----------------------
*BUBBLE SORT TRYOUT*
class Tester {
static int noOfSwaps = 0;
static int noOfPasses = 0;

public static void swap(int[] numbers, int firstIndex, int secondIndex) {


int temp = numbers[firstIndex];
numbers[firstIndex] = numbers[secondIndex];
numbers[secondIndex] = temp;
noOfSwaps += 1;
}

public static void bubbleSort(int[] numbers) {


int length = numbers.length;

for (int index1 = 0; index1 < (length - 1); index1++) {


boolean swapped = false;
noOfPasses += 1;
for (int index2 = 0; index2 < (length - index1 - 1); index2++) {
if (numbers[index2] > numbers[index2 + 1]) {
swap(numbers, index2, index2 + 1);
swapped = true;
}
}
if (swapped == false)
break;
}
}

public static void main(String[] args) {

int[] numbers = { 48, 40, 35, 49, 33 };


System.out.println("Given array:");
for (int number : numbers) {
System.out.println(number);
}

bubbleSort(numbers);

System.out.println("Sorted array:");
for (int number : numbers) {
System.out.println(number);
}

System.out.println("No. of passes: " + noOfPasses);


System.out.println("No. of swaps: " + noOfSwaps);
}
}
-----------------------
*BUBBLE SORT-EXERCISE 1*
class Tester {
static int noOfSwaps = 0;
static int noOfPasses = 0;

public static void swap(int[] elements, int firstIndex, int secondIndex) {


// Implement your logic here
int temp = elements[firstIndex];
elements[firstIndex] = elements[secondIndex];
elements[secondIndex] = temp;
noOfSwaps += 1;
}

public static int bubbleSort(int[] elements) {


// Implement your logic here and change the return statement accordingly
int length = elements.length;

for (int index1 = 0; index1 < (length - 1); index1++) {


boolean swapped = false;
noOfPasses += 1;
for (int index2 = 0; index2 < (length - index1 - 1); index2++) {
if (elements[index2] > elements[index2 + 1]) {
swap(elements, index2, index2 + 1);
swapped = true;
}
}
if (swapped == false)
break;
}
return noOfPasses;
}

public static void displayArray(int[] elements) {


for (int element : elements)
System.out.print(element + " ");
System.out.println();
}

public static void main(String[] args) {

int[] elements = { 23, 67, 45, 76, 34, 68, 90 };

System.out.println("Given array:");
displayArray(elements);

int noOfPasses = bubbleSort(elements);

System.out.println("==========================");
System.out.println("Total number of passes needed to sort the array: " +
noOfPasses);
System.out.println("==========================");

System.out.println("Array after sorting:");


displayArray(elements);

}
}
----------------------
*MERGE SORT TRYOUT*
class Tester {
public static void main(String[] args) {
int[] arr = { 19, 8, 16, 26, 45, 76 };
mergeSort(arr, arr.length);
for (int number : arr)
System.out.println(number);
}

public static void mergeSort(int[] arr, int size) {


if (size < 2)
return;

int mid = size / 2; //Dividing the array into two halves


int[] left = new int[mid]; //Creating temporary array to the left of the mid value
int[] right = new int[size - mid]; //Creating temporary array to the right of the mid
value

//Copying data to temporary arrays


for (int index = 0; index < mid; index++)
left[index] = arr[index];

for (int index = mid; index < size; index++)


right[index - mid] = arr[index];

//Invoking mergeSort() by passing left array


mergeSort(left, mid);

//Invoking mergeSort() by passing right array


mergeSort(right, size - mid);

//Invoking merge() by passing the arrays returned


merge(arr, left, right, mid, size - mid);
}

public static void merge(int[] arr, int[] left, int[] right, int leftMerge, int rightMerge) {

int firstIndex = 0; //initial index of first sub-array


int secondIndex = 0; //initial index of second sub-array
int thirdIndex = 0; //initial index of merged sub-array

while (firstIndex < leftMerge && secondIndex < rightMerge) {


if (left[firstIndex] <= right[secondIndex])
arr[thirdIndex++] = left[firstIndex++];
else
arr[thirdIndex++] = right[secondIndex++];
}

while (firstIndex < leftMerge)


arr[thirdIndex++] = left[firstIndex++];

while (secondIndex < rightMerge)


arr[thirdIndex++] = right[secondIndex++];
}
}
----------------------------
*MERGE SORT EXERCISE 1*
class Tester {

public static void mergeSort(int[] elements, int size) {


//Implement your logic here
if (size < 2)
return;

int mid = size / 2; //Dividing the array into two halves


int[] left = new int[mid]; //Creating temporary array to the left of the mid value
int[] right = new int[size - mid]; //Creating temporary array to the right of the mid
value

//Copying data to temporary arrays


for (int index = 0; index < mid; index++)
left[index] = elements[index];

for (int index = mid; index < size; index++)


right[index - mid] = elements[index];

//Invoking mergeSort() by passing left array


mergeSort(left, mid);

//Invoking mergeSort() by passing right array


mergeSort(right, size - mid);

//Invoking merge() by passing the arrays returned


merge(elements, left, right, mid, size - mid);
}

public static void merge(int[] elements, int[] left, int[] right, int leftMerge, int rightMerge) {
//Implement your logic here
int firstIndex = 0; //initial index of first sub-array
int secondIndex = 0; //initial index of second sub-array
int thirdIndex = 0; //initial index of merged sub-array
while (firstIndex < leftMerge && secondIndex < rightMerge) {
if (left[firstIndex] <= right[secondIndex])
elements[thirdIndex++] = left[firstIndex++];
else
elements[thirdIndex++] = right[secondIndex++];
}

while (firstIndex < leftMerge)


elements[thirdIndex++] = left[firstIndex++];

while (secondIndex < rightMerge)


elements[thirdIndex++] = right[secondIndex++];

public static void displayArray(int[] elements) {


for(int element:elements)
System.out.print(element+" ");
System.out.println();
}

public static void main(String[] args) {


int[] elements = { 95, 56, 20, 98, 34, 77, 80 };

System.out.println("Given Array:");
displayArray(elements);

mergeSort(elements, elements.length);

System.out.println("Sorted Array:");
displayArray(elements);

}
----------------------------
*BUBBLE SORT ASSIGNMENT 1*
class Tester {
static int noOfSwaps = 0;
static int noOfPasses = 0;

public static void sortArray(int arr[]) {


// Implement your logic here
int length = arr.length;

for (int index1 = 0; index1 < (length - 1); index1++) {


boolean swapped = false;
noOfPasses += 1;
for (int index2 = 0; index2 < (length - index1 - 1); index2++) {
if (arr[index2] > arr[index2 + 1]) {
int temp = arr[index2];
arr[index2] = arr[index2+1];
arr[index2+1] = temp;
noOfSwaps += 1;
swapped = true;
}
}
if (swapped == false)
break;
}
}

public static int findMaxSum(int arr[], int m) {


// Implement your logic here and change the return statement accordingly
int sum=0;
int a=arr.length-1;
if(m>arr.length)
return 0;
else{
for(int i=0; i<m; i++){
sum=sum+arr[a--];
}
}
return sum;
}

public static int findMinSum(int arr[], int m) {


// Implement your logic here and change the return statement accordingly
int sum=0;
if(m>arr.length)
return 0;
else{
for(int i=0; i<m; i++){
sum=sum+arr[i];
}
}
return sum;
}

public static void main(String[] args) {


int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
sortArray(arr);
System.out.println("Maximum Sum for m=4: " + findMaxSum(arr, 4));
System.out.println("Minimum Sum for m=3: " + findMinSum(arr, 3));
}

}
----------------------
*MERGE SORT ASSIGNMENT 1*
class Tester {

public static void mergeSort(int[] elements, int size) {


//Implement your logic here
//Implement your logic here
if (size < 2)
return;

int mid = size / 2; //Dividing the array into two halves


int[] left = new int[mid]; //Creating temporary array to the left of the mid value
int[] right = new int[size - mid]; //Creating temporary array to the right of the mid
value

//Copying data to temporary arrays


for (int index = 0; index < mid; index++)
left[index] = elements[index];

for (int index = mid; index < size; index++)


right[index - mid] = elements[index];

//Invoking mergeSort() by passing left array


mergeSort(left, mid);

//Invoking mergeSort() by passing right array


mergeSort(right, size - mid);

//Invoking merge() by passing the arrays returned


merge(elements, left, right, mid, size - mid);
}
public static void merge(int[] elements, int left[], int right[], int leftMerge, int rightMerge) {
//Implement your logic here
int firstIndex = 0; //initial index of first sub-array
int secondIndex = 0; //initial index of second sub-array
int thirdIndex = 0; //initial index of merged sub-array

while (firstIndex < leftMerge && secondIndex < rightMerge) {


if (left[firstIndex] <= right[secondIndex])
elements[thirdIndex++] = left[firstIndex++];
else
elements[thirdIndex++] = right[secondIndex++];
}

while (firstIndex < leftMerge)


elements[thirdIndex++] = left[firstIndex++];

while (secondIndex < rightMerge)


elements[thirdIndex++] = right[secondIndex++];
}

public static double findMedian(int elements[]) {


double med=0;
int length= elements.length;
//Implement your logic here and change the return statement accordingly
if(elements.length==0)
return -1;
if(elements.length==1)
return -1;
if(elements.length%2==0){
med= (double)(elements[(length - 1) / 2] + elements[length / 2]) / 2.0;
}
else{
med= (double)elements[length / 2];
}
return med;
}

public static void main(String[] args) {


int elements[] = { 64, 34, 25, 12, 22, 11, 90 };
mergeSort(elements, elements.length);
System.out.println("Median: "+findMedian(elements));
}
}
------------------
*BRUTE FORCE EXERCISE 1*
class Tester {

public static int calculatePower(int num, int p) {


//Implement your logic here and change the return statement accordingly
int product=1;
for(int i=1; i<=p; i++){
product*=num;
}
return product;
}

public static void main(String[] args) {


System.out.println(calculatePower(2,3));
}
}
---------------------------
*DIVIDE AND CONQUER EXERCISE 1*
class Tester {
public static int[] getMaxMin(int arr[], int low, int high) {
//Implement your logic here and change the return statement accordingly
int max;
int min;
if ( low == high )
{
max = arr[low];
min = arr[low];
}
else if ( low + 1 == high )
{
if ( arr[low] < arr[high] )
{
max = arr[high];
min = arr[low];
}
else
{
max = arr[low];
min = arr[high];
}
}
else
{
int mid = low + (high - low)/2;
int left[] = getMaxMin(arr, low, mid);
int right[] = getMaxMin(arr, mid+1, high);
if ( left[0] > right[0] )
max = left[0];
else
max = right[0];
if ( left[1] < right[1] )
min = left[1];
else
min = right[1];
}
int ans[] ={max, min};
return ans;
}

public static void main(String args[]) {


int arr[] = {1000, 10, 5, 1, 2000};

int[] maxMin = getMaxMin(arr, 0, arr.length - 1);

System.out.println("Minimum value is "+ maxMin[1]);


System.out.println("Maximum value is "+ maxMin[0]);
}
}
-------------------------------
*GREEDY APPROACH EXERCISE 1*
class Tester {

public static int findMaxActivities(int start[], int finish[]) {


//Implement your logic here and change the return statement accordingly
int n= finish.length;
int i,j;
int count=1;
i=0;
for(j=1; j<n; j++){
if(start[j]>=finish[i]){
count++;
i=j;
}
}
return count;
}

public static void main(String[] args) {


int start[] = {1, 3, 0, 5, 8, 5};
int finish[] = {2, 4, 6, 7, 9, 9};

System.out.println("Maximum number of activities: "+findMaxActivities(start, finish));


}
}
-------------------------------
*DYNAMIC PROGRAMMING- TRYOUT 1*// RECURSIVE
class Tester {

public static int fibonacci(int num) {


//If passed input is 0, return 0
if (num == 0)
return 0;
//If passed input is 1, return 1
else if(num == 1)
return 1;
else
return fibonacci(num - 1) + fibonacci(num - 2);
}

public static void main(String[] args) {


int num = 30;
System.out.println(num+"th fibaonacci number: "+fibonacci(num));
}
}
------------------------------
*DYNAMIC PROGRAMMING TRYOUT 2*// DYNAMIC
class Tester {

public static int fibonacci(int num) {


//Declare an array to store Fibonacci numbers
int f[] = new int[num + 1];
int index;

//0th and 1st number of the series are 0 and 1


f[0] = 0;

if (num > 0) {
f[1] = 1;
for (index = 2; index <= num; index++) {
//Add the previous 2 numbers in the series and store the sum
f[index] = f[index - 1] + f[index - 2];
}
}

return f[num];
}

public static void main(String[] args) {


int num = 30;
System.out.println(num+"th fibonacci number : "+fibonacci(num));
}
}
---------------------------
*DYNAMIC PROGRAMMING EXERCISE 1*
class Tester {

public static int cutRod(int[] price, int n) {


//Implement your logic here and change the return statement accordingly
int val[] = new int[n+1];
val[0] = 0;

// Build the table val[] in bottom up manner and return


// the last entry from the table
for (int i = 1; i<=n; i++)
{
int max_val = Integer.MIN_VALUE;
for (int j = 0; j < i; j++)
max_val = Math.max(max_val,
price[j] + val[i-j-1]);
val[i] = max_val;
}

return val[n];
}

public static void main(String[] args) {


int price [] = { 1, 5, 8, 9, 10, 17, 17, 20 };
int n = 4;
System.out.println("Maximum price: " + cutRod(price, n));
}
}
---------------------------
*BRUTE FORCE ASSIGNMENT 1*
class Tester {

public static int[][] multiply(int arr1[][],int arr2[][]) {


//Implement your logic here and change the return statement accordingly
int c[][]= new int[2][2];
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
c[i][j]=0;
for(int k=0;k<2;k++)
{
c[i][j]+=arr1[i][k]*arr2[k][j];
}//end of k loop
}
}
return c;
}

public static void main(String[] args) {


int arr1[][]=new int [][] {{2,4},{1,4}};
int arr2[][]=new int [][] {{1,4},{1,3}};

int[][] arr3=multiply(arr1,arr2);

for(int index1=0;index1<arr3.length;index1++){
for(int index2=0;index2<arr3.length;index2++){
System.out.print(arr3[index1][index2]+" ");
}
System.out.println();
}
}
}
-------------------------------
*DIVIDE AND CONQUER ASSIGNMENT 1*
class Tester {

public static int findMaxSum(int arr[], int low, int high) {


// Implement your logic here and change the return statement accordingly
// Base Case: Only one element
if (low == high)
return arr[low];
// Find middle point
int mid = (low + high)/2;

/* Return maximum of following three


possible cases:
a) Maximum subarray sum in left half
b) Maximum subarray sum in right half
c) Maximum subarray sum such that the
subarray crosses the midpoint */
return Math.max(Math.max(findMaxSum(arr, low, mid),
findMaxSum(arr, mid+1, high)),
findMaxCrossingSubarraySum(arr, low, mid, high));
}

public static int findMaxCrossingSubarraySum(int arr[], int low, int mid, int high) {
// Implement your logic here and change the return statement accordingly
// Include elements on left of mid.
int sum = 0;
int left_sum = Integer.MIN_VALUE;
for (int i = mid; i >= low; i--)
{
sum = sum + arr[i];
if (sum > left_sum)
left_sum = sum;
}

// Include elements on right of mid


sum = 0;
int right_sum = Integer.MIN_VALUE;
for (int i = mid + 1; i <= high; i++)
{
sum = sum + arr[i];
if (sum > right_sum)
right_sum = sum;
}

// Return sum of elements on left


// and right of mid
// returning only left_sum + right_sum will fail for [-2, 1]
return Math.max(left_sum + right_sum, Math.max(left_sum, right_sum));
}
public static void main(String[] args) {
int arr[] = { -2, -5, 6, -2, -3, 1, 5, -6 };
System.out.println("Maximum sum: " + findMaxSum(arr, 0, arr.length - 1));
}
}
----------------------------
*GREEDY APRROACH ASSIGNMENT 1*
import java.util.*;
class Tester {

public static int findSwapCount(String inputString) {


//Implement your logic here and change the return statement accordingly
// Keep track of '['
Vector<Integer> pos = new Vector<Integer>();
for(int i = 0; i < inputString.length(); ++i)
if (inputString.charAt(i) == '(')
pos.add(i);

// To count number of encountered '['


int count = 0;

// To track position of next '[' in pos


int p = 0;

// To store result
int sum = 0;

char[] S = inputString.toCharArray();

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


{

// Increment count and move p


// to next position
if (S[i] == '(')
{
++count;
++p;
}
else if (S[i] == ')')
--count;

// We have encountered an
// unbalanced part of string
if (count < 0)
{

// Increment sum by number of


// swaps required i.e. position
// of next '[' - current position
sum += pos.get(p) - i;
char temp = S[i];
S[i] = S[pos.get(p)];
S[pos.get(p)] = temp;
++p;

// Reset count to 1
count = 1;
}
}
return sum;
}

public static void main(String args[]) {


String inputString = "())()(";
System.out.println("Number of swaps: "+findSwapCount(inputString));
}

}
---------------------------
*DYNAMIC PROGRAMMING ASSIGNMENT 1*
import java.util.ArrayList;
import java.util.List;

class Tester {

static int count=0;

public static void findWordSegments(List<String> wordsList, String inputString) {


//Implement your logic here
// if we have reached the end of the String,
// print the output String

if (inputString.length() == 0)
{
count++;
}

for (int i = 1; i <= inputString.length(); i++)


{
// consider all prefixes of current String
String prefix = inputString.substring(0, i);

// if the prefix is present in the dictionary, add prefix to the


// output String and recur for remaining String

if (wordsList.contains(prefix)) {
findWordSegments(wordsList, inputString.substring(i));
}
}
}

public static void main(String[] args){


List<String> wordsList = new ArrayList<String>();
wordsList.add("i");
wordsList.add("like");
wordsList.add("pizza");
wordsList.add("li");
wordsList.add("ke");
wordsList.add("pi");
wordsList.add("zza");

String inputString = "ilikepizza";


findWordSegments(wordsList, inputString);
System.out.println("Number of segments: "+count);
}
}
----------------------------------

You might also like