[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
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!).
(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";
}
}
}
private String name;
private int[] runsScored;
private int ballsFaced;
private int extras;
this.name = name;
this.runsScored = new int[60]; // Max 10 overs, 6 balls per over
this.ballsFaced = 0;
this.extras = 0;
}
return name;
}
return ballsFaced;
}
return extras;
}
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++;
}
}
}
int totalRuns = 0;
for (int i = 0; i < ballsFaced; i++) {
totalRuns += runsScored[i];
}
return totalRuns;
}
return runsScored;
}
}
private String name;
private Player[] players;
private int totalScore;
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]);
}
}
return totalScore;
}
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());
}
int teamExtras = 0;
for (Player player : players) {
teamExtras += player.getExtras();
}
return teamExtras;
}
}
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";
team1 = new Team("Sri Lanka", team2Players);
team2 = new Team("India", team1Players);
} else {
team1 = new Team("India", team1Players);
team2 = new Team("Sri Lanka", team2Players);
}
Thread innings2 = new Thread(team2);
innings1.start();
innings2.start();
try {
innings1.join();
innings2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
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");
}
String matchResult = determineMatchResult(team1, team2);
System.out.println("\nMatch Result: " + matchResult);
System.out.println("Today's Date: " + dateFormat.format(new Date()));
}
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