Monday, 9 October 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 (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.

Points to Note

200 Marks will be Awarded to this Question. Pass Marks are at 120. You have to understand if you do not use any threading or async task execution in java, you will be awarded at the maximum 120- 140 marks, provided that your logic is working correctly. The Remaining 60-80 marks are given to showcase/prove your skills in Java Multi-Threading or Async Task Execution. You have to start the first thread for the first innings while the main program runs, then once the innings is complete, you have to make sure that the main program understands that. Similar way you have to start the second thread and note there might be shared objects or shared data to use. Please make sure you also understand/demonstrate thread safety.

[Explanation of Solution]

This Java program simulates a cricket match between India and Sri Lanka using multi-threading. It begins by randomly determining which team bats first and then runs the innings in separate threads.

Each ball bowled is generated with a random number from 0 to 7, where 0 means the batsman is out, 1 to 6 represent the runs scored, and 7 signifies an extra run. The match consists of two innings, and the program keeps track of batsmen, their scores, and extras.

The match result is determined based on the scores of both teams. If the second team's score is lower than the first team's, team 1 wins. If the scores are tied, it's a tie, and if the second team scores more, team 2 wins.

The program showcases multi-threading concepts to simulate the cricket match and provides a detailed scorecard at the end. 

[Solution (Java Code)] 

package codeathon;

import java.util.Date;

public class Codeathon08_vijay {
public static void main(String arg[])  {
String team1[] = {"Rohit Sharma", "Shubman Gill", "Virat Kohli", "KL Rahul", "Ishan Kishan",
                "Hardik Pandya", "Ravindra Jadeja", "Washington Sundar", "Kuldeep Yadav",
                "Mohammed Siraj", "Jasprit Bumrah"};
        String team2[] = {"Pathum Nissanka", "Kusal Perera", "Kusal Mendis", "Sadeera Samarawickrama",
                "Charith Asalanka", "Dhananjaya de Silva", "Dasun Shanaka", "Dunith Wellalage",
                "Dushan Hemantha", "Pramod Madushan", "Matheesha Pathirana"};
        Team india = new Team("India", team1);
        Team sriLanka = new Team("Sri Lanka", team2);
        Thread team1Thread = new Thread(india);
        Thread team2Thread = new Thread(sriLanka);
        double random = Math.random() * 10;
        double toss = random % 2;
        for(int i = 0; i < 2; i++) {
            if(toss > 0 && toss < 1) {
                if(i == 0) {
                    System.out.println("India Batting first");
                } else {
                    System.out.println("\nIndia Batting Second");
                }
                team1Thread.start();
                try {
                    team1Thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                toss = 1.5;
            } else {
                if(i == 0) {
                    System.out.println("Sri Lanka Batting first");
                } else {
                    System.out.println("\nSri Lanka Batting Second");
                }
                team2Thread.start();
                try {
                    team2Thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                toss = 0.5;
            }
        }
        if(india.totalScore > sriLanka.totalScore) {
            System.out.println("India Won By " + (india.totalScore - sriLanka.totalScore));
            System.out.println("Today date: = " + new Date());
        }
        if(sriLanka.totalScore > india.totalScore) {
            System.out.println("Sri Lanka Won By " + (sriLanka.totalScore - india.totalScore));
            System.out.println("Today date: = " + new Date());
        }
    }
}

class Team implements Runnable {
    String teamName;
    String playerName[];
    int totalScore = 0;
    int runsPerBall[];
    play players[];

    Team(String team, String player[]) {
        teamName = team;
        playerName = player;
        runsPerBall = new int[60];
        players = new play[11];
    }

    @Override
    public void run() {
        int ballsBowled = 0;
        int extras = 0;
        int totalRuns = 0;

        for (int i = 0; i < 11; i++) {
            players[i] = new play(teamName, playerName[i]);
            totalRuns = 0;
            int ballLength = 0;
            extras = 0;
            for (int j = 0; ballsBowled < 60; j++) {
                double random = Math.random() * 10;
                int runs = (int) random % 8;
                ballsBowled++;
                ballLength++;
                totalRuns += runs;
                if (runs == 7) {
                    extras++;
                    runs = 6;
                }
                runsPerBall[j] = runs;
                if (runs == 0) {
                    break;
                }
            }
            if (ballLength == 0) {
                players[i].count = new int[]{0, 0, 0};
            } else {
                players[i].count = runsPerBall;
            }
            players[i].ballsBowled = ballLength;
            players[i].extras = extras;
            players[i].totalRuns = totalRuns;
            m1(players[i]);
        }
        for (int i = 0; i < 10; i++) {
            totalScore = totalScore + players[i].totalRuns;
        }
        double overs = (double) ballsBowled / 6;
        System.out.println("\nTotal Score = " + totalScore + " total Overs = " + (int) (Math.round(overs * 10)) / 10.0);
    }

    void m1(play player) {
        System.out.print(player.playerName + " " + player.ballsBowled + "(");
        for (int i = 0; i < 60; i++) {
            System.out.print(player.count[i]);
            if (player.count[i] == 0) {
                break;
            } else {
                System.out.print(",");
            }
        }
        System.out.print(") = " + player.totalRuns + "  (total extra = " + player.extras + ")");
        System.out.println();
    }
}

class play {
    String teamName;
    String playerName;
    int ballsBowled;
    int extras;
    int[] count;
    int totalRuns;

    play(String team, String player) {
        teamName = team;
        playerName = player;
        count = new int[60];
    }
}

Thank you,

k.vijay(Intern)

vijay.keradhi@eminds.ai

Enterprise Minds.

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

Explanation:

This program takes a valid Windows directory as input and checks if it exists. If not found, it displays a "Directory Not Found" message. Otherwise, it recursively searches for .txt and .exe files in the directory and its subdirectories, storing them in a sorted Java collection.

The collection is structured with the fully qualified directory name as the key and a list of .txt and .exe files as the values. It continues this process for all child directories until there are no more directories to traverse.

The output displays the directory hierarchy with file names, sorted by directory name. Each line represents a directory and lists the corresponding .txt and .exe files found within it. 

[Explaination of the solution]

In this problem give the  input as directory and find the text and exe files in that directory. 

Github Repo for Code:https://github.com/em-tpt-kvijay/emt_codeathon_sep_2023_solutions/blob/master/src/codeathon/Codeathon07_vijay.java

[Solution (Java Code)]

package codeathon;

import java.io.File;

import java.util.*;

public class Codeathon07_vijay {

    public static Map<String, List<String>> traverseAndCollectFiles(String directoryPath) {

        Map<String, List<String>> filesMap = new HashMap<>();

        traverseDirectory(directoryPath, filesMap);

        return filesMap;

    }

    private static void traverseDirectory(String directoryPath, Map<String, List<String>> filesMap) {

        File directory = new File(directoryPath);

        if (!directory.exists() || !directory.isDirectory()) {

            System.out.println("Directory Not Found on the Filesystem");

            return;

        }

        File[] files = directory.listFiles();

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

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

        for (File file : files) {

            if (file.isFile()) {

                String fileName = file.getName();

                if (fileName.endsWith(".txt")) {

                    txtFiles.add(fileName);

                } else if (fileName.endsWith(".exe")) {

                    exeFiles.add(fileName);

                }

            }

        }

        String fullPath = directory.getAbsolutePath();

        if (!txtFiles.isEmpty() || !exeFiles.isEmpty()) {

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

            fileList.addAll(txtFiles);

            fileList.addAll(exeFiles);

            filesMap.put(fullPath, fileList);

        }

        for (File file : files) {

            if (file.isDirectory()) {

                traverseDirectory(file.getAbsolutePath(), filesMap);

            }

        }

    }

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the directory path: ");

        String directoryPath = scanner.nextLine();

        Map<String, List<String>> filesMap = traverseAndCollectFiles(directoryPath);

        for (Map.Entry<String, List<String>> entry : filesMap.entrySet()) {

            System.out.print(entry.getKey());

            List<String> filesList = entry.getValue();

            if (!filesList.isEmpty()) {

                System.out.print("\t");

                for (String file : filesList) {

                    System.out.print(file + ", ");

                }

                System.out.println();

            } else {

                System.out.println();

            }

        }

        scanner.close();

    }

}

Thank you,

k.vijay(Intern)

vijay.keradhi@eminds.ai

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>thactually contains the key as the unique code and the list of fruits that correlates to that unique key.

Sample Input

List 1

OE1234

0823F

1200J

600K

456700I

A001

8432X

List 2

Apple,

Orange,

Banana,

Grape,

Watermelon

Pomegranate ,

Jackfruit

Sample Output

0E1234: 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.

Explanation:

In this cryptic fruit game, two lists are given. The first list contains unique identifiers, each representing a letter's position in the English alphabet. The second list contains fruits of varying lengths. The goal is to match each unique identifier with fruits whose length corresponds to the letter's position in the alphabet.

For example, if a unique identifier has 'E' at the 5th position, it should be matched with fruits of length 5, such as 'Apple' and 'Orange'. The output is a map where the keys are unique identifiers, 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 creates a map with this format and prints it as shown in the example output, displaying the key-value pairs. 

[Explaination of the solution]

In this problem list1 have one character in Unique code and list2 has some fruits name. If fruits name length is equal to the character in English's alphabetic order.Then we need to print list the fruits name with paricular unique code using <map,list<string>>.

Github Repo for Code:https://github.com/em-tpt-kvijay/emt_codeathon_sep_2023_solutions/blob/master/src/codeathon/Codeathon06_vijay.java

[Solution (Java Code)]

package codeathon;


import java.util.*;


public class Codeathon06_vijay {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the number of values for list1 and list2: ");

        int numValues = sc.nextInt();

        sc.nextLine();

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

        System.out.println("give list1 values:");

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

            String input = sc.nextLine();

            list1.add(input);

        }


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

        System.out.println("give list2 values:");

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

            String input = sc.nextLine();

            list2.add(input);

        }


        Map<String, List<String>> resultMap = new HashMap<>();


        for (int i = 0; i < list1.size(); i++) {

            String str = list1.get(i);

            List<String> fruits = findTheListOfFruits(str, list2);

            resultMap.put(str, fruits);

        }


        for (int i = 0; i < list1.size(); i++) {

            String str = list1.get(i);

            List<String> findFruits = resultMap.get(str);//here we are getting list of fruits name with key string value

            System.out.print(str + ": ");

            if (findFruits.isEmpty()) {

                System.out.println("[no fruit]");

            } else {

                System.out.println(String.join(",", findFruits));

            }

        }

    }


    private static List<String> findTheListOfFruits(String str, List<String> fruitList) {

        char word = findTheLetter(str);

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


        for (int i = 0; i < fruitList.size(); i++) {

            String s = fruitList.get(i);

            if (s.length() == word - 'a' + 1) {

                findFruits.add(s);

            }

        }

        return findFruits;

    }


    private static char findTheLetter(String uniqueCode) {

        for (char ch : uniqueCode.toCharArray()) {

            if (Character.isLetter(ch)) {

                return Character.toLowerCase(ch);

            }

        }

        return ' ';

    }

}

