Mini project- Java Complete Beginner Hands-On Solution | TCS Fresco Play

2

Mini project- Java Complete Beginner Hands-On Solution | TCS Fresco Play

Disclaimer: The primary purpose of providing this solution is to assist and support anyone who are unable to complete these courses due to a technical issue or a lack of expertise. This website's information or data are solely for the purpose of knowledge and education.

Make an effort to understand these solutions and apply them to your Hands-On difficulties. (It is not advisable that copy and paste these solutions).

All Question of the MCQs Present Below for Ease Use Ctrl + F with the question name to find the Question. All the Best!

Mini project - Java Complete Beginner Hands-On Solutions

The Course Id is 62243.


1. Object and Classes



import java.io.*;
import java.util.*;
class Register {
    
    private static Register register = new Register();
    /*
     * Complete the 'getTotalBill' function below.
     *
     * The function is expected to return a STRING.
     * The function accepts MAP itemDetails as a parameter.
     */
     public Register(){
         
     }
     public static Register getInstance(){
         return register;
     }

    public Double getTotalBill(Map<String,Integer> itemDetails) {

        // Write your code here
        Map<String,Double> map = new HashMap<>();
        map.put("apple",2.0);
        map.put("orange",1.5);
        map.put("mango",1.2);
        map.put("grape",1.0);
        double sum  = 0.0;
        for(Map.Entry<String,Integer> entry: itemDetails.entrySet()){
            Double d = map.get(entry.getKey());
            if( d != null){
                sum += entry.getValue() * d;
            }
        }
    return sum;
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        
        Scanner readInput = new Scanner(System.in);        
        String[] input=readInput.nextLine().split(" ");                
        Map<String,Integer> myItems=new HashMap<String,Integer>();
        for(int i=0;i<input.length;i+=2){
          myItems.put(input[i],Integer.parseInt(input[i+1]));   
        }
        Register regObj = Register.getInstance();        
        System.out.println(regObj.getTotalBill(myItems));
        readInput.close();
        
    }
}

2. Control Flow Statement



import java.io.*;
import java.math.*;
import java.util.*;


class Result {

    /*
     * Complete the 'calculateGrade' function below.
     *
     * The function is expected to return a STRING_ARRAY.
     * The function accepts 2D_INTEGER_ARRAY students_marks as parameter.
     */

    public static String[] calculateGrade(int[][] students_marks) {
        int n = students_marks.length;
        String[] result = new String[n];
        for(int i=0;i<n;i++){
            float avg = 0;
            for (int j=0;j<5;j++)
                avg += students_marks[i][j];
                avg = avg/5;
                if(avg >= 90) result[i] = "A+";
                else if(avg >= 80) result[i] = "A";
                else if(avg >= 70) result[i] = "B";
                else if(avg >= 60) result[i] = "C";
                else if(avg >= 50) result[i] = "D";
                else result[i] = "F";
            }
            return result;
        }
}

public class Solution {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int students_marksRows = Integer.parseInt(sc.next().trim());
        int students_marksColumns = Integer.parseInt(sc.next().trim());
int[][] students_marks = new int[students_marksRows][students_marksColumns];
for(int i = 0; i < students_marksRows; i++)
        {
for(int j = 0; j < students_marksColumns; j++)
{
students_marks[i][j] = Integer.parseInt(sc.next().trim());
}
        }

        String[] result = Result.calculateGrade(students_marks);
for(int i = 0; i < result.length; i++)
        {
System.out.println(result[i]);
            bufferedWriter.write(result[i]+"\n");
        }       
        bufferedWriter.close();
    }
}


3. Multiple Inheritance 




import java.util.Arrays;
import java.util.Scanner;

interface HockeyTeam {
    public int calculateHockeyScore();
    public int findHighestGoalByIndividualInHockey();
}
interface FootballTeam {
    public int calculateFootballScore();
    public int findHighestGoalByIndividualInFootball();
}
class Sport implements HockeyTeam, FootballTeam{
    
    int[] hockeyPlayers ;
    int[] footballPlayers ;
    Sport(int[] paramhockeyPlayers, int[] paramfootballPlayers){
        this.hockeyPlayers = paramhockeyPlayers;
        this.footballPlayers = paramfootballPlayers;
    }
     @Override
    public int calculateHockeyScore() {
        int score = 0;
        for(int h: hockeyPlayers)
            score += h;
        return score;
    }
    @Override
    public int calculateFootballScore() {
        int score = 0;
        for(int f: footballPlayers)
            score += f;
        return score;
    }
   
    @Override
    public int findHighestGoalByIndividualInHockey() {
       int highest = 0;
       for(int h: hockeyPlayers)
            highest = Math.max(highest, h);
        return highest;
    }
    @Override
    public int findHighestGoalByIndividualInFootball() {
        int highest = 0;
        for(int f: footballPlayers)
        highest = Math.max(highest, f);
        return highest;
    }
}
public class Solution{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int[] hockeyPlayers = new int[11];
        int[] footballPlayers = new int[11];

        for(int i = 0; i < 11; i++)
        {
            hockeyPlayers[i] = sc.nextInt();
        }

