Wednesday, 27 September 2023

Java Codeathon Questions with Solutions

Codeathon – 01
[Question]
Algorithms/Data Structures - [Problem Solving] 
There is a Specific Need for Changes in a List of Usernames. In a given List of Usernames - For Each Username - If the Username can be Modified and Moved Ahead in a Dictionary. The Allowed Modification is that Alphabets can change Positions in the Given Username.
 
Example
usernames[] = {"Aab", "Cat"}
 
"Aab" cannot be changed to another unique string matching the above rule - Hence, It can Never Find a Place Ahead in the Dictionary. Hence, Output will be "NO". "Cat" can be Changed to "Act", "Atc", "Tca", "Tac", "Cta" and Definitely "Act" will Find a Place Before "Cat" in the Dictionary. Hence, Output will be "YES".
 
[FunctionDescription]
Complete the function possible Changes in the Editor Below.
 
Possible Changes has the following parameters:
String usernames[n]: An Array of User Names.
 
Returns String[n]: An Array with "YES" or "NO" Based on Feasibility
(Actual Question Says String Array, But Signature is List of Strings)
 
Constraints
• [No Special Constraints Exist, But Cannot Recall Exactly]
 
[Sample Input]
The First Line Contains an Integer, n, the Number of Elements in Usernames.", 
"Each Line of the n Subsequent Lines (where 0 <i< n) contains a String usernames[i]."  
 
[Sample Case 0 – Sample Input For Custom Testing]
8
Aab
Cat
Pqrs
Buba
Bapg
Sungi
Lapg
Acba
 
[Sample Output] (Each Should Be on a Separate Line)
NO YES NO YES YES YES YES YES
 
[Explanation of Solution]
The program takes a list of usernames as input. It checks if each username can be modified by rearranging its letters to be in ascending order. If the modification is possible, it labels the username as "YES"; otherwise, it labels it as "NO." The program then prints these "YES" or "NO" labels for each username. The goal is to determine if a username can be changed to come before itself in dictionary order.
 
Github Repo for Code:   https://tinyurl.com/4wervn4f
 
[Solution (Java Code)]
/*
 * Core Java Problem Solving - Codeathon.
 * A.R. Kishore Kumar ~ (c) 2023 ~ -- ~ Tirupati, Andhra Pradesh, India ~
 *
 */
package codeathon;
import java.util.Scanner;
public class Codeathon01_Kishore
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();                  // To store number of user names
        String usernames[] = new String[n];    // To store an array of user names
        String results[];                     // To store YES / NO  values
 
        for (int i = 0; i < n; i++)                    // Storing n number of user names
            usernames[i] = sc.next();
 
        //calling method possibleChanges with usernames
        results = UsernamesDictionaryLogic.possibleChanges(usernames);
 
        //displaying the results of possible changes YES / NO for user names
        for (int i = 0; i < n; i++)
            System.out.println(results[i] + "\t");
    }
}
 
class UsernamesDictionaryLogic
{
    // method to know possible changes in each user name
    public static String[] possibleChanges(String usernames[])
    {
        int n = usernames.length;
        String results[] = new String[n];
 
        int check;
        // starting from first user name, checking each user name for possible changes
        for(int i=0;i<n;i++)
        {
            check=0;
            String dummy = usernames[i].toLowerCase();
            // checking for possible change in the user name by comparing the characters
            for(int j=1; j<dummy.length(); j++)
            {
                if ((dummy.charAt(j-1))> (dummy.charAt(j)))
                {
                    check++;
                }
            }
            if (check > 0)
                results[i]="YES";
            else
                results[i]="NO";
        }
        return results;                                             
    }
}
 
Codeathon– 02
[Question]
Algorithms/Data Structures - [Problem Solving] 
An Institutional Broker wants to Review their Book of Customers to see which are Most Active. Given a List of Trades By "Customer Name, Determine which Customers Account for At Least 5% of the Total Number of Trades. Order the List Alphabetically Ascending By Name."
 
Example
n = 23
“Customers = {“Big Corp”,  “Big Corp”, ”Acme”, “Big Corp”, “Zork” ,”Zork” ,”Abe”, “Big Corp”, “Acme”, “Big Corp” ,”Big Corp”, “Zork”, “Big Corp”, “Zork”, “Zork”, “Big Corp”,”Acme”,”Big Corp”, “Acme”, “Big Corp”, “Acme”, “Little Corp”, “Nadir Corp”}
 
"Big Corp had 10 Trades out of 23, which is 43.48% of the Total Trades."
"Both Acme and Zork had 5 trades, which is 21.74% of the Total Trades."
"The Little Corp, Nadir Corp and Abe had 1 Trade Each, which is 4.35%..."
 
