Question

Implement a greedy strategy in JAVA which takes in a list of job object ( each...

Implement a greedy strategy in JAVA which takes in a list of job object ( each job object consist of Job id (integer) , startTime (float) and endTime(float)) and outputs a list of non-conflicting jobs according to their start time. (Implement the given method provided in the code).

Example of Input:

id startTime endTime

1 4 7

2 3 5

3 7 9

CODE

import java.util.Scanner;

import java.util.List;

import java.util.ArrayList;

import java.io.InputStream;

public class JobScheduling {

public static final Strategy chosen = Strategy.EARLIEST_START;

/**

* Returns a non-conflicting selection of jobs from the input list,

* chosen according to the earliest starting time strategy, i.e. jobs are

* considered in order of earliest to latest starting time, each

* job is included if and only if it doesn't conflict with previously

* chosen jobs.

*

* @param jobs the jobs which make up the job scheduling instance

* @return a list containing the selected jobs

*/

public static List<Job> byEarliestStart(List<Job> jobs) {

//TODO : implement this method.

return null;

}

public static void main(String[] args) {

List<Job> jobs = loadJobs(System.in);

System.out.println(byEarliestStart(jobs));

}

/**

* Loads a list of jobs from a specified input stream, such as standard input.

* The input is expected to be a newline-separated sequence of jobs, each given

* by a space-separated triplet of numbers, in order: id, startTime, finishTime.

*

* @param stream the input stream from which to read job data

* @return the loaded list of jobs

*/

public static List<Job> loadJobs(InputStream stream) {

Scanner scanner = new Scanner(stream);

List<Job> jobs = new ArrayList<>();

while (scanner.hasNext()) {

int id = scanner.nextInt();

float startTime = scanner.nextFloat();

float finishTime = scanner.nextFloat();

jobs.add(new Job(id, startTime, finishTime));

}

return jobs;

}

public static enum Strategy {

SHORTEST_INTERVAL,

EARLIEST_FINISH,

FEWEST_CONFLICTS,

EARLIEST_START

}

}

public class Job {

private final int id;

private final float startTime;

private final float finishTime;

public Job(int id, float startTime, float finishTime) {

this.id = id;

this.startTime = startTime;

this.finishTime = finishTime;

}

public int getId() {

return id;

}

public float getStartTime() {

return startTime;

}

public float getFinishTime() {

return finishTime;

}

public String toString() {

return "(" + id + ", " + startTime + ", " + finishTime + ")";

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE TO COPY:

import java.io.File;

import java.io.FileNotFoundException;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.Comparator;

import java.util.Scanner;

class Job{

private int id;

private float startTime;

private float endTime;

/**

* @return the id

*/

public int getId() {

return id;

}

/**

* @param id the id to set

*/

public void setId(int id) {

this.id = id;

}

/**

* @return the startTime

*/

public float getStartTime() {

return startTime;

}

/**

* @param startTime the startTime to set

*/

public void setStartTime(float startTime) {

this.startTime = startTime;

}

/**

* @return the endTime

*/

public float getEndTime() {

return endTime;

}

/**

* @param endTime the endTime to set

*/

public void setEndTime(float endTime) {

this.endTime = endTime;

}

public String toString()

{

return id+" "+startTime+" "+endTime;

}

}

public class JobTest {

public static void main(String[] args) throws FileNotFoundException {

File file=new File("inputJobs.txt");

Scanner obj=new Scanner(file);

ArrayList<Job> jobs=new ArrayList<Job>();

while(obj.hasNext())

{

Job job=new Job();

job.setId(obj.nextInt());

job.setStartTime(obj.nextFloat());

job.setEndTime(obj.nextFloat());

jobs.add(job);

}

Comparator<Job> cmp=new Comparator<Job>()

{

public int compare(Job a, Job b)

{

if(a.getEndTime()<b.getEndTime())

return -1;

else if(a.getEndTime()==b.getEndTime())

return 0;

return 1;

}

};

Collections.sort(jobs, cmp);//sort the jobs list using the comparator

int nonConflict=0;

int curJobIndex=0;

ArrayList<Job> nonConflictJobs=new ArrayList<Job>();

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

{

if(i==0)

{

nonConflictJobs.add(jobs.get(i));

nonConflict=1;

continue;

}

if(jobs.get(i).getStartTime()>=jobs.get(curJobIndex).getEndTime())

{

nonConflictJobs.add(jobs.get(i));

nonConflict++;

curJobIndex=i;

}

}

System.out.println("Number of non conflicting jobs: "+nonConflict);

System.out.println("Non conflicting jobs: "+nonConflictJobs.toString());

}

}

PROGRAM SCREENSHOTS:

OUTPUT:

In case of any doubt, please let me know in the comments section. I'll get it resolved :):) Don't forget to give a THUMBS UP! :)

Add a comment
Know the answer?
Add Answer to:
Implement a greedy strategy in JAVA which takes in a list of job object ( each...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • in java coorect this code & screenshoot your output ---------------------------------------------------------------------- public class UNOGame {     /**...

    in java coorect this code & screenshoot your output ---------------------------------------------------------------------- public class UNOGame {     /**      * @param args the command line arguments      */         public static void main(String[] args) {       Scanner input=new Scanner(System.in);          Scanner input2=new Scanner(System.in);                             UNOCard c=new UNOCard ();                UNOCard D=new UNOCard ();                 Queue Q=new Queue();                           listplayer ll=new listplayer();                           System.out.println("Enter Players Name :\n Click STOP To Start Game..");        String Name = input.nextLine();...

  • java  Operating System Scheduler Two scheduling strategies for an operating system scheduler are first come first serve...

    java  Operating System Scheduler Two scheduling strategies for an operating system scheduler are first come first serve (FCFS) and fixed priority pre-emptive scheduling (FPPS). Since queues operate on a first come first serve basis, FCFS is implemented using a queue. Similarly, FPPS is implemented using a priority queue. The operating system scheduler simulation is already provided for you. To use it you simply need to modify the main method to run the simulator using either the LinkedListQueue or the PriorityQueue. Run...

  • pls help me with it. you just need to answer the question in Appointment.Java, There is...

    pls help me with it. you just need to answer the question in Appointment.Java, There is only 1 question u need to answer! Appointment.Java package option1.stage3; import option1.stage1.Doctor; import option1.stage1.Patient; import option1.stage2.TimeSlot; public class Appointment { private Doctor doctor; private Patient patient; private TimeSlot timeSlot; public Doctor getDoctor() { return doctor; } public void setDoctor(Doctor doctor) { this.doctor = doctor; } public Patient getPatient() { return patient; } public void setPatient(Patient patient) { this.patient = patient; } public TimeSlot getTimeSlot()...

  • FOR JAVA: Summary: Create a program that adds students to the class list (see below). The...

    FOR JAVA: Summary: Create a program that adds students to the class list (see below). The solution should be named Roster402_v2.java. Allow the user to control the number of students added to the roster. Ask if the user would like to see their new roster to confirm additions. If yes, then display contents of the file, if no, end the program. ------------------------------------------------------------------------------------- List of student names and IDs for class (this will be your separate text file): Jones, Jim,45 Hicks,...

  • Implement the following in java. 1. An insertAtBeginning(Node newNode) function, that inserts a node at the...

    Implement the following in java. 1. An insertAtBeginning(Node newNode) function, that inserts a node at the beginning(root) of the linked list. 2. A removeFromBeginning() function, that removes the node from the beginning of the linked list and assigns the next element as the new beginning(root). 3. A traverse function, that iterates the list and prints the elements in the linked list. For the insertAtBeginning(Node newNode) function: 1. Check if the root is null. If it is, just assign the new...

  • Java: Hello, can someone please find a way to call my arraylist "list" and linkedhashmap called...

    Java: Hello, can someone please find a way to call my arraylist "list" and linkedhashmap called "jobMap" in my main method instead of calling them in the 2 classes? Also, is there a way to avoid the "Suppress Warning" portion in RoundRobin.java? I haven't been able to find a way for some reason. This is a job scheduling program, so the output should give the same values. To run: javac Main.java, java Main 5jobs.txt . txt file will be provided...

  • Write in Java Implement the parse method and test it by calling with three different strings...

    Write in Java Implement the parse method and test it by calling with three different strings and by printing the results. The Scanner method can be used to read values from strings, files, or System.in. We need to invoke the useDelimiter method to define what symbols can separate, or terminate, the digits of a Fraction. public static Fraction parse(String input) t Scanner s new Scanner(input) useDelimitercTVMitln"); int num s.nextlnt() int denom s.nextlnt); s.close): return new Fraction(num, denom) class Codechef static...

  • this needs to be in Java: use a comparator class which is passed into the sort...

    this needs to be in Java: use a comparator class which is passed into the sort method that is available on the ArrayList. import java.util.Scanner; public class Assign1{ public static void main(String[] args){ Scanner reader = new Scanner (System.in); MyDate todayDate = new MyDate(); int choice = 0; Library library = new Library(); while (choice != 6){ displayMainMenu(); if (reader.hasNextInt()){ choice = reader.nextInt(); switch(choice){ case 1: library.inputResource(reader, todayDate); break; case 2: System.out.println(library.resourcesOverDue(todayDate)); break; case 3: System.out.println(library.toString()); break; case 4: library.deleteResource(reader,...

  • You will implement the following method public static int[] linearSearchExtended(int[][] numbers, int key) { // Implement...

    You will implement the following method public static int[] linearSearchExtended(int[][] numbers, int key) { // Implement this method return new int[] {}; }    There is a utility method provided for you with the following signature. You may use this method to convert a list of integers into an array. public static int[] convertIntegers(List<Integer> integers) Provided code import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Scanner; public class MatrixSearch { // This method converts a list of integers to an array...

  • I need help filling in the the code in the methods add, multiply, and evaluate package...

    I need help filling in the the code in the methods add, multiply, and evaluate package poly; import java.io.IOException; import java.util.Scanner; /** * This class implements evaluate, add and multiply for polynomials. * * * */ public class Polynomial {       /**    * Reads a polynomial from an input stream (file or keyboard). The storage format    * of the polynomial is:    * <pre>    * <coeff> <degree>    * <coeff> <degree>    * ...    *...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT