Thursday, October 12, 2023

EM-Tirupati Codeathon Series #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 © 1,4,6,0=11 (4)

Dunith Wellalage 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.

Code Explaination:

Main Class and Initialization:

  • The Question08_Venkata class contains the main method, serving as the program's entry point.
  • Two arrays, team1Players and team2Players, are created to represent the players in each team.

Team Class:

  • Represents a cricket team, encapsulating data and actions.
  • Contains instance variables for team name, players, and total score.
  • The constructor initializes the team's name and player roster.
  • Provides methods to get the team's name and total score.
  • playInnings simulates the batting innings for each player in the team.
  • Calculates and displays total score, overs, and extras.

Player Class:

  • Represents an individual player in the team.
  • Stores player's name, total runs, extras, balls bowled, and runs per ball.
  • The constructor initializes the player with a name.
  • Offers methods to get player-specific statistics.
  • playInnings simulates the player's innings, generating runs, extras, and calculating balls bowled.
  • displayScore shows the player's detailed performance.

Main Method:

  • Creates two teams, team1 and team2, with their player arrays.
  • Simulates the toss using a random number and lets the winning team choose to bat first.
  • Calls the playMatch method twice, simulating both teams' innings.
  • Determines the match result based on total scores.
  • Prints the match result and date to the console.

The code models a cricket match using Java classes, providing detailed player scores and following SOLID principles for clean and structured code.

GitHub Repo link: http://surl.li/lyiqv  

Source Code(Java):

import java.util.Date;

public class Question08_Venkata {
   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 = new Team("India", team1Players);
      Team team2 = new Team("Sri Lanka", team2Players);

      // Simulate the toss
      double toss = Math.random() * 10;
      if (toss < 1) {
         System.out.println("Toss Won By SL (Team 0)");
         playMatch(team2, team1);
      } else {
         System.out.println("Toss Won By India (Team 1)");
         playMatch(team1, team2);
      }
   }

   private static void playMatch(Team battingTeam, Team bowlingTeam) {
      System.out.println(battingTeam.getName() + " - Batting Scoresheet");
      battingTeam.playInnings();

      System.out.println("\n" + bowlingTeam.getName() + " — Batting Scoresheet");
      bowlingTeam.playInnings();

      String matchResult = battingTeam.getTotalScore() > bowlingTeam.getTotalScore()
            ? battingTeam.getName()
            : (battingTeam.getTotalScore() < bowlingTeam.getTotalScore() ? bowlingTeam.getName() : "Match Tied");
      int runDifference = Math.abs(battingTeam.getTotalScore() - bowlingTeam.getTotalScore());
      System.out.println("\nMatch Result: " + matchResult + " Won By " + runDifference + " Runs");
      System.out.println("Today's Date: " + new Date());
   }
}

class Team {
   private String name;
   private String[] players;
   private int totalScore;

   public Team(String name, String[] players) {
      this.name = name;
      this.players = players;
      this.totalScore = 0;
   }

   public String getName() {
      return name;
   }

   public int getTotalScore() {
      return totalScore;
   }

   public void playInnings() {
      int totalBalls = 0;
      int totalExtras = 0;
      for (String player : players) {
         Player p = new Player(player);
         p.playInnings();
         totalScore += p.getTotalRuns();
         totalBalls += p.getBallsBowled();
         totalExtras += p.getExtras();
         p.displayScore();
      }

      double totalOvers = totalBalls / 6;
      System.out.println("Extras " + totalExtras);
      System.out.println("Total Score " + totalScore + " in " + totalOvers + " overs");
   }
}

class Player {
   private String playerName;
   private int totalRuns;
   private int extras;
   private int ballsBowled;
   private int[] runsPerBall;

   public Player(String playerName) {
      this.playerName = playerName;
      this.totalRuns = 0;
      this.extras = 0;
      this.ballsBowled = 0;
      this.runsPerBall = new int[60];
   }

   public int getTotalRuns() {
      return totalRuns;
   }

   public int getExtras() {
      return extras;
   }

   public int getBallsBowled() {
      return ballsBowled;
   }

   public void playInnings() {
      int ballsBowled = 0;
      int extras = 0;
      int totalRuns = 0;

      for (int i = 0; i < 60; i++) {
         int run = (int) (Math.random() * 10) % 8;
         ballsBowled++;
         totalRuns += run;

         if (run == 7) {
            extras++;
            run = 1;  // Convert a 7 into a 1
         } else if (run == 0) {
            break;
         }

         runsPerBall[i] = run;
      }

      this.ballsBowled = ballsBowled;
      this.extras = extras;
      this.totalRuns = totalRuns;
   }