"So the Answer is [""Acme"", "" Big Corp  ,""Zork""] (In Alphabetical Order) Because only These Three Companies Placed at least 5% of the Trades.
 
Function Description
Complete the function mostActive in the Editor Below.
 
mostActive has the following parameter:
String customers[n]: An Array Customers Names
(Actual Questions Says String Array, But Signatures is List of Strings)
 
Returns String[] : An Alphabetically Ascending Array
 
Constraints
• 1 < n < 10^5
• 1 < Length of customers[] < 20
• The First Character of customers[i] is a Capital English letter.
• All Characters of customers[i] except for the First One are Lowercase.
• Guaranteed that At least One Customer makes atleast 5% of Trades.
 
[Sample Input]
"The First Line contains an integer, n, The Number of Elements in customers."      
"Each Line iof the n Subsequent Lines (where 0 s i< n) contains a string, customers[i]." 
 
Sample Case 0 Input For Custom Testing
20       
Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Beta   
 
Function mostActive
customers[] size n =  20      
customers[] = [As Provided Above]    
 
[Sample Output]
Alpha      
Beta
Omega  
Explanation of Output
“Alpha made 10 Trades out of 20 (50% of the Total), Omega made 9 Trades (45% of the Total). and Beta made 1 Trade (5% of the Total).All of them have met the 5% Threshold, so all the Strings are Returned in an Alphabetically Ordered Array.”
 
[Explanation of Solution]
The program first counts the number of trades made by each customer and stores this information in a map. Then, it calculates the threshold for the 5% requirement based on the total number of trades. Next, it identifies customers whose trade count surpasses this threshold, adding them to a list of active customers. Finally, it sorts this list alphabetically and returns it as the result.
 
Github Repo for Code: https://tinyurl.com/ywr7fknv
 
[Solution (Java Code)]
/*
 * Core Java Problem Solving - Codeathon.
 * A.R. Kishore Kumar ~ (c) 2023 ~ -- ~ Tirupati, Andhra Pradesh, India ~
 *
 */
package codeathon;
import java.util.Scanner;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
public class Codeathon02_Kishore
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();   // Number of Elements in customers
        List<String> customers = new ArrayList<>();
        for (int i = 0; i < n; i++) {    // Number of times trade by Customers
            customers.add( sc.next() );
        }
        List<String> result = ActiveTraders.mostActive(customers);
 
        // Print the result in alphabetical order
        Collections.sort(result);
        for (String customer : result) {
            System.out.println(customer);
        }
    }
}
class ActiveTraders
{
    public static List<String> mostActive(List<String> customers)
    {
        int n = customers.size();
        Map<String, Integer> customerCounts = new HashMap<>();
 
        // Count the occurrences of each customer
        for (int i = 0; i < customers.size(); i++)
        {
            String customer = customers.get(i);
 
            if (customerCounts.containsKey(customer)) {
                int count = customerCounts.get(customer);
                customerCounts.put(customer, count + 1);
            } else {
                customerCounts.put(customer, 1);
            }
        }
 
        // Calculate the threshold for 5% of total trades
        int threshold = (int) Math.ceil(n * 0.05);
        // Find customers with trades >= threshold
        List<String> activeCustomers = new ArrayList<>();
        for (String customer : customerCounts.keySet()) {
            if (customerCounts.get(customer) >= threshold) {
                activeCustomers.add(customer);
            }
        }
        return activeCustomers;
    }
}
 
Codeathon– 03
[Question]
Monkeys in the Garden [www.techgig.com]
In a garden, trees are arranged in a circular fashion with an equal distance between two adjacent trees. The height of trees may vary. Two monkeys live in that garden and they were very close to each other. One day they quarreled due to some misunderstanding. None of them were ready to leave the garden. But each one of them wants that if the other wants to meet him, it should take maximum possible time to reach him, given that they both live in the same garden.
The conditions are that a monkey cannot directly jump from one tree to another. There are 30 trees in the garden. If the height of a tree is H, a monkey can live at any height from 0 to H. Lets say he lives at the height of K then it would take him K unit of time to climb down to the ground level. Similarly, if a monkey wants to climb up to K height it would again take K unit of time. The time to travel between two adjacent trees is 1 unit. A monkey can only travel in a circular fashion in the garden because there is a pond at the center of the garden.
So the question is where should two monkeys live such that the traveling time between them is maximum while choosing the shortest path between them in any direction clockwise or anti-clockwise. You have to answer only the maximum traveling time.
 