Thank you,

k.vijay(Intern)

vijay.keradhi@eminds.ai

Enterprise Minds.


EM-Tirupati Codeathon Series #05

[Question]

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.

[Explanation of the Solution]

In this problem we are  using Java Inheritance / Simple oops concepts to call display method in rectangle class and area of traingle REctangleArea class.

Github Repo for Code:https://github.com/em-tpt-kvijay/emt_codeathon_sep_2023_solutions/blob/master/src/codeathon/Codeathon05A_vijay.java

[Solution (Java Code)]

package codeathon;

import java.util.Scanner;

class Rectangle{

    int width;

    int height;

    void display() {

        System.out.println(width + " " + height);

    }

}

class RectangleArea extends Rectangle {

    void read_input() {

        Scanner scanner = new Scanner(System.in);

        width = scanner.nextInt();

        height = scanner.nextInt();

        scanner.close();

    }

    @Override

    void display() {

        super.display();// get the information from parent class

        int area = width * height;

        System.out.println(area);   // prints the area of a rectangle

    }

}

    public class Codeathon05A_vijay {

        public static void main(String[] args) {

            RectangleArea rectangleArea =new RectangleArea();

            rectangleArea.read_input();

            rectangleArea.display();


        }

    }


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

[Explanation of the Solution]:

This Java program swaps the values of two variables, `var1` and `var2`, without using a third variable. It ensures that after swapping, `var1` holds 10% (rounded down) of the original `var2` value, and `var2` holds 20% (rounded down) of the original `var1` value.

For example, if `var1` initially has a value of 250 and `var2` has a value of 400, after swapping, `var1` will be updated to hold 10% of 400 (40), and `var2` will hold 20% of 250 (50). The program then prints the swapped values, resulting in `var1=40` and `var2=50`.

Github Repo for Code:https://github.com/em-tpt-kvijay/emt_codeathon_sep_2023_solutions/blob/master/src/codeathon/Codeathon05B_vijay.java

[Solution (Java Code)]

package codeathon;

import java.util.Scanner;

public class codeathon05B_vijay {

    public static void main(String[] args) {

        System.out.println("Enter the value of x and y");

        Scanner sc = new Scanner(System.in);

        int variable1 = sc.nextInt();

        int variable2 = sc.nextInt();

        variable1 = variable1 + variable2;

        variable2 = (variable1 -  variable2);

        variable1 = (variable1 - variable2);

        System.out.println("variable1 = " + ((int)(0.10*variable1)));//10% of variable1

        System.out.println("variable2 = " + ((int)(0.20*variable2)));//20% of variable2

    }

}