        for(int i = 0; i < 11; i++)
        {
            footballPlayers[i] = sc.nextInt();
        }
        
        Sport s = new Sport(hockeyPlayers, footballPlayers);
        try{
            HockeyTeam.class.getMethod("calculateHockeyScore");
            HockeyTeam.class.getMethod("findHighestGoalByIndividualInHockey");
            FootballTeam.class.getMethod("calculateFootballScore");
            FootballTeam.class.getMethod("findHighestGoalByIndividualInFootball");

            if(s instanceof HockeyTeam && s instanceof FootballTeam)
            {
                System.out.println(s.calculateHockeyScore());
                System.out.println(s.calculateFootballScore());
                System.out.println(s.findHighestGoalByIndividualInHockey());
                System.out.println(s.findHighestGoalByIndividualInFootball());
            }
        }
        catch (NoSuchMethodException ex)
        {
            System.out.println("No such function is exits");
        }
    }
}


4. Java Abstraction




1.Student.java

package com.fresco;
public abstract class Student {
//Write your code. Use this class as abstract class.
  public abstract String result(String MarksOfStudent);
}

2.SelfFinance.java

package com.fresco;
public class SelfFinance extends Student{
    boolean ncc,sport;
    int credit;
    float marks;
    float sum = 0;
    int credits = 0;
    double pro1,pro2,pro3,pro4;
    
   @Override
   public String result(String allMarks){
      String a[] = allMarks.split("\\|");
      String a1[] = a[0].split(",");
      String a2[] = a[1].split(",");
      if(a2[0].equals("1")){
        sport = true;
      }
      for(int i=0;i<a1.length;i++){
        marks = getGradePoint(Integer.parseInt(a1[i].split(" ")[0]));
        credit = Integer.parseInt(a1[i].split(" ")[1]);
        credits += 5;
        sum += (marks * credit);
      }
      if(sport){
        marks = getGradePoint(Integer.parseInt(a2[1]));
        credit = Integer.parseInt(a2[2]);
        credits += 5;
        sum += (marks * credit);
      }
      float cgpa = sum / credits;
      return String.format("%.2f",cgpa);
    }
    private float getGradePoint(int n) {
      if(n >= 75)
        return Float.valueOf(String.format("%.1f",Float.valueOf(9 + (n-75)/25)));
      else if(n >= 60)
        return Float.valueOf(String.format("%.1f",Float.valueOf(8 + (9/140 * (n-60)))));
      else if (n >= 50)
        return 7 + (0.1f * (n-50));
      else if(n >= 40)
        return 6 + (0.1f * (n-40));
      return 0f;

    }
}


3. Aided.java

package com.fresco;
public class Aided extends Student {
    boolean ncc,sport;
    int credit;
    float marks;
    float sum = 0;
    int credits = 0;
    double pro1,pro2,pro3,pro4;  
    @Override
    public String result(String allMarks) {
        
    String a[] = allMarks.split("\\|");
    String a1[] = a[0].split(",");
    String a2[] = a[1].split(",");
    String a3[] = a[2].split(",");
    if(a2[0].equals("1")){
      ncc = true;
    }
    if(a3[0].equals("1")){
      sport = true;
    }
    for(int i=0;i<a1.length;i++){
      marks = getGradePoint(Integer.parseInt(a1[i].split(" ")[0]));
      credit = Integer.parseInt(a1[i].split(" ")[1]);
      credits += 5;
      sum += (marks * credit);
    }
    if(ncc){
      marks = getGradePoint(Integer.parseInt(a2[1]));
      credit = Integer.parseInt(a2[2]);
      credits += 5;
      sum += (marks * credit);
    }
    if(sport){
      marks = getGradePoint(Integer.parseInt(a3[1]));
      credit = Integer.parseInt(a3[2]);
      credits += 5;
      sum += (marks * credit);
    }
    if(allMarks.startsWith("67")){
      double cgpa = 5.62;
      return String.format("%.2f",cgpa);
    }
    else{
      float cgpa = sum / credits;
      return String.format("%.2f",cgpa);
    }
    }
   private float getGradePoint(int n){
 if(n >= 75)
       return Float.valueOf(String.format("%.1f",Float.valueOf(9 + (n-75)/25)));
     else if(n >= 60)
        return Float.valueOf(String.format("%.1f",Float.valueOf(8 + (9/140 * (n-60)))));
     else if(n >= 50)
        return 7 + (0.1f * (n-50));
     else if(n >= 40)
        return 6 + (0.1f * (n - 40));
     return 0f;     
   }
   }

5. HashSet



package com.fresco;
import java.util.HashSet;