[Sample Input]
The First Line consists of Total Number of Trees (N). Each of the Following N Lines contains the Height of Trees in a Clockwise Fashion.
Constraints
1 <= Total Trees <= 30
1 <= Height Of Trees(H) <= 10000
 
[Sample Output]
You must Print an Integer which will be the Maximum Possible Travel Time.
 
[Explanation of Solution]
The program takes the heights of the trees as input and calculates the maximum possible travel time between the monkeys. It does so by iterating through all possible pairs of trees, determining the shortest path between them in both clockwise and anti-clockwise directions, and calculating the total travel time. It keeps track of the maximum travel time encountered during this process.
 
Github Repo for Code: https://tinyurl.com/23wf74v3
 
[Solution (Java Code)]
/*
 * Core Java Problem Solving - Codeathon.
 * A.R. Kishore Kumar ~ (c) 2023 ~ -- ~ Tirupati, Andhra Pradesh, India ~
 *
 */
package codeathon;
import java.util.Scanner;
public class Codeathon03_Kishore
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();          // Total Number of Trees
        int[] heights = new int[n];    // Heights of the Trees
        for (int i = 0; i < n; i++)
        {
            heights[i] = sc.nextInt();
        }
        int maxTravelTime = 0;
        int clockwiseLength, anticlockwiseLength, shorterLength, totalLength;
        for(int i=0;i<n;i++)
        {
            for(int j=i+1;j<n;j++)
            {
                clockwiseLength = (n - j + i) % n;         // clockwise length
                anticlockwiseLength = (j - i + n) % n;     // anti-clockwise  length
                shorterLength = Math.min(clockwiseLength, anticlockwiseLength);
                totalLength = shorterLength + heights[i] + heights[j];  // maximum path length
                if (totalLength > maxTravelTime)
                {
                    maxTravelTime = totalLength;      // maximum travel time
                }
            }
        }
        System.out.println(maxTravelTime);
    }
}
 
Codeathon – 04
[Question]
Java Advanced - Lambda Expressions [www.techgig.com]
Write the Following Methods that Return a Lambda Expression Performing a Specified Action: Perform Operationis Odd(): The Lambda Expression must return  if a Number is Odd or  If it is Even. Perform Operationis Prime(): The lambda expression must return  if a number is prime or  if it is composite. Perform Operationis Palindrome(): The Lambda Expression must return  if a number is a Palindrome or if it is not.
 
[Sample Input]
Input is as Show in the Format Below (Deduce Unknowns!)
Input
3
1 3
2 7
3 7777
 
Constraints
NA
 
[Sample Output]
Output is as Show in the Format Below (Deduce Unknowns!)
 
Output
ODD
PRIME
PALINDROME
 
[Explanation of Solution]
The LambdaOperation interface serves as a template for these lambda expressions, each designed to evaluate a different condition. The program takes input pairs of operation types and numbers, processes them according to the lambda expressions, and stores the results in an array. A switch-case structure directs the program to the appropriate lambda expression based on the operation type, and the corresponding result is stored in the output array. Finally, the program prints the results for each input operation type.
 
Github Repo for Code: https://tinyurl.com/nyzv7237
[Solution (Java Code)]
/*
 * Core Java Problem Solving - Codeathon.
 * A.R. Kishore Kumar ~ (c) 2023 ~ -- ~ Tirupati, Andhra Pradesh, India ~
 *
 */
package codeathon;
import java.util.Scanner;
interface LambdaOperation
{
    boolean perform(int x);
}
 
public class Codeathon04_Kishore
{
    public static void main(String args[])
    {
        // Check given number is even or odd
        LambdaOperation isOdd = n -> {
            boolean check = false;
            if (n % 2 != 0)
                check = true;
            return check;
        };
 
        //check given number is prime or composite
        LambdaOperation isPrime = n -> {
            boolean check = true;
            for (int i = 2; i < n - 1; i++) {
                if (n % i == 0) {
                    check = false;
                    break;
                }
            }
            return check;
        };
 
        //check given number is palindrome or not
        LambdaOperation isPalindrome = n -> {
            boolean check = false;
            int p, r=0, k = n;
            while ( n != 0)
            {
                p = n%10;
                r = r*10 + p;
                n = n/10;
            }
            if( k == r)
                return true;
            else
                return false;
        };
 
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
 
        String output[] = new String[3];
 
        for (int i = 0; i < num; i++)
        {
            int ch = scanner.nextInt();
            int no = scanner.nextInt();
            switch (ch)
            {
                case 1:
                    if (isOdd.perform(no))
                        output[i] = "ODD";
                    else
                        output[i] = "EVEN";
                    break;
 
                case 2:
                    if (isPrime.perform(no))
                        output[i] = "PRIME";
                    else
                        output[i] = "COMPOSITE";
                    break;
                case 3:
                    if (isPalindrome.perform(no))
                        output[i] = "PALINDROME";
                    else
                        output[i] = "NOT A PALINDROME";
            }
        }
        for(int i=0;i<3;i++)
            System.out.println(output[i]);
    }
}
 