   public void displayScore() {
      System.out.print(playerName + " " + ballsBowled + " (");
      for (int i = 0; i < runsPerBall.length; i++) {
         System.out.print(runsPerBall[i]);
         if (runsPerBall[i] == 0) {
            break;
         }
         System.out.print(", ");
      }
      System.out.println(") = " + totalRuns + " (" + extras + " extra)");
   }
}


Thank you

Venkata kishore T(Intern)

Shield Warriors,

Data Shield Team,

Enterprise Minds.

Wednesday, October 11, 2023

EM-Tirupati Codeathon Series #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:\filesfile1.txt, file2.exe

c:\files\filex                             

c:\files\filexz\filez                      

c:\files\filey       file4.txt, file5.exe                       

c:\files\filey\fileffile6.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.

Code Explaination:

  • The program is structured to collect specific file types within a specified directory and its subdirectories.
  • User Input:
    • The program starts by taking user input for a valid Windows directory path.
    • Check Directory Existence:
      • It checks if the specified directory exists on the filesystem and is indeed a directory. If not found, it displays an error message and exits.
    • Initialize Data Structures:
      • The program initializes a TreeMap called fileMap to store directory-path-file lists.
    • Define File Filtering Criteria:
      • An interface FileFilter is introduced for file filtering conditions.
      • A specific filter (txtAndExeFileFilter) is defined to accept files with .txt and .exe extensions.
    • Collect Files:
      • The program uses a recursive method collectFiles to navigate through directories and collect files that match the filter.
      • It stores the directory path and a list of filtered files in fileMap.
    • Display Results:
      • Finally, the program displays the collected data. It lists each directory and the associated files that match the filter criteria.

    GitHub Repo link: http://surl.li/lyiqn   


    Source Code(Java):

    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Scanner;
    import java.util.TreeMap;

    // Interface for file filtering
    interface FileFilter {
        boolean accept(File file);
    }

    public class Question07_Venkata {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter a valid Windows directory path: ");
            String directoryPath = scanner.nextLine();
            scanner.close();

            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 = new TreeMap<>();
            // Implement a file filter for .txt and .exe files
            FileFilter txtAndExeFileFilter = file -> file.isFile() && (file.getName().endsWith(".txt") || file.getName().endsWith(".exe"));

            collectFiles(directory, fileMap, txtAndExeFileFilter);

            for (Map.Entry<String, List<String>> entry : fileMap.entrySet()) {
                System.out.println("Directory: " + entry.getKey());
                System.out.println("Files: "+entry.getKey()+":  " + entry.getValue());
            }
        }

        private static void collectFiles(File directory, Map<String, List<String>> fileMap, FileFilter fileFilter) {
            File[] files = directory.listFiles();
            if (files != null) {
                List<String> filteredFiles = new ArrayList<>();
                for (File file : files) {
                    if (fileFilter.accept(file)) {
                        filteredFiles.add(file.getName());
                    }
                }
                if (!filteredFiles.isEmpty()) {
                    fileMap.put(directory.getAbsolutePath(), filteredFiles);
                }

                for (File subDirectory : files) {
                    if (subDirectory.isDirectory()) {
                        collectFiles(subDirectory, fileMap, fileFilter);
                    }
                }
            }
        }
    }

     

    Thank you

    Venkata kishore T(Intern)

    Shield Warriors,

    Data Shield Team,

    Enterprise Minds.

    EM-Tirupati Codeathon Series #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>th+++at actually contains the key as the unique code and the list of fruits that correlates to that unique key.

    [Sample Input]

    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 OE1234, 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 OE1234 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.

    Example:

    In this cryptic fruit game, you're given two lists. The first list has unique codes, each representing the position of a letter in the English alphabet. The second list contains fruits of various lengths. The objective is to pair each unique code with fruits whose length matches the position of the letter in the alphabet.

    For example, if a unique code corresponds to 'E' at the 5th position, it should be paired with fruits that have a length of 5, such as 'Apple' and 'Orange'. The result is a map where the keys are the unique codes, and the values are lists of matching fruits. If there are no matching fruits, it's represented as "[No Fruit]" in the output.

    The program generates this map in the specified format and displays it as shown in the example output, showing the key-value pairs.

     Code Explaination:

    1. This program enables users to play the "Cryptic Fruit Game," processing unique codes to find matching fruits based on alphabet letter positions. It demonstrates key Java programming aspects, including user input, data processing, and output generation.
    2. Input Collection:
        • Read the number of unique codes and fruits.
        • Collect unique codes and fruit names from the user.
    3. Alphabet Generation:
        • Generate the English alphabet (A to Z) and store it in the letters ArrayList
    4. Processing Unique Codes:

        • Process each unique code by calling the processWord method.
        • In the processWord method, check each character in the unique code.
        • If a character is an alphabet letter and exists in the letters ArrayList, add it to the processed word.
        • Result is a processed string representing the unique code based on matching alphabet letters.

    5. Matching Fruits:
        • Compare the length of the processed unique code with the indices of the English alphabet.
        • If the lengths match, collect fruits with corresponding lengths from the user's input.
    6. Result Map:
        • Construct a result map where each unique code is paired with matching fruits.
        • Use this map for generating the final output.
    7. Output Display:
        • Display the result for each unique code:
        • If matching fruits are found, list them.
        • If no matching fruits are found, display "[No Fruit]."
    GitHub Repo link: http://surl.li/mpkjs 

    Source Code(Java):

    import java.util.*;
    import java.util.stream.Collectors;

    public class Question06_Venkata

     {
        static ArrayList<String> letters = new ArrayList<>();

        public static Map<String, List<String>> playGame(List<String> uniqueCodes, List<String> fruits) {
            Map<String, List<String>> resultMap = new HashMap<>();

            // Iterate through the English alphabet
            for (char letter = 'A'; letter <= 'Z'; letter++) {
                String alphabet = String.valueOf(letter);
                letters.add(alphabet);
            }

            // Iterate through each character in the word
            for (String code : uniqueCodes) {
                String uniqueChar = processWord(code);
                int index = letters.indexOf(uniqueChar);

                List<String> matchingFruits = fruits.stream().filter(fruit -> fruit.length() == index).collect(Collectors.toList());
                resultMap.put(code, matchingFruits);
            }

            return resultMap;
        }

        public static String processWord(String word) {
            StringBuilder processedWord = new StringBuilder();

            for (int i = 0; i < word.length(); i++) {
                char character = word.charAt(i);

                // Check if the character is an alphabet letter
                if (Character.isAlphabetic(character)) {
                    String characterStr = String.valueOf(character).toUpperCase();

                    if (letters.contains(characterStr)) {
                        // If the character exists in the 'letters' ArrayList, add it to the processed word
                        processedWord.append(characterStr);
                    }
                }
            }
            return processedWord.toString();
        }

        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);

            System.out.print("Enter the number of unique codes and fruits: " + "\n");
            int numValues = scanner.nextInt();
            scanner.nextLine();

            List<String> uniqueCodes = new ArrayList<>();
            System.out.println("Enter unique codes:" + "\n");
            for (int i = 0; i < numValues; i++) {
                String input = scanner.nextLine();
                uniqueCodes.add(input);
            }

            List<String> fruits = new ArrayList<>();
            System.out.println("Enter fruit names:" + "\n");
            for (int i = 0; i < numValues; i++) {
                String input = scanner.nextLine();
                fruits.add(input);
            }

            Map<String, List<String>> resultMap = playGame(uniqueCodes, fruits);

            for (String code : uniqueCodes) {
                List<String> matchingFruits = resultMap.get(code);
                System.out.print(code + ": ");
                if (matchingFruits.isEmpty()) {
                    System.out.println("[No Fruit]");
                } else {
                    System.out.println(String.join(", ", matchingFruits));
                }
            }
            scanner.close();
        }
    }


    Thank you

    Venkata kishore T(Intern)

    Shield Warriors,

    Data Shield Team,

    Enterprise Minds.

     

    EM-Tirupati Codeathon Series #05

    [Question] #1

    Swap the variables (Java code)

    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

    Code Explaination:

    1. It demonstrates basic arithmetic operations in Java to swap and manipulate integer values.
    2. The program uses a Scanner to collect user input for var1 and var2.
    3. It swaps the values of var1 and var2 without a temporary variable using arithmetic operations
    4. After swapping, both var1 and var2 are scaled down by multiplying them by 0.1 and 0.2, respectively.
    5. The program displays the swapped and scaled values as "Swapped values: var1 = [var1], var2 = [var2]."
    GitHub Repo link:  http://surl.li/mpkjd

    Source Code(Java):

    import java.util.Scanner;

    public class Question05_01_Venkata {
        public static void main(String[] args) {
            // Step 1: Input
            Scanner input = new Scanner(System.in);
            System.out.print("Enter the value of var1: ");
            int var1 = input.nextInt();
            System.out.print("Enter the value of var2: ");
            int var2 = input.nextInt();

            // Step 2: Swap using arithmetic operations
            // Swap var1 and var2 without using a temporary variable
            var1 = var1 + var2;
            var2 = var1 - var2;
            var1 = var1 - var2;

            // Step 3: Apply a scaling factor
            // Scale down the swapped values
            var1 = (int) (0.1 * var1);
            var2 = (int) (0.2 * var2);

            // Step 4: Output
            System.out.println("Swapped values: var1 = " + var1 + ", var2 = " + var2);
        }
    }

     

    [Question] #2

    Java Inheritance / Simple oops [www.techgig.com]

    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 RectangleArea dass 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³

    [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 Second line, Print the Area of the Rectangle

    1. Code Explaination:

    1. Class Structure:
      • Two classes: Rectangle for storing dimensions and RectangleArea for calculation.
      • Inheritance: RectangleArea extends Rectangle for added functionality.
    2. User Input:
      • The program collects user input for rectangle width and height.
      • Input uses the Scanner class, and clear prompts are provided.
    3. Display Method Override:
      • RectangleArea class overrides display method to show dimensions and area.
    4. Area Calculation:
      • The program calculates the rectangle area by multiplying width and height.
    5. Main Method:
      • The entry point creates an instance of RectangleArea.
      • Displays a user-friendly interface with a title and prompts.
      • Collects user input and displays rectangle dimensions and area.
    6. User-Friendly:
      • The code offers a clear and user-friendly interface.
    7. Purpose:
      • Allows users to calculate the area of a rectangle from its dimensions. It follows best coding practices for clarity and usability.

     GitHub Repo link: http://surl.li/lyipp

    Source Code(Java):

    import java.util.Scanner;

    class Rectangle {
        int width;
        int height;

        public void display() {
            System.out.println("Rectangle dimensions: " + width + " x " + height);
        }
    }

    class RectangleArea extends Rectangle {
        public void readInput() {
            Scanner scanner = new Scanner(System.in);

            System.out.print("Enter the width of the rectangle: "+"\n");
            width = scanner.nextInt();

            System.out.print("Enter the height of the rectangle: "+"\n");
            height = scanner.nextInt();

            scanner.close();
        }

        @Override
        public void display() {
            super.display(); // Display dimensions from the parent class

            int area = width * height;
            System.out.println("Area of the rectangle: " + area);
        }
    }

    public class Codeathon05_02_Venkata {
        public static void main(String[] args) {
            RectangleArea rectangleArea = new RectangleArea();
            System.out.println("Rectangle Area Calculator");
            System.out.println("--------------------------"+"\n");

            rectangleArea.readInput(); // Prompt user to enter width and height
            rectangleArea.display();   // Display rectangle dimensions and area
        }
    }

     

    Thank you

    Venkata kishore T(Intern)

    Shield Warriors,

    Data Shield Team,

    Enterprise Minds.


     

     


    EM-Tirupati Codeathon Series #04

    [Question]

    Java Advanced — Lambda Expressions [www.techgig.com]

    Write the Following Methods that Return a Lambda Expression Performing a Specified Action: Perform Operation is Odd(): The Lambda Expression must return if a Number is Odd or If it is Even. Perform Operation is Prime(): The lambda expression must return if a number is prime or if it is composite. Perform Operation is 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

    Code Explaination:

    1. This program uses lambda expressions and functional interfaces to encapsulate different operations for checking numbers, making the code more modular and readable.
    2. The program defines a functional interface called Operation with a single method apply, which takes an integer and returns a boolean.
    3. The ValueChecker class provides methods to create lambda expressions using the Operation functional interface for three specific operations: checking if a number is odd, checking if it's prime, and checking if it's a palindrome.
    4. In the main method of the Question04_Venkata class:
      • An instance of ValueChecker is created.
      • The program reads the number of test cases from the user.
      • For each test case:
        • The program reads two integers from the user, representing a choice and a number.
        • Depending on the choice (1, 2, or 3), it selects the corresponding lambda expression from ValueChecker.
        • The selected lambda expression is applied to the input number using the apply method of the Operation functional interface.
        • The result is stored as a string, indicating whether the input number meets the criteria (e.g., "ODD," "PRIME," "COMPOSITE," "PALINDROME," or "NOT PALINDROME").
        • The results are added to a list.
    5. After processing all test cases, the program displays the results by iterating through the list and printing each result. 

    GitHub Repo link: http://surl.li/mpkit

    Source Code(Java):

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    import java.util.StringTokenizer;

    // Step 1: Define a functional interface for operations.
    interface Operation {
       boolean apply(int number);
    }

    class ValueChecker {
       public static boolean checkValue(Operation operation, int number) {
          return operation.apply(number);
       }
       // Step 2: Implement methods for operations as lambda expressions.
       public static Operation isOdd() {
          return n -> (n & 1) == 1; // Checks if a number is odd.
       }

       public static Operation isPrime() {
          return n -> {
             if (n < 2) {
                return false;
             }
             int sqrt = (int) Math.sqrt(n);
             for (int i = 2; i <= sqrt; i++) {
                if (n % i == 0) {
                   return false;
                }
             }
             return true; // Checks if a number is prime.
          };
       }

       public static Operation isPalindrome() {
          return n -> {
             String original = Integer.toString(n);
             String reversed = new StringBuilder(Integer.toString(n)).reverse().toString();
             return original.equals(reversed); // Checks if a number is a palindrome.
          };
       }
    }

    public class Question04_Venkata {
       public static void main(String[] args) {
          ValueChecker valueChecker = new ValueChecker();
          Scanner scanner = new Scanner(System.in);
          int testCases = scanner.nextInt();
          Operation operation;
          String result = null;
          scanner.nextLine();
          List<String> results = new ArrayList<>();

          while (testCases-- > 0) {
             String input = scanner.nextLine().trim();
             StringTokenizer tokenizer = new StringTokenizer(input);
             int choice = Integer.parseInt(tokenizer.nextToken());
             int number = Integer.parseInt(tokenizer.nextToken());

             // Step 3: Use the functional interfaces to check values.
             if (choice == 1) {
                operation = valueChecker.isOdd();
                result = valueChecker.checkValue(operation, number) ? "ODD" : "EVEN";
             } else if (choice == 2) {
                operation = valueChecker.isPrime();
                result = valueChecker.checkValue(operation, number) ? "PRIME" : "COMPOSITE";
             } else if (choice == 3) {
                operation = valueChecker.isPalindrome();
                result = valueChecker.checkValue(operation, number) ? "PALINDROME" : "NOT PALINDROME";
             }

             results.add(result);
          }

          scanner.close();

          // Step 4: Display the results.
          for (String output : results) {
             System.out.println(output);
          }
       }
    }


    Thank you

    Venkata kishore T(Intern)

    Shield Warriors,

    Data Shield Team,

    Enterprise Minds.

    EM-Tirupati Codeathon Series #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.


    Code Explaination:

    1. The program, "Question03_Venkata," calculates the maximum travel time for two monkeys in a circular garden with varying tree heights.
    2. Users are prompted to input the number of trees and their respective heights.
    3. The calculateMaximumTravelTime method computes the maximum travel time by iterating through each tree as a potential starting point for one of the monkeys.
    4. For each pair of trees, the method calculates clockwise and anticlockwise distances, choosing the shortest path and adding tree heights to determine the total time.
    5. The program employs a Scanner to collect user input and displays the maximum travel time once calculated.
    6. It offers a straightforward tool for analyzing travel times between trees in a circular garden with variable tree heights.
    GutHub Repo link : https://rb.gy/bf1d5

    Source Code(Java):

    import java.util.Scanner;

    public class Question03_Venkata {

       /**
        * Calculates the maximum travel time for two monkeys in a circular garden.
        */
      
    public static int calculateMaximumTravelTime(int[] treeHeights) {
          int maxTravelTime = 0;
          int n = treeHeights.length;

          for (int i = 0; i < n; i++) {
             int maxTime = 0;

             for (int j = i + 1; j < n; j++) {
                int clockwiseDistance = (n - j + i) % n;
                int anticlockwiseDistance = (j - i) % n;
                int shortestDistance = Math.min(clockwiseDistance, anticlockwiseDistance);

                int totalTime = shortestDistance + treeHeights[i] + treeHeights[j];
                maxTime = Math.max(maxTime, totalTime);
             }

             maxTravelTime = Math.max(maxTravelTime, maxTime);
          }

          return maxTravelTime;
       }

       public static void main(String[] args) {
          Scanner scanner = new Scanner(System.in);

          System.out.print("Enter the number of trees: ");
          int n = scanner.nextInt();

          int[] treeHeights = new int[n];

          System.out.println("Enter the heights of trees (one on each line):");
          for (int i = 0; i < n; i++) {
             treeHeights[i] = scanner.nextInt();
          }

          int maxTravelTime = calculateMaximumTravelTime(treeHeights);
          System.out.println("Maximum Traveling Time: " + maxTravelTime);

          scanner.close();
       }
    }

    Thank you

    Venkata kishore T(Intern)

    Shield Warriors,

    Data Shield Team,

    Enterprise Minds.

     

    EM-Tirupati Codeathon Series #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.

    Constraints

    • 1 < n < 10⁵
    • 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 at least 5% of Trades.

    [Sample Input]

    “The First Line contains an integer, n, The Number of Elements in customers.”

    “Each Line of 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

    Fnction 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⁵

    • 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 at least 5% of Trades.

    [Sample Input]

    “The First Line contains an integer, n, The Number of Elements in customers.”

    “Each Line of 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 most ACTIVE

    customers[] size n = 20

    customers[] = [As Provided Above]

    [Sample Output]

    Alpha

    Beta

    Omega

    [Explanation of Solution]

    In this problem  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.

    Code Explaination:

    1. This code is written to identify and display the most active traders based on a given list of trades.
    1. The code consists of two classes: MostActiveTraders and Codeathon02_Venkat.
    1. MostActiveTraders contains the core logic for finding and displaying the most active traders, while Codeathon02_Venkat serves as the entry point for user input and result display.
    1. It employs two primary data structures: a Map<String, Integer> named tradeCounts to store trade counts for each trader and a List<String> named activeTraders to store the most active traders.
    1. User input is collected through a Scanner, allowing users to specify the number of trades they want to analyze and provide a list of trades (one trade per line).
    1. The findMostActiveTraders method counts the trades for each trader using a for-each loop and sets a threshold based on the number of trades (in this case, 5% of the total).
    1. Active traders are identified by iterating through the tradeCounts map and adding those whose trade counts exceed the threshold to the activeTraders list.
    1. Active traders are sorted alphabetically using Collections.sort.
    1. The displayActiveTraders method is used to display the active traders to the user.
    1. The code includes exception handling for potential IllegalArgumentException, although there is no specific case in the given code where this exception is thrown.

    GitHub Repo link: https://rb.gy/609wc

    Source Code(Java):

    import java.util.*;

    class MostActiveTraders {

        public List<String> findMostActiveTraders(List<String> trades, int numTrades) {

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


            // Count the trades for each trader

            for (String trader : trades) {

                tradeCounts.put(trader, tradeCounts.getOrDefault(trader, 0) + 1);

            }

            int threshold = numTrades * 5 / 100;

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

            // Find traders with trade counts above the threshold

            for (Map.Entry<String, Integer> entry : tradeCounts.entrySet()) {

                if (entry.getValue() > threshold) {

                    activeTraders.add(entry.getKey());

                }

            }

            // Sort the active traders alphabetically

            Collections.sort(activeTraders);

            int totalTrades = trades.size();

            return activeTraders;

        }

        void displayActiveTraders(List<String> activeTraders) {

            System.out.println("Most Active Traders:");

            for (String trader : activeTraders) {

                System.out.println(trader);

            }

        }

    }

     

    public class Codeathon02_Venkat {

        public static void main(String[] args) {

            MostActiveTraders mat = new MostActiveTraders();

            Scanner scanner = new Scanner(System.in);

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

            System.out.print("Enter the number of trades you want: ");

            int numTrades = scanner.nextInt();

            scanner.nextLine();

            System.out.println("Enter a list of trades (one trade per line):");

     

            while (trades.size() < numTrades) {

                String input = scanner.nextLine();

                trades.add(input);

            }

            try {

                List<String> activeTraders = mat.findMostActiveTraders(trades, numTrades);

                mat.displayActiveTraders(activeTraders);

            } catch (IllegalArgumentException e) {

                System.out.println("Error: " + e.getMessage());

            }

            scanner.close();

        }

    Thank you

    Venkata kishore T(Intern)

    Shield Warriors,

    Data Shield Team,

    Enterprise Minds.

    EM-Tirupati Codeathon Series #08

    [Question] ROBOTIC CRICKET MATCH you should write a program that simulate an automatic cricket match between India and Sri Lanka. The fo...