Thank you,

k.vijay(Intern)

vijay.keradhi@eminds.ai

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

[Explanation of the Solution]

Here in this problem we need to consider first input as option and second input as number. According to the option we need to do Lambda operations for the number like(odd, prime, palindrome).

Github Repo for Code:https://github.com/em-tpt-kvijay/emt_codeathon_sep_2023_solutions/blob/master/src/codeathon/Codeathon04_vijay.java

[Solution (Java Code)]


package codeathon;

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

import java.util.StringTokenizer;

interface  Operation{

    boolean check(int a);

}


class FindTheValue {

    public static boolean checker(Operation p, int num) {

        return p.check(num);

    }


    public static Operation is_odd() {

        return n -> (n & 1) == 1;

    }


    public static Operation is_prime() {

        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;

        };

    }


    public static Operation is_palindrome() {

        return n -> {

            String original = Integer.toString(n);

            String reversed = new StringBuilder(Integer.toString(n)).reverse().toString();

            return original.equals(reversed);

        };

    }

}


public class codeathon04_vijay {

    public static void main(String[] args) {

        FindTheValue ob = new FindTheValue();

        Scanner scanner = new Scanner(System.in);

        int T = scanner.nextInt();

        Operation op;

        String ans = null;

        scanner.nextLine();


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


        while (T-- > 0) {

            String s = scanner.nextLine().trim();

            StringTokenizer st = new StringTokenizer(s);

            int ch = Integer.parseInt(st.nextToken());

            int num = Integer.parseInt(st.nextToken());

            switch(ch)

            {

                case 1:

                    op = ob.is_odd();

                    ans = ob.checker(op, num) ? "ODD" : "EVEN";

                    results.add(ans);

                    break;


                case 2:

                    op = ob.is_prime();

                    ans = ob.checker(op, num) ? "PRIME" : "COMPOSITE";

                    results.add(ans);

                    break;

                case 3:

                    op = ob.is_palindrome();

                    ans = ob.checker(op, num) ? "PALINDROME" : "NOT PALINDROME";

                    results.add(ans);

                    break;

                default :

                    System.out.println("Enter vaild option for input "+ch+":"+num);

            }

        }

        scanner.close();

        for (String result : results) {

            System.out.println(result);

        }

    }

}