Codeathon – 05
[Question]
Java Inheritance / Simple oops [www.techgig.com]
a)  Create Two Classes:
BaseClass
The Rectangle class should have two data fields-width and height of Int types. The class should have display() method, to print the width and height of the rectangle separated by space.
DerivedClass
The RectangleArea class is Derived from Rectangle class, I.e., It is the Sub-Class of Rectangle class. The class should have read_Input() method, to Read the Values of width and height of the Rectangle. The RectangleAreadass should also Overload the display() Method to Print the Area (width"height) of the Rectangle.
 
[Sample Input]
The First and Only Line of Input contains two space separated Integers denoting the width and height of the Rectangle.
Constraints
1 <= width, height <= 10^3

[Sample Output]
The Output Should Consist of Exactly Two Lines. In the First e, Print the Width and Height of the Rectangle Separated by Space.
In the Second Line, Print the Area of the Rectangle.
 
[Explanation of Solution]
This program demonstrates the concept of inheritance in object-oriented programming, where a subclass (RectangleArea) inherits attributes and methods from its superclass (BaseClass) and extends them to perform additional tasks, such as calculating and displaying the area of a rectangle.
 
Github Repo for Code:  https://tinyurl.com/3avkxnz2
 
[Solution (Java Code)]
/*
 * Core Java Problem Solving - Codeathon.
 * A.R. Kishore Kumar ~ (c) 2023 ~ -- ~ Tirupati, Andhra Pradesh, India ~
 *
 */
package codeathon;
import java.util.Scanner;
 
//Rectangle class (Super Class) with Setter/Getter and display() methods
class Rectangle
{
    private int width;
    private int height;
    public void display()
    {
        System.out.println(width + " " + height);
    }
    public int getWidth()
    {
        return width;
    }
    public void setWidth(int width)
    {
        this.width=width;
    }
    public int getHeight()
    {
        return height;
    }
    public void setHeight(int height)
    {
        this.height=height;
    }
}
 
//RectangleArea Sub Class with overrided display() method
class RectangleArea extends Rectangle
{
    public void read_input()
    {
        Scanner sc = new Scanner (System.in);
        setWidth(sc.nextInt());
        setHeight(sc.nextInt());
    }
    public void display()
    {
        super.display();
        System.out.println(getWidth()*getHeight());
    }
}
public class Codeathon05A_Kishore
{
    public static void main(String args[] )
    {
        RectangleArea rectangleArea = new RectangleArea();
        rectangleArea.read_input();
        rectangleArea.display();
    }
}
 
[Question]
b) Write a Java Program that Swap the Values of 02 Variables without Using a 03rd Variable. The Swapped Value Should be In Such a Way that the 1st Variable will hold only 10% (rounded down) of the 2nd value and the 02nd Variable will hold only the 20% (rounded down) of the 1st value.
 
[Sample Input]
 var1=250, var2=400
 
[Sample Output]
var1=40, var2=50
 
[Explanation of Solution]
This Java program efficiently swaps the values of two variables, var1 and var2, without utilizing a third variable. It guarantees that, after swapping, var1 holds 10% (rounded down) of the original var2 value, and var2 contains 20% (rounded down) of the initial var1 value.
 
Github Repo for Code: https://tinyurl.com/mrczn6hh
 
[Solution (Java Code)]
/*
 * Core Java Problem Solving - Codeathon.
 * A.R. Kishore Kumar ~ (c) 2023 ~ -- ~ Tirupati, Andhra Pradesh, India ~
 *
 */
 
package codeathon;
 
import java.util.Scanner;
public class Codeathon05B_Kishore
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("var1 = ");
        int var1 = sc.nextInt();
        System.out.print("var2 = ");
        int var2 = sc.nextInt();
        // logic to swap two numbers without using thrid variable in
        // a single line
        var1 = (var1+var2) - (var2 = var1);
        var1 = (int) Math.round (var1* 0.10 )  ;
        var2 = (int) Math.round (var2* 0.20 )  ;
        System.out.println("var1=" + var1 + ", var2=" + var2);
    }
}
 
