You are on page 1of 18

Final Exam Spring-2021

FACULTY OF ENGINEERING, SCIENCES AND TECHNOLOGY

Subject: Data Structures and Algorithms (Lab)


Instructor(s): Rukhsana Majeed/ Sania Mariam
Submission Date: 31st May 2021 Submission Day: Monday
Name: Mahrukh Batool Student ID: 46889

Program: BSCS

Max. Marks: 40 Please follow the instructions carefully:

1. Write your answers directly on the Black Board (recommended) or upload word file
before the due date on Blackboard.

2. Write your name and registration ID on the first page of your Word file.
3. Answer scripts can only be uploaded on Blackboard only during the submission time.
4. To avoid any unforeseen problems, you are advised to follow the Guide lines
communicated by the Faculty Members.

5. Submission of answer copy(ies) will be considered acceptable through


Blackboard only.
Therefore, do not submit your document through email or any other medium.
6. Use 12 pt. font size and Times New Roman font style along with 1-inch page margins.
7. Follow the requirements of the word limit and the marking criteria while writing your
answers.

8. Provide relevant, original and conceptual answers, as this exam aims to test your
ability to examine, explain, modify or develop concepts discussed in class.

9. Do not copy answers from the internet or other sources. The plagiarism of your
answers may be checked through Turnitin.

10. Double check your word file before uploading it on BlackBoard to ensure that you
have uploaded the correct file with your answers.
Question no 01: [15 Marks]

Write a simulation of T20 match. There are two teams, Team A and Team B. For every ball
delivered generate a random number from -1 to 6 (both inclusive). A -1 means that batsman is
out, any other number is the runs scored on that delivery. A 0 in this case represent a dot ball.
After every 12 balls, generate a random value which represents the weather conditions.

Random Number Weather Condition Score Limits


0 Sunny 0-6
1 Cloudy 0-4
2 Windy 0-3
3 Drizzle 0-2
4 Rain Match stopped

Team A plays continuously until all players are out or 120 balls are delivered or match is stopped
due to the rain.
Team B plays continuously until all players are out or 120 balls are delivered they have scored
more than Team A or match is stopped due to rain. Every time a rain event occurs, deduct 12
balls from both innings. A match result should be draw if any of the innings is less than 18
balls. You have to maintain 2d array, store player id and player score. Count total scores of
teams depending upon preceding information. At the end of match announce the wining team
and Man of the match also.
Answer 01:
 CODE:
package Mahrukh_46889;
import java.util.*;

class match
{
public static void main(String[] args) {

Random r = new Random();


String teamA[][] = new String[11][2];
String teamB[][] = new String[11][2];

int out=0;
int balls[]=new int[120];
int score=0;
int weather=0;
int players=1;
int totalScore=0;
int ballsbowled=0;

for (int i=1;i<=120 ;i++ ) {

if(i%12==0){
weather =r.nextInt(5);
}
if (weather==4) {
if(players==1){
teamA[0][0]="Player"+players;
teamA[0][1]=Integer.toString(score);
}
else{
teamA[players-1][0]="Player"+players;
teamA[players-1][1]=Integer.toString(score);
}
ballsbowled=i-1;
break;

}
else if(players>11){
ballsbowled=i;
break;
}
else
{
int ballval;
if (weather==0) {
ballval= -1+r.nextInt(7);
}
else if (weather==1) {
ballval= -1+r.nextInt(5);
}
else if (weather==2) {
ballval= -1+r.nextInt(4);

}
else{
ballval= -1+r.nextInt(3);
}

if (ballval==-1) {
out+=1;
totalScore+=score;
teamA[players-1][0]="Player"+players;
teamA[players-1][1]=Integer.toString(score);
players+=1;
score=0;

}
else
{
score+=ballval;
balls[i-1]=ballval;
}
}

if (ballsbowled<18) {
System.out.println("Match drawn");

}
else{

int deduct=0;
int b=120;
int outB=0;
score=0;
weather=0;
players=1;
int totalScoreA=totalScore;
int totalScoreB=0;
int v=0;

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

if(i%12==0){
weather =r.nextInt(5);

if (weather==4) {
b-=12;
deduct+=12;
totalScoreA=0;

for (int j=0;j<ballsbowled-deduct ;j++ ) {


totalScoreA+=balls[j];

}
}

if(players>11){
v=i;
break;
}
else if (totalScoreB>totalScoreA) {
v=i;
break;
}
else
{

int ballval;
if (weather==0) {
ballval= -1+r.nextInt(7);
}
else if (weather==1) {
ballval= -1+r.nextInt(5);
}
else if (weather==2) {
ballval= -1+r.nextInt(4);

}
else{
ballval= -1+r.nextInt(3);
}

if (ballval==-1) {
outB+=1;
teamB[players-1][0]="Player"+players;
teamB[players-1][1]=Integer.toString(score);
players+=1;
score=0;

}
else
{
score+=ballval;
totalScoreB+=ballval;
}

if (b<18) {
System.out.println("Match Drawn");

}
else{
System.out.println("Total Balls Bowled for TeamA - "+ballsbowled);
System.out.println("Team A Scores : \n");
for (int i=0;i<out ;i++ ) {
System.out.println(teamA[i][0]+" - "+teamA[i][1]);

}
System.out.println("\nTotal Score of TeamA - "+totalScore);
System.out.println("\nTotal Balls Bowled for TeamB - "+v);
System.out.println("Team B Scores : \n");
for (int i=0;i<outB ;i++ ) {
System.out.println(teamB[i][0]+" - "+teamB[i][1]);

}
System.out.println("\nTotal Score of TeamB - "+totalScoreB);
System.out.println("\nDeductions of Balls Due to Rain = "+deduct);
System.out.println("Final Score Of Team A after Deduction : " + totalScoreA);
System.out.println("Final Score Of Team B after Deduction : " + totalScoreB);

if (totalScoreA<totalScoreB) {
System.out.println("\nTeam B Wins ");

}
else{
System.out.println("\nTeam A Wins");
}}}}}

Question no 02: [15 Marks]

Mr. Patrick is fond of reading books he is looking for a computerized way to keep record of his
book collection, you have been given the responsibility to meet up his following requirements.
(Use appropriate data structure to accomplish your task), develop following methods:
1. Add(): adds a new book to the list ( A book contains name of the book, author name)
(4)
NOTE: every new book will have access to its neighboring books (previous and next)
2. Remove():in case any book is removed from the pile update your list (4)
3. countBooks(): displays the total number of books (3)
4. search(): returns true if the given book is present in the list else returns false (3)
5. display(): shows the book collection (1) Output:

Welcome Mr. Patrick please select anyone of the following


1. option
2. Add a book Remove a book
3. Show total number of books Search a book
4. Show all books
5.
Please input No of your desired operation: 1 Please input following
information.
Name of the book: warrior of the light
Author of the book: Paulo Coelho
Successfully added

Do you wish to continue?


No

Note: You are not allowed to use any built-in Data Structure classes to implement above scenario.

Answer 02:
 Class Book

package Mahrukh_46889;
import java.util.Scanner;

class Book {
private String name;
private String author;
private Book next, prev;

public Book(String name, String author) {


this.name = name;
this.author = author;
this.next = null;
this.prev = null;
}

public void setBookName(String name) {


this.name = name;
}

public String getBookName() {


return name;
}

public void setAuthorName(String author) {


this.author = author;
}

public String getAuthorName() {


return author;
}

public void setNext(Book next) {


this.next = next;
}

public Book getNext() {


return next;
}

public void setPrev(Book prev) {


this.prev = prev;
}

public Book getPrev() {


return prev;
}
}
 Class BookCollection

package Mahrukh_46889;
import java.util.Scanner;
public class BookCollection {

static Book head;


static int count;

public static void addBook(String name, String author) {

Book newBook = new Book(name, author);


if(head == null) {

head = newBook;
}
else {
Book curBook = head;
while(curBook.getNext() != null) {
curBook = curBook.getNext();
}
curBook.setNext(newBook);
newBook.setPrev(curBook);
}
System.out.println("Successfully added");
count++;
}

public static void removeBook(String name, String author) {

if(searchBook(name, author)) {

if(head.getBookName().equals(name) && head.getAuthorName().equals(author)) {


if(head.getNext() != null) {
head.getNext().setPrev(null);
head = head.getNext();
}
else {
head = null;
}
}
else {
Book current;
current = head.getNext();
while(current != null) {
if(current.getBookName().equals(name) && current.getAuthorName().equals(author))
break;
current = current.getNext();
}
current.getNext().setPrev(current.getPrev());
current.getPrev().setNext(current.getNext());
}
System.out.println("Successfully deleted");
count--;
}
else {

System.out.println("Book not found in the list");


}
}

public static boolean searchBook(String name, String author) {

if(head == null) {
return false;
}
else {
Book current = head;
while(current != null) {
if(current.getBookName().equals(name) && current.getAuthorName().equals(author)) {
return true;
}
current = current.getNext();
}
return false;
}
}

public static void countBooks() {

System.out.println("Total number of books in the collection = " + count);


}

public static void display() {

if(head == null) {
System.out.println("No books in the collection");
return;
}
Book current = head;
System.out.println("Books in the Collection:\n");
while(current != null) {
System.out.println(current.getBookName() + " by " + current.getAuthorName());
current = current.getNext();
}
}

public static void main(String[] args) {

head = null;
count = 0;
Scanner sc = new Scanner(System.in);
String cont, name, author;
int choice;
System.out.println("Welcome Mr.Patrick! Please select anyone of the following option.");
do {
// MENU
System.out.println("1. Add a book");
System.out.println("2. Remove a book");
System.out.println("3. Show total number of books");
System.out.println("4. Search a book");
System.out.println("5. Show all books");
System.out.print("Please input number of your desired operation: ");
choice = sc.nextInt();
sc.nextLine();
switch(choice) {
case 1:
System.out.println("Please input following information");
System.out.print("Name of the book: ");
name = sc.nextLine();
System.out.print("Author of the book: ");
author = sc.nextLine();
addBook(name, author);
break;
case 2:
System.out.println("Please input following information");
System.out.print("Name of the book: ");
name = sc.nextLine();
System.out.print("Author of the book: ");
author = sc.nextLine();
removeBook(name, author);
break;
case 3:
countBooks();
break;
case 4:
System.out.println("Please input following information");
System.out.print("Name of the book: ");
name = sc.nextLine();
System.out.print("Author of the book: ");
author = sc.nextLine();
boolean found = searchBook(name, author);
if(found)
System.out.println("Book found in the collection");
else
System.out.println("Book not found in the collection");
break;
case 5:
display();
break;
default:
System.out.println("Invalid option!");
}
System.out.println("\nDo you wish to continue (Yes/No)?");
cont = sc.nextLine();
}while(!cont.equals("No") && !cont.equals("no") && !cont.equals("NO"));
sc.close();
}

}
Question no 03: [10 Marks]

Consider flight network having places of departure and destination. Flight network represent
place name as a node and flight trajectories between place names are the edges. Consider
Pakistan cities as a node and show the source and destination paths, show all the paths
separately with their labels and include their code as well.
Analyze this scenario that tree or graph should implement here, justify and also implement this
with appropriate data structure.

Example:
Network represents that there are three cities named Karachi, Islamabad and Lahore. Flight
schedule from Karachi to Islamabad, Islamabad to Lahore and Lahore to Karachi. Places save
as class having departure time and day also.

Note: You are not allowed to use any built-in Data Structure classes to implement above scenario.

Answer 03:
Datastructure for classes implementation
1-Create a HashMap of given pair of tickets.
HashMap be 'dataset'. Every entry of 'dataset' is of the form
"from->to" like "Karachi" -> "Lahore"

2-Find the starting point of itinerary.


a-Create a reverse HashMap. Let the reverse be 'reverseMap'
Entries of 'reverseMap' are in "to->form".
Following is 'reverseMap' for above example.
"Karachi"-> "Islamabaad"
"Islamabaad"-> "Lahore"
"Lahore"-> "Karachi

b-Traverse 'dataset'. For every key of dataset, check if it


is there in 'reverseMap'. If a key is not present, then we
found the starting point. In the above example, "Karachi" is
starting point.

3) Start from above found starting point and traverse the 'dataset'
to print itinerary.

//CODE
package Mahrukh_46889;
import java.util.HashMap;
import java.util.Map;
public class Flight_Network
{
public static void main(String[] args)
{
Map<String, String> dataSet = new HashMap<String, String>();
dataSet.put("Karachi", "Lahore");
printResult(dataSet);
}
private static void printResult(Map<String, String> dataSet)
{
Map<String, String> reverseMap = new HashMap<String, String>();
for (Map.Entry<String,String> entry: dataSet.entrySet())
reverseMap.put(entry.getValue(), entry.getKey());
String isl = "Islamabad";
String start = null;
for (Map.Entry<String,String> entry: dataSet.entrySet())
{
if (!reverseMap.containsKey(entry.getKey()))
{
start = entry.getKey();
break;
}
}
if (start == null)
{
System.out.println("Invalid Input");
return;
}
String to = dataSet.get(start);
while (to != null)
{
System.out.print(start + "->" + to + "->" + isl + ".");
start = to;
to = dataSet.get(to);
}}}

You might also like