Thank you,

k.vijay(Intern)

vijay.keradhi@eminds.ai

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.

[Explanation of the Solution]

In this problem one monkey wants to meet another monkey .so we need to find maximum distances travel by two monkeys.In that first we need find the clockwise and Anticlockwise distance between two monkeys.consider short distance between them and calculate both tree heights.and find the max distance.

Github Repo for Code: https://github.com/em-tpt-kvijay/emt_codeathon_sep_2023_solutions/blob/master/src/codeathon/Codeathon03_vijay.java

[Solution (Java Code)]

package codeathon;

import java.util.Scanner;

    public class Codeathon03_vijay {

        public static void main(String[] args) {


            Scanner sc = new Scanner (System.in);

            int clockwise=0;

            int anticlockwise=0;

            int lenght=0;

            int total=0;

            System.out.println("Enter no of trees");

            int n = sc.nextInt();


            int height[] = new int[n];

            int max=0;

            System.out.println("Enter their respective heights of the tree");

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

                height[i] = sc.nextInt();

            }

            max=height[0];

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

                for(int j=i+1;j<n;j++) {

                    clockwise=Math.abs(((n-j)+i));//find the distance between trees Clockwise

                    anticlockwise=Math.abs((j-i));//find the distance between trees Anticlockwise

                    if(clockwise<=anticlockwise) {

                        lenght=clockwise;

                    }

                    else{

                        lenght=anticlockwise;

                    }

                    total=lenght+height[i]+height[j];

                    if(total>max)

                        max=total;

                }

            }

            System.out.println("maximum time travel between trees :"+max);

        }

    }

Thank you,

k.vijay(Intern)

vijay.keradhi@eminds.ai

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.

Function Description

Complete the function most ACTIVE in the Editor Below.

most ACTIVE 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.

Github Repo for Code: https://github.com/em-tpt-kvijay/emt_codeathon_sep_2023_solutions/blob/master/src/codeathon/Codeathon02_vijay.java

[Solution (Java Code)]

package codeathon;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

import java.util.Scanner;


public class Codeathon02_vijay{


    public static List<String> mostActive(String[] customers) {

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

        int totalTrades = customers.length;

        int threshold = (int) (0.05 * totalTrades);


        // Sort the array of customers

        Arrays.sort(customers);


        int currentCount = 1;

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

            if (customers[i].equals(customers[i - 1])) {

                currentCount++;

            } else {

                if (currentCount >= threshold) {

                    result.add(customers[i - 1]);

                }

                currentCount = 1;

            }

        }


        // Check the last customer

        if (currentCount >= threshold) {

            result.add(customers[totalTrades - 1]);

        }


        return result;

    }


    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);


        System.out.println("Enter the number of trades:");

        int numTrades = scanner.nextInt();

        scanner.nextLine();

        if (numTrades <= 0) {

            System.out.println("Please enter trades must be greater than zero.");

            return; // Exit the program if numTrades is not valid.

        }


        String[] customers = new String[numTrades];

        System.out.println("Enter the names of customers (one on each line):");

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

            customers[i] = scanner.nextLine();

        }

        System.out.println("OUTPUT:");

        List<String> activeCustomers = mostActive(customers);

        if (activeCustomers.isEmpty()) {

            System.out.println("No active customers found.");

        }

        else {

            for (String customer : activeCustomers) {

                System.out.println(customer);

            }

        }

    }

}

Thank you,

k.vijay(Intern)

vijay.keradhi@eminds.ai

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 focu...