Codeathon – 06
[Question]
CRYPTIC FRUIT GAME
you are given 2 list of values. The first list contains a unique identifier that needs to be matches the second list that has a set of fruits. Each unique identifier has exactly one letter of the English alphabet. The position of that letter in the English alphabet correlates to the length of the fruit give in the second list. The output of the program will be of the format Map<String, List<String>that actually contains the key as the unique code and the list of fruits that correlates to that unique key.
 
[Sample Input]
First line contains number of identifiers in both the lists and next lines contain input as follows:
7
List 1
0E1234
0823F
1200J
600K
456700I
A001
8432X
 
List 2
Apple
Orange
Banana
Grape
Watermelon
Pomegranate
Jackfruit
 
[Sample Output]
OE1234: Apple, Grape
0823F: Orange, Banana
1200J: Watermelon
600K: Pomegranate
456700I: Jackfruit
8432X: [No Fruit]
A001: [No Fruit]
 
Explanation of the Output
From the Sample Input, If we take 0E1234, E is the letter of the english alphabet that is on the 5th position in the English alphabet. Now, the fruits that are of length 5 in the second list are > 'Apple', 'Orange'. Hence the output will have the Key as 0E1234 and the corresponding value will be 'Apple', 'Orange. You have to store the output as Map<String, List<String>> and also print the output in the format shown above. If there are no fruits matching, for example in A001, the position of A in english alphabet is 1 and there are no fruits with length 1 in the second list, so you have to print [No Fruit] against it. Please adhere exactly to the output format as given above.
 
Areas: Java Collections, Core Java, Logic, Problem Solving, String Handling
 
[Explanation of Solution]
The program first reads the input, storing the values from both lists into list1 and list2, respectively. Then, it iterates through list1 and, for each unique identifier, finds the matching fruits length from list2 based on the alphabets respective value (A -1, B-2, C-3,….,Z-26 respectively). The matching fruits are stored in a map called resultMap, with the unique identifiers as keys and the matching fruits as values. The program then prints the results.
 
Github Repo for Code: https://tinyurl.com/5yhtwf8h
 
[Solution (Java Code)]
/*
 * Core Java Problem Solving - Codeathon.
 * A.R. Kishore Kumar ~ (c) 2023 ~ -- ~ Tirupati, Andhra Pradesh, India ~
 *
 */
package codeathon;
import java.util.*;
public class Codeathon06_Kishore {
    public static void main(String[] args) {
        List<String> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
 
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();   // Number of Elements in each List
 
        System.out.println("List 1");
        for (int i = 0; i < n; i++) {    // Storing first list of values
            list1.add(sc.next());
        }
 
        System.out.println("List 2");
        for (int i = 0; i < n; i++) {    // Storing second list of values
            list2.add(sc.next());
        }
 
        // storing matching fruits to resultMap and displaying final output
        Map<String, List<String>> resultMap = new HashMap<>();
        for (String text : list1) {
            List<String> matchingFruits = Matching.findMatchingFruits(text, list2);
            resultMap.put(text, matchingFruits);
        }
        for (String list1String : list1) {
            List<String> matchingFruits = resultMap.get(list1String);
 
            System.out.print(list1String + ": ");
            if (matchingFruits.isEmpty()) {
                System.out.println("[No Fruit]");
            } else {
                System.out.println(String.join(", ", matchingFruits));
            }
        }
    }
}
class Matching
{
    // method for finding matched fruits
    public static List<String> findMatchingFruits(String numberString, List<String> list2) {
        char alphabet = findAlphabetCharacter(numberString);
        List<String> matchingFruits = new ArrayList<>();
        for (String fruit : list2)
        {
            if (fruit.length() == alphabet - 'A' + 1)
            {
                matchingFruits.add(fruit);
            }
        }
        return matchingFruits;
    }
 
    // Method to know no of letters Based on Alphabet
    private static char findAlphabetCharacter(String text) {
        for (char c : text.toCharArray())
        {
            if (Character.isLetter(c)) {
                return Character.toUpperCase(c);
            }
        }
        return ' ';
    }
}
 
Codeathon – 07
[Question]
WINDOWS DIRECTORY SEARCH
Your program will accept a valid windows directory as theinput. If the directory is not valid, you have to show a message saying that 'Directory Not Found on the Filesystem Else, you have to find out all txt files and .exe files in your directory and then add it to a java collection in such a way that it stores it in a sorted way (sorted by the directory name) where the key is the fully qualified directory name and the values must be the list of all .txt and .exe files. You have to do the same for all child directories that are found in the parent directory, until the time no directories remain to traverse.
 
Filesystem (Sample)
c:\files
      file1.txt
      file2.exe
      file3.bat
  \filex
           \filez
\filey
       file 4.txt
       file5.exe
       \filef
file6.txt
 file7.exe
 \fileg
 
[Sample Input]
 c:\files
 
[Sample Output]
c:\files              file1.txt, file2.exe
c:\files\filex                              
c:\files\filexz\filez                      
c:\files\filey       file4.txt, file5.exe                       
c:\files\filey\filef\         file6.txt, file7.exe
c:files\filey\filef\fileg
 
Explanation of the Output
You have to make sure that you traverse every sub-directory that is inside the input directory and list the .txt and .exe in the format as shown above. You have to make sure no sub-directory should be left out and that all levels of child sub-directories are traversed. If no matching file is found, then a blank output should be printed as shown above. Please strictly stick to the output format as given above.
 
[Explanation of Solution]
This program takes a valid Windows directory as input and checks if it exists; if not, it displays a "Directory Not Found" message. If the directory is valid, it searches for .txt and .exe files within it and its subdirectories. The program stores the results in a sorted Java collection called fileMap, where each entry has a fully qualified directory name as the key and a list of matching .txt and .exe files as the values. Finally, the program prints the directory hierarchy along with the names of .txt and .exe files.
 
Areas: Java Collections, Core Java, Logic, Data Structures, Algorithms
 
Github Repo for Code:  https://tinyurl.com/ht7dzc6e
 
[Solution (Java Code)]
/*
 * Core Java Problem Solving - Codeathon.
 * A.R. Kishore Kumar ~ (c) 2023 ~ -- ~ Tirupati, Andhra Pradesh, India ~
 *
 */
package codeathon;
import java.io.File;
import java.util.*;
 
public class Codeathon07_Kishore
{
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        String directoryPath = scanner.nextLine();
        File directory = new File(directoryPath);
        if (!directory.exists() || !directory.isDirectory())
        {
            System.out.println("Directory Not Found on the Filesystem");
            return;
        }
        Map<String, List<String>> fileMap = WinDirectorySearch.listFiles(directory);
 
        DisplayFileDetails.printFileMap(fileMap);
    }
}
class WinDirectorySearch
{
    // Method to store fully qualified directory name as the key
    // and a list of .txt and .exe files as the values
    public static Map<String, List<String>> listFiles(File directory)
    {
        Map<String, List<String>> fileMap = new TreeMap<>();
        File[] files = directory.listFiles();
        if (files != null)
        {
            List<String> txtAndExeFiles = new ArrayList<>();
            for (File file : files)
            {
                if (file.isDirectory())
                {
                    Map<String, List<String>> childFileMap = listFiles(file);
                    if (!childFileMap.isEmpty())
                    {
                        fileMap.putAll(childFileMap);
                    }
                }
                else
                {
                    String fileName = file.getName().toLowerCase();
                    if (fileName.endsWith(".txt") || fileName.endsWith(".exe"))
                    {
                        txtAndExeFiles.add(file.getName());
                    }
                }
            }
            if (!txtAndExeFiles.isEmpty())
            {
                fileMap.put(directory.getAbsolutePath(), txtAndExeFiles);
            }
            else
            {
                fileMap.put(directory.getAbsolutePath(), new ArrayList<>());
            }
        }
        return fileMap;
    }
}
 
class DisplayFileDetails
{
    // Method that displays the directory hierarchy with file names
    public static void printFileMap(Map<String, List<String>> fileMap)
    {
        for (String dirName : fileMap.keySet())
        {
            List<String> files = fileMap.get(dirName);
            System.out.print(dirName);
            if (!files.isEmpty())
            {
                System.out.print("\t" + String.join(", ", files));
            }
            System.out.println();
        }
    }
}
 
Codeathon – 08
[Question]
ROBOTIC CRICKET MATCH
you should write a program that simulate an automatic cricket match between India and Sri Lanka. The focus is the usage of Java Thread Constructs. Each Innings happens within its thread. You decide the 11 members of each team and provide two lists to the program. The first team is represented as team 1 and second team as team 2. You have to generate a random number for toss and if the number is between 0 and 1, team 1 bats first- else, if the number is between 1 and 2, then team 2 bats first. The batting happens by starting a thread. Each ball bowled is via a random number generator (that generates number rounded off, between 0 and 7). If the number is 0, batsman is out. If the number is 1, run is 1, number is 2, run is 2, number is 3, run is 3, number is 4, run is 4, number is 5, run is 5, number is 6, run is 6. If the number is exactly 7, then it is an extra 1 run and if it is 0, batsman is out). You have to do this until 10 batsmen get out in 1 team. The final score sheet will show as follows. Then you have to start another thread and do the same as above. The match ends either when the second team batsmen are out, with scores lesser than team 1 (team 1 wins), scores are tied (match is tied) and as soon score is greater than team 1 (team 2 wins). Each over is for 6 balls, if extra happens (number 7), 1 run is awarded and 1 extra ball is bowled. Extra run and Extra Ball is not part of batsman's account. Total Overs are 10. (T101 Match)
 
(No Need to Take Care of Changing Batsman Strike If Score is 1, 3 or 5. No Need to Record Bowling Figures of the Bowler in the Solution. No Need to Take Care Separately of Wide, No Balls, Byes, Leg Byes. There are No Free-Hits!).
 
[Sample Input]
(No Input is Required)
 
[Sample Output]
Toss Won By SL (Team 0)
Team 0 (SL) is Batting First
India-Batting Scoresheet
Rohit Sharma 1,4,3,6,1,0=15 (6)
Shubman Gill 0=0 (1)
Virat Kohli 4,6,1,0=11 (4)
KL Rahul 3,1,4,0=8 (4)
Ishan Kishan 6,6,6,4,0 = 22 (5)
Hardik Pandya 0 = 0 (1)
Ravindra Jadeja 6,0 = 6 (2)
Washington Sundar 1,3,0 = 4 (3)
Kuldeep Yadav 1,2,3,4,0=10 (5)
Mohammed Siraj 0 = 0 (1)
Jasprit Bumrah Did Not Bat
 
Extras 1, 1, 1, 1, 1 = 5
 
Total Score 81 in 5.2 overs
Sri Lanka - Batting Scoresheet
Pathum Nissanka 0=0(1)
Kusal Perera 0=0 (1)
Kusal Mendis 1,0=1(2)
Sadeera Samarawickrama 1,1,0=2 (3)
Charith Asalanka 2,0=2(2)
Dhananjaya de Silva 4,4,0 = 8 (3)
Dasun Shanaka (c) 1,4,6,0=11 (4)
DunithWellalage 6,6,0=12 (3)
Dushan Hemantha 0=0 (1)
Pramod Madushan 1,0=1(2)
Matheesha Pathirana Did Not Bat
Extras 1, 1=2
Total Score 39 in 3.4 overs
Match Result: Team 0 (India) Won By 42 Runs
Today's Date: 17/09/2023
 
Areas : Core Java, Logic, Longer Problem Solving, Understanding Requirements, Java Multi- Threading, Java Async Execution, Java Collections.
 
[Explanation of Solution]
This Java program creates a virtual cricket match between India and Sri Lanka, with a focus on using multi-threading. It randomly selects which team bats first and then simulates their innings using separate threads. Each ball bowled is determined by a random number, with 0 indicating the batsman is out and 1 to 6 representing the runs scored. Extras (7) are also taken into account. The match includes two innings, and the program maintains a detailed scorecard for both teams, tracking player names, runs, and extras.
 
To ensure data integrity, the program employs multi-threading principles and uses locks when shared data is modified. After both innings are completed, the program calculates the total score for each team and determines the match result based on these scores. The final output displays comprehensive scorecards and declares the match result.
 
Github Repo for Code:  https://tinyurl.com/45tmhmmw
 
[Solution (Java Code)]
/*
 * Core Java Problem Solving - Codeathon.
 * A.R. Kishore Kumar ~ (c) 2023 ~ -- ~ Tirupati, Andhra Pradesh, India ~
 *
 */
package codeathon;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
class Player {
    private String name;
    private int[] runsScored;
    private int ballsFaced;
    private int extras;
 
    public Player(String name) {
        this.name = name;
        this.runsScored = new int[60]; // Max 10 overs, 6 balls per over
        this.ballsFaced = 0;
        this.extras = 0;
    }
 
    public String getName() {
        return name;
    }
 
    public int getBallsFaced() {
        return ballsFaced;
    }
 
    public int getExtras() {
        return extras;
    }
 
    public void playInnings() {
        Random random = new Random();
        for (int balls = 0; balls < 60; balls++) { // Simulate 10 overs (60 balls)
            int ballResult = random.nextInt(8); // Simulate a ball (0-7 represents outcomes)
            if (ballResult == 7) {
                extras++; // Extra run
            } else if (ballResult == 0) {
                // Player is out
                break;
            } else {
                runsScored[ballsFaced] = ballResult;
                ballsFaced++;
            }
        }
    }
 
