×

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a start time (si) and completion time (fi). If a person can only work on one activity at a time, the challenge is to choose the most tasks that a single human or machine can complete.

Non-conflicting activities:

Assume that there are N multiple tasks and that each activity has a launch date (s) and a deadline (f). If s1>=f2 or s2 >=f1, two actions, 1 and 2, are said to have been non-conflicting. 

Greedy Approach

The greedy decision is to consistently choose the next action whose start time is greater than or equal to the completion time of the preceding activity and whose finish time is the earliest available activity. The activities can be arranged according to their completion time such that the subsequent action is always thought of as the activity with the earliest completion time.

Algorithm

  • Sort all the activities through the time activity ends.
  • Please choose the first activity, record the time it ends, and label it current_endtime.
  • Continue by repeating the remaining tasks. current activity for each
  • if current_activitytime >current_endtime of the start time.
  • select current_activitytime  parameter.
  • Update current_endtime to reflect current_activitytime end time.
  • If not, delete the current activity.

Filename: ActivitySelectionProblem.java

//Java program that solves the problem of activity selection. 
//The following implementation of the activities are arranged in order of //finish time.
import java.io.*;
import java.lang.*;
import java.util.*;
class ActivitySelectionProblem{
	//Displays the activities that can be done at a single time
	//By the single person
	public static void printMaxActivities(int si[], int fi[],int num)
	{
		int i, j;
		System.out.println("The activities selected are:");
		// the initial activity is always selected as it is initial
		i = 0;
		System.out.print(i + " ");
		// The other activities are
		for (j = 1; j < num; j++) {
			// The activity should be chosen if its start time is greater than or equal to the previously chosen activity.
			if (si[j] >= fi[i]) 
                              {
				System.out.print(j + " ");
				i = j;
			}
		}
	// Main section of the program
	public static void main(String[] args)
	{
		int si[] = { 3, 3, 0, 6, 7, 5 };
		int fi[] = { 2, 5, 6, 9, 8, 2 };
		int num = si.length;
		// Function call
		printMaxActivities(si, fi, num);
	}
}

Output

The activities selected are are:0 1 3

Time complexity: O(n)

Space complexity is: O(1)

Implementation of the unsorted activities

For the implementation of unsorted activities, first, we need to sort the activities based on the ending time of each of the activities.

After that, the greedy algorithm is applied to solve the problem.

Example:

Input:

Array[]={{1,9},{2,8},{4,8},{1,6},{0,5},{6,7}}

The given array Array is sorted according to the completion time

Sorted Array={{0,5},{1,6},{6,7},{2,8},{4,8},{1,9}}

Output:

{(0, 5), (6, 7)}

Program for unsorted activities

Filename: ActivitySelection.java

//Java program for activity selection when activities are not sorted
import java.io.*;
import java.util.*;
// the job having the initial and final time
class ActivityProblem{
	int initial, end;
	// The ActivityProblem constructor
	public ActivityProblem(int initial,int end)
	{
		this.initial =initial;
		this.end = end;
	}
}
//comparing the activities
class Compares {
	// sorting the activities
	static void compares(ActivityProblem array[], int num)
	{
		Arrays.sort(array, new Comparator<ActivityProblem>() {
			@Override
			public int compare(ActivityProblem st1, ActivityProblem st2)
			{
				return st1.end - st2.end;
			}
		});
	}
}


// Main class
class ActivitySelection {
	// Displays the possibilities
	static void printMaxActivities(ActivityProblem array[], int num)
	{
		//the jobs are according to the end time
		Compares object = new Compares();
		object.compares(array, num);
		System.out.println("The selected activities");
		// The initial activity is selected first
		int i = 0;
		System.out.print("(" + array[i].initial + ", "+ array[i].end + ")");


		// iterating the other activities
		for (int j = 1; j < num; j++) {
			//The activity should be chosen if its start time is greater //than or equal to the previously chosen //in the list.
			if (array[j].initial >= array[i].end) {
				System.out.print(", (" + array[j].initial + ", "
								+ array[j].end + ")");
				i = j;
			}
		}
	}
	//Main section
	public static void main(String[] args)
	{
		int num = 6;
		ActivityProblem array[] = new ActivityProblem[num];
		array[0] = new ActivityProblem(5, 7);
		array[1] = new ActivityProblem(1, 6);
		array[2] = new ActivityProblem(8, 5);
		array[3] = new ActivityProblem(1, 0);
		array[4] = new ActivityProblem(9, 9);
		array[5] = new ActivityProblem(7, 1);
		// function calling
		printMaxActivities(array, num);
	}
}

Output

The selected activities(1, 0), (7, 1), (8, 5), (5, 7), (9, 9)

Time Complexity=O(N Log N)

Space Complexity=O(1)

Using Priority Queue

To solve that problem, follow the instructions given:

  • Push the activities onto the priority queue (Min-Heap).
  • Place the first activity in the priority at the beginning of the response vector. Set the parameters to start and end to the first activity's beginning and completion times, respectively.
  • Perform the following when the priority is not zero:
  • Check the first spot in the priority line.
  • Push this activity into the response vector if its start time is larger than or equal to the end time of the previous one.
  • Aside from that, disregard it.
  • Print the selected actions that are saved in the response vector.

Filename: ActivitySelection.java

// Java program for activity selection
//importing required packages
import java.io.*;
import java.lang.*;
import java.util.*;
class ActivitySelection{
	// the pairs of the class
	static class Pairs {
		int firsts;
		int seconds;
		Pairs(int firsts, int seconds)
		{
			this.firsts = firsts;
			this.seconds = seconds;
		}
	}
	static void SelectActivity(int st[], int ft[])
	{
		// Vector for storing the result
		ArrayList<Pairs> anss = new ArrayList<>();
		// sorting of the pairs
		PriorityQueue<Pairs> pair = new PriorityQueue<>((p1, p2) -> p1.firsts - p2.firsts);
		for (int i = 0; i < st.length; i++) {
			// the elements are added to the queue
			pair.add(new Pairs(ft[i],st[i]));
		}
		Pairs ite = pair.poll();
		int starts = ite.seconds;
		int ends = ite.firsts;
		anss.add(new Pairs(starts, ends));


		while (!pair.isEmpty()) {
			Pairs itre = pair.poll();
			if (itre.seconds >= ends) {
				starts = itre.seconds;
				ends = itre.firsts;
				anss.add(new Pairs(starts, ends));
			}
		}
		System.out.println("The activities which are selected \n");
		for (Pairs itre : anss) {
			System.out.println("The Activity began at " + itre.firsts+ " and it completed at " + itre.seconds);
		}
	}
	// Main section
	public static void main(String[] args)
	{


		int st[] = { 3, 3, 0, 1, 2, 8 };
		int ft[] = { 4, 0, 6, 2, 1, 4 };
		// Function call
		SelectActivity(st, ft);
	}
}

Output

The activities which are selected 
The Activity began at 3 and it completed at 0
The Activity began at 2 and it completed at 1
The Activity began at 1 and it completed at 2
The Activity began at 3 and it completed at 4
The Activity began at 8 and it completed at 4

Time Complexity=O(N *log N)

Space Complexity=O(N)


Related Topics

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

TreeSet in Java

Java TreeSet with Example Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not...

8 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Zigzag Traversal of Binary Tree in Java

In this article, you will be acknowledged about the zigzag traversal of binary tree in java and the approaches or ways in which the zigzag traversal can be done. Zigzag Traversal A...

10 minutes read.

How to Reduce Time Complexity in Java

What is time complexity?  The time complexity in java is given as the amount of time a program requires to run or execute it Calculating the time complexity of the program The time...

4 minutes read.

Collections in Java

Collection framework is one of Java's most powerful subsystems. It is a set of classes and interfaces that is all-the-rage technology for superintending objects and a group of objects. In...

6 minutes read.

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Java String Methods

Java String Methods Java String class is the most important class of the java.lang package. It is used to handle the String related operations. It contains a lot of built-in Java...

2 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Java URL Class with Example

Java URL Uniform Resource Locator To find any resource on the internet, you need to have an address of it. The URL and IP addresses are the pointers used for this purpose....

12 minutes read.

Sealed Class in Java

What is a Sealed Class in Java? In programming, the two main issues that must be taken into account when creating an application are security and control flow. The use of...

5 minutes read.