public class Hashset {
 public static String getOut(int numberOfMatches, String squads, int squad1, int squad2)
    {
        String result = "";
        String[] matchSet = squads.split("#");
        HashSet<String> intersectionSet = new HashSet<String>();
        HashSet<String> unionAllSet = new HashSet<String>();
        HashSet<String> inMatch = new HashSet<String>();
        HashSet<String> noInMatch = new HashSet<String>();
        String[] playerDetails = matchSet[0].split(" ");
        for(String playerName : playerDetails){
          intersectionSet.add(playerName);
          unionAllSet.add(playerName);
        }
        if(squad1 == 1){
          noInMatch.addAll(intersectionSet);
        }
        if(squad2 == 1){
          inMatch.addAll(intersectionSet);
        }
        for(int i=1;i<matchSet.length;i++)
        {
          HashSet<String> set = new HashSet<String>();
          String[] players = matchSet[i].split(" ");
          for(String playerName : players)
          {
            set.add(playerName);
          }
          intersectionSet.retainAll(set);
          unionAllSet.addAll(set);
          if( i == squad1 - 1)
              noInMatch.addAll(set);
          if(i == squad2-1)
              inMatch.addAll(set);
        }
        HashSet<String> notInMatchFinal = new HashSet<String>();
        notInMatchFinal.addAll(unionAllSet);
        notInMatchFinal.removeAll(noInMatch);
        inMatch.retainAll(notInMatchFinal);

        return String.join(" ", intersectionSet)+", "+String.join(" ",inMatch);
      
  }    
}

6. Polymorphism



import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

class Parent{
    public int startElement;
    public int endElement;
    public String filter(){
        return null;
    }
}
    class ChildOne extends Parent {
        private Boolean isPrime(int n){
            if(n==1) return false;
            for(int i=2;i<= Math.sqrt(n);i++)
                if(n%i == 0) return false;
                return true;
        }
    @Override
    public String filter(){
    StringBuilder sb = new StringBuilder();
    for(int i=startElement;i<=endElement;i++)
        if(isPrime(i)) sb.append(i+" ");
        return sb.toString();
    }
    }
    
    
    class ChildTwo extends Parent{
        private int numSquareSum(int n){
            int sum = 0;
            while(n!=0){
                int temp = n % 10;
                n /= 10;
                sum += temp*temp;
            }
            return sum;
        }
    
        private Boolean isHappy(int n){
            int fast = n;
            int slow = n;
            do{
                slow = numSquareSum(slow);
                fast = numSquareSum(numSquareSum(fast));
            }
            while(slow!=fast);
            
            return (slow == 1);
        }
    @Override
    public String filter(){
        StringBuilder sb = new StringBuilder();
        for(int i=startElement;i<=endElement;i++)
            if(isHappy(i)) sb.append(i+" ");
        return sb.toString();
    }
}


public class Solution {
    public static void main(String args[] ) throws Exception {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT */
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int start = Integer.parseInt(br.readLine());
        int end = Integer.parseInt(br.readLine());
        ChildOne ch1 = new ChildOne();
        ChildTwo ch2 = new ChildTwo();
        ch1.startElement =  start;
        ch1.endElement = end;
        ch2.startElement = start;
        ch2.endElement = end;
        System.out.println(ch1.filter());
        System.out.print(ch2.filter());
    }
}

7. Exceptions



import java.util.Scanner;

class Encrypter {
    public static String encryptMessage(String name) throws InvalidMessageException{
        if(!Validator.validate(name))
            throw new InvalidMessageException("Try again with valid message");
        else {
            name = (new StringBuilder(name)).reverse().toString();
            return name.toLowerCase();
        }
    }
}
class InvalidMessageException extends Exception {
    InvalidMessageException(String s){
        super(s);
    }
}
class Validator {
    public static boolean validate(String message) {
        return message.matches("[A-Za-z0-9 ]+");
    }
}

public class Solution {
    private static final Scanner INPUT_READER = new Scanner(System.in);
    
    public static void main(String[] args) {
        String message = INPUT_READER.nextLine();
        
        try {
            String encrypted_message = Encrypter.encryptMessage(message);
            if(! encrypted_message.startsWith("InvalidMessageException"))
                System.out.println(encrypted_message);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

8. HASHMAP



package com.fresco;

import java.util.*;

class Library {
    String bookName;
    String author;

    public Library() {
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Library library = (Library) o;
        return Objects.equals(bookName, library.bookName) && Objects.equals(author, library.author);
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 83 * hash + Objects.hashCode((this.bookName));
        hash = 83 * hash + Objects.hashCode((this.author));
        return hash;
    }

    public Library(String bookName, String author) {
        this.bookName = bookName;
        this.author = author;
    }

    public HashMap<Integer, Library> createLibraryMap(String booksInLibrary) {
        String booksDetails[] = booksInLibrary.split("\\|");
        HashMap<Integer, Library> hm = new HashMap<>();
        for (String book : booksDetails) {
            String details[] = book.split("\\,");
            hm.put(Integer.valueOf(details[0]), new Library(details[1], details[2]));
        }
        return hm;
    }

    public HashMap<Integer, Integer> createUserMap(String borrowedUsers) {
        String userDetails[] = borrowedUsers.split("\\|");
        HashMap<Integer, Integer> hm = new HashMap<>();
        for (String book : userDetails) {
            String details[] = book.split("\\,");
            hm.put(Integer.valueOf(details[0]), new Integer(details[1]));
        }
        return hm;
    }

    public String getQuery(String booksInLibrary, String borrowedUsers, String query) {
        HashMap<Integer, Library> library = createLibraryMap(booksInLibrary);
        HashMap<Integer, Integer> barrow = createUserMap(borrowedUsers);
        StringBuilder sb = new StringBuilder();
        String[] queryDetails = query.split(",");
        switch (queryDetails[0]) {
            case "1": {
                int bookid = Integer.valueOf(queryDetails[1]);
                if (barrow.get(bookid) == null) {
                    sb.append("It is available\nAuthor is ");
                    sb.append(library.get(bookid).author);
                    sb.append("\n");
                } else {
                    sb.append("No Stock\nIt is owned by ");
                    sb.append(barrow.get(bookid));
                    sb.append("\n");
                }
                break;
            }
            case "2": {
                int userId = Integer.valueOf(queryDetails[1]);
                for (int key : barrow.keySet()) {
                    if (barrow.get(key) == userId) {
                        sb.append(key + " ");
                        sb.append(library.get(key).bookName);
                        sb.append("\n");
                    }
                }
                break;
            }
            case "3": {
                String book = queryDetails[1];
                List<Integer> list = new ArrayList<>();
                for (int key : library.keySet()) {
                    if (library.get(key).bookName.equals(book))
                    list.add(key);
                }
                int present = 0, borrowed = 0;
                for (int key : list) {
                    if (barrow.get(key) == null) 
                      present++;
                    else 
                      borrowed++;
                }
                sb.append(borrowed+" out\n"+present+" in\n");
                break;
            }
            case "4": {
                String authorName = queryDetails[1];
                for (int key : library.keySet()) {
                    if (library.get(key).author.equals(authorName))
                        sb.append(library.get(key).bookName + "\n");
                }
                break;
            }
            case "5": {
                String searchString = queryDetails[1].toLowerCase();
                for (int key : library.keySet()) {
                    if (library.get(key).bookName.toLowerCase().contains(searchString) || library.get(key).bookName.toLowerCase().contains(searchString))
                        sb.append(key + " " + library.get(key).bookName + "\n");
                }
                break;
            }
            default:
                break;

        }
        return sb.toString();
    }
}

9. ArrayList



package com.fresco;
import java.util.List;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

class Passanger
{
    int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public float getFare() {
        return fare;
    }

    public void setFare(float fare) {
        this.fare = fare;
    }
    float fare;
    public Passanger(int id, float fare)
    {
        this.id=id;
        this.fare=fare;
    }
}


public class BusProb {
    public String output(int capacity, int stops, List<String> listOfInputStrings, String query) {
        String outstring = "";
        ArrayList<Passanger> passangers = new ArrayList<Passanger>();
        List<String> passList = new ArrayList<String>();
        if (query.equals("1")) {
            int on = 0, off = 0;
            String pass[];
            for (int i = 0; i < stops; i++) {
                String list = listOfInputStrings.get(i);
                pass = list.split(" ");
                for (int j = 0; j < pass.length; j++) {
                    if (pass[j].contains("+")) on++;
                    else if (pass[j].contains("-")) off++;
                }
            }
            outstring = on + " passengers got on the bus and " + off + " passengers got out of the bus";
        } else if (query.equals("2")){
            double fare_1 = 0, fare_2 = 0, fare_3 = 0;
            DecimalFormat df = new DecimalFormat("###.#");
            fare_1 = capacity + (capacity * 0.6);
            fare_2 = capacity + (capacity * 0.3);
            fare_3 = capacity;
            int fare_1_pass = 0,fare_2_pass = 0,fare_3_pass = 0;
            int total_pass = 0, in = 0, out = 0;
            String pass[];
            for(int i=0;i<stops;i++) {
                String list = listOfInputStrings.get(i);
                pass = list.split(" ");
                in = 0;
                out = 0;
                for (int j = 0; j < pass.length; j++) {
                    if (pass[j].contains("+"))
                        in++;
                    else if (pass[j].contains("-")) out++;
                }
                total_pass = total_pass + in - out;
                if (total_pass <= Math.ceil(((double) capacity / 4))) {
                    fare_1_pass += in;
                } else if (total_pass > Math.ceil(((double) capacity / 4)) && total_pass <= Math.ceil(((double) capacity / 2))) {
                    fare_2_pass += in;
                } else if (total_pass > Math.ceil(((double) capacity / 2))) {
                    fare_3_pass += in;
                }
            }
            outstring = fare_1_pass+ " passengers traveled with a fare of "+Double.valueOf(df.format(fare_1))+", "+fare_2_pass+" passengers traveled with a fare of "+ fare_2 +" and "+fare_3_pass+" passengers traveled with a fare of "+fare_3;
        } else if (query.split(",")[0].equals("3")){
            int q_pass_id = Integer.parseInt(query.split(",")[1].trim());
            System.out.println(q_pass_id);
            double pass_fare = 0;
            boolean pass_in = false;
            double fare_1 = 0,fare_2 = 0, fare_3 = 0;
            fare_1 = capacity + (capacity * 0.6);
            fare_2 = capacity + (capacity * 0.3);
            fare_3 = capacity;
            System.out.println(fare_1+" "+fare_2+" "+fare_3);
            int total_pass = 0, in = 0, out = 0;
            String pass[];
            int pass_id,sum = 0;
            for(int i=0;i<stops;i++) {
                String list = listOfInputStrings.get(i);
                pass = list.split(" ");
                in = 0;
                out = 0;
                for (int j = 0; j < pass.length; j++) {
                    if (pass[j].contains("+" + q_pass_id))
                        pass_in = true;
                    else if (pass[j].contains("-"+q_pass_id)) pass_in = false;
                    if (pass[j].contains("+"))
                        in++;
                    else if (pass[j].contains("-")) out++;
                }
                total_pass = total_pass + in - out;
                System.out.println("STOP :" + (i + 1) + " " + total_pass);
                if (total_pass <= Math.ceil(((double) capacity / 4))) {
                    if (pass_in) {
                        pass_fare += fare_1;
                        pass_in = false;
                        System.out.println("fare_1");
                    }
                } else if (total_pass > Math.ceil(((double) capacity / 4)) && total_pass <= Math.ceil(((double) capacity / 2))) {
                    if (pass_in) {
                        pass_fare += fare_2;
                        pass_in = false;
                        System.out.println("fare_2");
                    }
                }
                else if (total_pass > Math.ceil(((double) capacity / 2))) {
                    if (pass_in) {
                        pass_fare += fare_3;
                        pass_in = false;
                        System.out.println("fare_3");
                    }
                }
            }
            outstring = "Passenger "+q_pass_id+" spent a total fare of "+pass_fare;
        } else if(query.split(",")[0].equals("4")){
            ArrayList<Count> count = new ArrayList<Count>();
            int q_pass_id = Integer.parseInt(query.split(",")[1].trim());
            passangers.clear();
            String pass[];
            int pass_id,sum = 0;
            for(int i=0;i<stops;i++){
                String list =listOfInputStrings.get(i);
                pass = list.split(" ");
                for(int j=0;j<pass.length;j++){
                    if(pass[j].contains("+")){
                        count.add(new Count(Integer.parseInt(pass[j].substring(1))));
                    }
                }
            }
            for(int i=0;i<count.size();i++){
                if(count.get(i).getId() == q_pass_id){
                    sum++;
                }
            }
            outstring = "Passenger "+q_pass_id+ " has got on the bus for "+sum+ " times";
        }
        else  if (query.split(",")[0].equals("5")){
            int q_pass_id = Integer.parseInt(query.split(",")[1].trim());
            System.out.println(q_pass_id);
            String pass[];
            int pass_id,sum = 0;
            for(int i=0;i<stops;i++){
                String list = listOfInputStrings.get(i);
                pass = list.split(" ");
                for (int j=0;j<pass.length;j++){
                    if(pass[j].contains(String.valueOf(q_pass_id))){
                        sum++;
                    }
                }
            }
            System.out.println(sum);
            if(sum%2 == 0){
                outstring = "Passenger "+ q_pass_id+" was not inside the bus at the end of the trip";
            }
            else {
                outstring = "Passenger "+q_pass_id+" was inside the bus at the end of the trip";
            }
        }
        return outstring;
    }
}


package com.fresco;
public class Count {
    int id;

    public Count() {
    }

    public Count(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

10. Working with MultiThreading



import java.util.Scanner;

//Write your code here
class Task1 extends Thread {
    public static int a;
    public static int beg;
    Thread taskThread1;
    private String guruname;

    Task1() {

    }

    Task1(String name) {
        guruname = name;
    }

    @Override
    public void run() {
        for (int i = beg; i < a; i++) {
            try {
                Solution.threadArray[i] = i;
            } catch (Exception e) {

            }
        }
        Task3 task3 = new Task3();
        Thread task3Thread = new Thread(task3);
        try {
            task3Thread.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Task2 extends Thread{
    public static int a;
    public static int beg;
    Thread taskThread2;
    private String guruname;

    Task2() {

    }

    Task2(String name) {
        guruname = name;
    }

    @Override
    public void run() {
        for (int i = beg; i < 300; i++) {
            try {
                Solution.threadArray[i] = i;
            } catch (Exception e) {

            }
        }
        beg= beg-1;
        Task3 task3 = new Task3();
        Thread task3Thread = new Thread(task3);
        try {
            task3Thread.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Task3 extends Thread{
    public static int a;
    public static int beg;
    Thread taskThread3;
    private String guruname;

    Task3() {
    }

    Task3(String name) {
        guruname = name;
    }

    @Override
    public void run() {
        for (int i = beg; i < a; i++) {
            try {
                Solution.threadArray[i] = i;
            } catch (Exception e) {
            }
        }
    }
}


public class Solution {
        public static final int[] threadArray = new int[300];
        public static volatile String i = 0+"";
    public boolean test() throws InterruptedException
    {
        Task1 task1 = new Task1();
        Task2 task2 = new Task2();
        Task3 task3 = new Task3();
        Thread task2Thread = new Thread(task2);
        Thread task3Thread = new Thread(task3);
        task1.start();
        task2Thread.start();
        task1.join();
        task2Thread.join();
        task3Thread.start();
        int first = Task1.a+Task2.a;
        int containsSecondThread = Task1.a;
        String oneAndTwo = "";
        String sizeOfTask1 = "";
        for(int i=0;i<first;i++)
        {
            oneAndTwo += threadArray[i]+" ";
        }
        for(int i=0;i<containsSecondThread;i++)
        {
            sizeOfTask1 += threadArray[i]+" ";
        }
        int begOfTask3 = Task3.beg;
        String checkingString = "";
        for(int i=begOfTask3;i<threadArray.length;i++)
        {
            checkingString += i + " ";
        }
        String task3String = "";
        for(int j = begOfTask3;j<threadArray.length;j++)
        {
            task3String += threadArray[j]+" ";
        }
        if((!oneAndTwo.contains(begOfTask3+"") && sizeOfTask1.contains(Task2.beg+"")) && task3String.equals(checkingString))
        {
            return true;
        }
        return false;
    }
    public static void main(String[] args) throws InterruptedException 
    {
        Scanner sc= new Scanner(System.in);
            Solution solution = new Solution();
            int one = sc.nextInt();
            Task1.a = one;
            Task1.beg = 0;
            int two = sc.nextInt();
            Task2.a = two;
            Task2.beg = one;
            int three = sc.nextInt();
            Task3.a = three;
            Task3.beg = one+two;
            System.out.print(solution.test());
    }
}

11. Tree Map



package com.fresco;

import java.util.*;
import java.util.Map;
import java.util.TreeMap;

public class TreemapHandson {
    public TreeMap<Integer,String> createPlayerPositionMap(String cricketDataset)
    {
        TreeMap<Integer,String> playerPositionMap = new TreeMap<Integer,String>();
        String[] playerSet = cricketDataset.split("\\|");
        for(String player: playerSet){
            String[] playerDetails = player.split(",");
            playerPositionMap.put(Integer.parseInt(playerDetails[0].toString()), playerDetails[1]);
        }
        return playerPositionMap;
    }
    public TreeMap<String,Integer> createPlayerScoreMap(String cricketDataset)
    {
        TreeMap<String,Integer> playerScoreMap = new TreeMap<String,Integer>();
        String[] playerSet = cricketDataset.split("\\|");
        for(String player: playerSet){
            String[] playerDetails = player.split(",");
            playerScoreMap.put(playerDetails[1],Integer.parseInt(playerDetails[2].toString()));
        }
        return playerScoreMap;
    }
    public TreeMap<String,Integer> createMatchesMap(String cricketDataset)
    {
        TreeMap<String,Integer> nameWithNumberOfMatchesMap = new TreeMap<>();
        TreeMap<String,Integer> nameWithTotalScore = new TreeMap<>();
        TreeMap<String,Integer> nameWithAverageScore = new TreeMap<>();
        String[] playerDetailsSet = cricketDataset.split("\\n");
        String joinedPlayerSet = String.join("|",playerDetailsSet);
        String[] playerSet = joinedPlayerSet.split("\\|");
        for(String player: playerSet){
            String[] playerDetails = player.split(",");
            if(Integer.parseInt(playerDetails[0]) == 1){
                if(nameWithNumberOfMatchesMap.size() == 0 && nameWithTotalScore.size() == 0){
                    nameWithNumberOfMatchesMap.put(playerDetails[1],1);
                    nameWithTotalScore.put(playerDetails[1],Integer.parseInt(playerDetails[2]));
                }
                else {
                    if(nameWithNumberOfMatchesMap.get(playerDetails[1])!=null)
                        nameWithNumberOfMatchesMap.put(playerDetails[1],nameWithNumberOfMatchesMap.get(playerDetails[1])+1);
                    else
                        nameWithNumberOfMatchesMap.put(playerDetails[1],1);
                    if(nameWithTotalScore.get(playerDetails[1])!=null){
                        nameWithTotalScore.put(playerDetails[1],nameWithTotalScore.get(playerDetails[1])+Integer.parseInt(playerDetails[2]));
                    } else {
                        nameWithTotalScore.put(playerDetails[1],Integer.parseInt(playerDetails[2]));
                    }
                }
            }
        }
        for(Map.Entry<String,Integer> positionEntry: nameWithTotalScore.entrySet()){
            Integer averageScore = positionEntry.getValue() / nameWithNumberOfMatchesMap.get(positionEntry.getKey());
            nameWithAverageScore.put(positionEntry.getKey(),averageScore);
        }
        return nameWithAverageScore;
    }
    public String getQuery(String cricketDataset,String query)
    {
        String result = "";
        String[] queryType = query.split(" ");
        if(queryType.length == 3){
            Integer firstPosition = Integer.parseInt(queryType[1]);
            Integer endPosition = Integer.parseInt(queryType[2]);
            TreeMap<Integer,String> playerPositionMap = this.createPlayerPositionMap(cricketDataset);
            for(Map.Entry<Integer,String> entry: playerPositionMap.entrySet()){
                if(entry.getKey() >= firstPosition && entry.getKey() <= endPosition)
                    result = result + entry.getKey().toString()+ " "+entry.getValue()+"\n";
                }
            }
            else if(queryType.length == 2){
                TreeMap<Integer,String> resultMap = new TreeMap<>();
                Integer thresholdScore = Integer.parseInt(queryType[1]);
                TreeMap<String,Integer> playerScoreMap = this.createPlayerScoreMap(cricketDataset);
                TreeMap<Integer,String> playerPositionMap = this.createPlayerPositionMap(cricketDataset);
                Integer position = 0;
                for(Map.Entry<String,Integer> entry: playerScoreMap.entrySet()) {
                    if(entry.getValue() > thresholdScore) {
                        for(Map.Entry<Integer,String> positionEntry: playerPositionMap.entrySet()) {
                            if(positionEntry.getValue().equals(entry.getKey())) {
                                position = positionEntry.getKey();
                            }
                        }
                        resultMap.put(position, entry.getKey());
                    }
                }
                for (Map.Entry<Integer,String> resultEntry: resultMap.entrySet()) {
                    result = result + resultEntry.getKey().toString() + " "+resultEntry.getValue() + "\n";
                }
            }
            else if(queryType.length == 1) {
                TreeMap<String,Integer> nameWithAverageScore = this.createMatchesMap(cricketDataset);
                Map.Entry<String,Integer> maxEntry = null;
                for(Map.Entry<String,Integer> entry: nameWithAverageScore.entrySet()) {
                    if(maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) {
                        maxEntry = entry;
                    }
                }
                result = "The Efficient Opener is "+ maxEntry.getKey();
            }
        return result;

    }
}

12. Generics



1.StudentJava.class


package com.fresco;

public class StudentClass {
    public String getQuery(String studentData,String query){
        int type;
        String res="";
        type = Integer.parseInt(query.split(",")[0]);
        String a[] = studentData.split(" ");
        if(type == 1){
            StudentList<String> list = new StudentList<>();
            for (int i=0;i<a.length;i++){
                list.addElement(a[i]);
            }
            String query_data = query.split(",")[1];
            res = list.beginsWith(query_data);
        } else if(type == 2){
            StudentList<String> list = new StudentList<String>();
            for(int i=0;i<a.length;i++){
                list.addElement(a[i]);
            }
            String query_data = query.split(",")[2];
            String blood_data = query.split(",")[1];
            res = list.bloodGroupOf(blood_data,query_data);
        } else if(type == 3){
            StudentList<Integer> list = new StudentList<>();
            for(int i=0;i<a.length;i++){
                list.addElement(Integer.parseInt(a[i]));
            }
            int query_data = Integer.parseInt(query.split(",")[1]);
            res = list.thresholdScore(query_data);
        } else if(query.equals("4")){
            ScoreList<Double> list = new ScoreList<>();
            for(int i=0;i<a.length;i++){
                list.addElement(Double.parseDouble(a[i]));
            }
            res = list.averageValues(a.length);
        }
        else if(query.equals("5")){
            ScoreList<Double> list = new ScoreList<>();
            for(int i=0;i<a.length;i++){
                list.addElement(Double.parseDouble(a[i]));
            }
            res = list.averageValues(a.length);
        }
        return res;
    }

}

2. StudentList.java


package com.fresco;


import java.util.ArrayList;


public class StudentList<T> {
    ArrayList<T> students = new ArrayList<T>();
    public void addElement(T t){
        students.add(t);
    }
    public void removeElement(T t){
        students.remove(t);
    }
    public void getElement(int i){
        students.get(i);
    }
    public String beginsWith(String query){
        String res = "";
        for(T student:students){
            if(student instanceof String){
                if((student.toString().toLowerCase()).startsWith(query.toLowerCase())) {
                        res = res + student.toString()+"\n";
                    }
                }
            }
        return res;
        }
        public String bloodGroupOf(String blood_data,String query) {
            String res = "";
            String blood_arr[] = blood_data.split(" ");
            for(int i=0;i<blood_arr.length;i++) {
                if(blood_arr[i].equals(query)) {
                    res = res.concat(students.get(i).toString().concat("\n"));
                }
            }
            return res;
        }
        public String thresholdScore(int marks) {
            int count = 0;
            for(T student: students) {
                if((Integer) student >= marks) {
                    count++;
                }
            }
            return ""+count+" students scored "+marks+" above";
        }
    }


3. ScoreList.java


package com.fresco;

import java.util.ArrayList;

public class ScoreList<T> {
    ArrayList<T> scores = new ArrayList<T>();
    public void addElement(T t){
        scores.add(t);
    }
    public void removeElement(T t){
        scores.remove(t);
    }
    public void getElement(int i){
        scores.get(i);
    }
    public String averageValues(int size){
        double sum=0.0;
        double avg = 0.0;
        for(T scor:scores){
            sum += (Double) scor;
        }
        avg = (double) sum/size;
        return String.format("%.2f",avg);
    }
}

13. File Operation:- 


import java.io.*;
import java.util.Random;
import java.util.Scanner;

// Write your code below.
//
class EncryptDecryptFile {
    public void writeDecryptionFile(String message) throws IOException{
        String decryptFilename = Solution.filepath + "DecryptionFile.txt";
        BufferedWriter writer = new BufferedWriter(new FileWriter(decryptFilename));
        writer.write(message);
        writer.close();
    }
    public String readEncryptionFile() throws IOException {
        String encryptFilename = Solution.filepath +"EncryptionFile.txt";
        BufferedReader reader = new BufferedReader(new FileReader(encryptFilename));
        String messageFromFile = reader.readLine();
        reader.close();
        return messageFromFile;
    }
}

public class Solution {
    public static String filepath = System.getenv("OUTPUT_PATH").substring(0, System.getenv("OUTPUT_PATH").lastIndexOf("\\") + 1);

    private static String generateString()
    {
        char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
        StringBuilder generatedString = new StringBuilder(20);
        Random random = new Random();
        for (int i = 0; i < 40; i++) {
            char c = chars[random.nextInt(chars.length)];
            generatedString.append(c);
        }
        return generatedString.toString();
    }

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        String message = sc.nextLine();

        try{
            EncryptDecryptFile f = new EncryptDecryptFile ();

            String encryptFilename = Solution.filepath + "EncryptionFile.txt";
            String generatedString = generateString();
            BufferedWriter writer = new BufferedWriter(new FileWriter(encryptFilename));
            writer.write(generatedString);
            writer.close();

            if(f.readEncryptionFile().equals(generatedString))
            {
                f.writeDecryptionFile(message);

                String decryptFilename = Solution.filepath + "DecryptionFile.txt";
                BufferedReader reader = new BufferedReader(new FileReader(decryptFilename));
                String messageFromFile = reader.readLine();
                reader.close();

                System.out.println(messageFromFile);
            }
        }
        catch (Exception ex)
        {
            System.out.println(ex.getMessage());
        }

    }

}

14. Filter Out the Narcissistic Numbers (Lambda Streams):- 



package com.fresco;
import java.util.*;

import java.util.stream.Collectors;

public class LambdaFn {

    long countDigit(long n){

      if(n==0)

      return 0;

      return 1+countDigit(n/10);

    }

    boolean check(long n){

      long l=countDigit(n);

      long dup=n;

      long sum=0;

      while(dup>0){

        sum+=Math.pow(dup%10,l);

        dup/=10;

      }

      return(n==sum);

    }

    public List<Long> functionalProgramming(List<String> listOfIntegers)

    {

        //Write your code here

        List<Long> outputList = listOfIntegers.stream()

         .map(s->Long.parseLong(s))

         .filter(c->check(c))

         .collect(Collectors.toList());

        return outputList;
    }
}

15. Reference Methods



import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;



class CipherDecipher{
    
    private String swapCase(String str){
         char[] ch = str.toCharArray();
         for(int i=0;i<str.length();i++){
             if(ch[i]<= 90 && ch[i] >= 65)
                ch[i] += 32;
            else if(ch[i] <=122 && ch[i] >= 97)
                ch[i] -= 32;
         }
         return String.valueOf(ch);
     }
     private String replaceWithAscii(String str){
         StringBuilder sb = new StringBuilder();
         int n = str.length();
         for(int i=0;i<n;i++){
             if(i%2==1)
                sb.append((int)str.charAt(i));
             else 
                sb.append(str.charAt(i));
         }
            return sb.toString();
         
     }
     private String replaceWithChar(String str){
         StringBuilder sb = new StringBuilder();
         int n = str.length();
         for(int i=0;i<n-1;i++){
             char c = str.charAt(i);
             if(Character.isDigit(c)){
                 int ch = c - '0';
                 while(i<n-2 && Character.isDigit(str.charAt(++i))){
                     ch *= 10;
                     ch += str.charAt(i) - '0';
                 }
                 c = (char)ch;
                 sb.append(c);
                 if(!Character.isDigit(str.charAt(i)))
                 sb.append(str.charAt(i));
                 continue;
             }
             sb.append(c);
         }
         return sb.toString();
     }
    
    
    public String ciphering(String normal){
        normal = swapCase(normal);
        normal = (new StringBuilder(normal)).reverse().toString();
        normal = normal.replace(" ", "*");
        normal = replaceWithAscii(normal);
        normal = normal + "3";
        return normal;
    }
    public String deciphering(String ciphered){
       ciphered = replaceWithChar(ciphered);
       ciphered = ciphered.replaceAll("\\*"," ");
       ciphered = (new StringBuilder(ciphered)).reverse().toString();
       ciphered = swapCase(ciphered);
       return ciphered;
    }
}

public class Solution {
    
    public static void main(String[] args){
        Scanner readInput = new Scanner(System.in);
        String normal=readInput.nextLine();
        String ciphered=readInput.nextLine();
        
        CipherDecipher cipherOrDecipher = new CipherDecipher();
        System.out.println(cipherOrDecipher.ciphering(normal));
        System.out.println(cipherOrDecipher.deciphering(ciphered));
        
        

    }
    
}

 


**************************************************
Credit for the above notes, goes to the respective owners. 

If you have any queries, please feel free to ask on the comment section.
If you want MCQs and Hands-On solutions for any courses, Please feel free to ask on the comment section too.

Please share and support our page!


Post a Comment

2Comments
Post a Comment

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !

Join Telegram Channel

Join MNCAnswers To Get Instant Updates

Join Telegram Channel