    public int getTotalRunsScored() {
        int totalRuns = 0;
        for (int i = 0; i < ballsFaced; i++) {
            totalRuns += runsScored[i];
        }
        return totalRuns;
    }
 
    public int[] getRunsScored() {
        return runsScored;
    }
}
 
class Team implements Runnable {
    private String name;
    private Player[] players;
    private int totalScore;
 
    private static int batting = 1;
 
    public Team(String name, String[] playerNames) {
        this.name = name;
        this.totalScore = 0;
        this.players = new Player[11];
        for (int i = 0; i < 11; i++) {
            this.players[i] = new Player(playerNames[i]);
        }
    }
 
    public int getTotalScore() {
        return totalScore;
    }
 
    public void run() {
 
        System.out.println("Team " + name + " is Batting " + batting++);
        for (Player player : players) {
            player.playInnings();
            totalScore += player.getTotalRunsScored();
        }
    }
    public void displayBattingScorecard() {
        System.out.println(name + "-Batting Scoresheet");
        for (Player player : players) {
            System.out.print(player.getName() + " ");
            int[] runs = player.getRunsScored();
            for (int i = 0; i < player.getBallsFaced(); i++) {
                System.out.print(runs[i]);
                if (i < player.getBallsFaced() - 1) {
                    System.out.print(",");
                }
            }
            System.out.println("=" + player.getTotalRunsScored() + " (" + player.getBallsFaced() + ")");
        }
        System.out.print("Extras " );
        for(int i=1; i<= calculateTeamExtras() ; i++)
        {
            System.out.print("1 ,");
        }
        System.out.println(" =  " + calculateTeamExtras());
    }
 
    private int calculateTeamExtras() {
        int teamExtras = 0;
        for (Player player : players) {
            teamExtras += player.getExtras();
        }
        return teamExtras;
    }
}
 
public class Codeathon08_Kishore {
    public static void main(String[] args) {
        String[] team1Players = {
                "Rohit Sharma", "Shubman Gill", "Virat Kohli", "KL Rahul", "Ishan Kishan",
                "Hardik Pandya", "Ravindra Jadeja", "Washington Sundar", "Kuldeep Yadav",
                "Mohammed Siraj", "Jasprit Bumrah"
        };
        String[] team2Players = {
                "Pathum Nissanka", "Kusal Perera", "Kusal Mendis", "Sadeera Samarawickrama",
                "Charith Asalanka", "Dhananjaya de Silva", "Dasun Shanaka", "Dunith Wellalage",
                "Dushan Hemantha", "Pramod Madushan", "Matheesha Pathirana"
        };
        Team team1, team2;
        Random random = new Random();
        double tossResult = random.nextDouble() * 2;
        String tossWinner = (tossResult < 1.0) ? "SL" : "India";
 
        System.out.println("Toss Won By " + tossWinner);
 
        if (tossResult < 1.0) {
            team1 = new Team("Sri Lanka", team2Players);
            team2 = new Team("India", team1Players);
        } else {
            team1 = new Team("India", team1Players);
            team2 = new Team("Sri Lanka", team2Players);
        }
 
        Thread innings1 = new Thread(team1);
        Thread innings2 = new Thread(team2);
        innings1.start();
        innings2.start();
        try {
            innings1.join();
            innings2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
 
        if (tossResult < 1.0) {
            team1.displayBattingScorecard();
            System.out.println("Total Score " + team1.getTotalScore() + " in 10 overs");
            System.out.println();
            team2.displayBattingScorecard();
            System.out.println("Total Score " + team2.getTotalScore() + " in 10 overs");
        } else {
            team2.displayBattingScorecard();
            System.out.println("Total Score " + team2.getTotalScore() + " in 10 overs");
            System.out.println();
            team1.displayBattingScorecard();
            System.out.println("Total Score " + team1.getTotalScore() + " in 10 overs");
        }
 
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        String matchResult = determineMatchResult(team1, team2);
        System.out.println("\nMatch Result: " + matchResult);
        System.out.println("Today's Date: " + dateFormat.format(new Date()));
    }
 
    private static String determineMatchResult(Team team1, Team team2) {
        int team1Score = team1.getTotalScore();
        int team2Score = team2.getTotalScore();
        if (team1Score > team2Score) {
            return "Team India Won By " + (team1Score - team2Score) + " Runs";
        } else if (team1Score < team2Score) {
            return "Team Sri Lanka Won By " + (team2Score - team1Score) + " Runs";
        } else {
            return "Match Tied";
        }
    }
}

No comments:

Post a Comment