×

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

How to run java program in ubuntu

To run the java programming in ubuntu, we need to follow several steps: Let's see the process. Step1: Install the Java compiler or JDK to the system. To run the java program, we...

3 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

6 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 minutes read.

Java Math floor() Method

The floor() method of Math class returns the largest double value that is equal to a mathematical integer and is less than or equal to the argument. Syntax: public static double floor(double...

2 minutes read.

How to Read XML Files in Java?

Introduction Today, we are going to learn about how to read XML files in java. Before, reading the XML Files let us learn about XML. XML Files The full form of XML is...

8 minutes read.

List of Constants in Java

In this tutorial, we are going to deal with constants available in Java.Every programming language has its constants. Similarly, Javaalso has got constants of its own. In this tutorial, we will...

6 minutes read.

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

Java HashMap

Java HashMap extends AbstractMap and implements Map interface. It is the collection of multiple entries where an entry consists of key and value pair. The HashMap can contain only one...

7 minutes read.

How to check data type in Java

In this section, we will learn about the methodology to verify the data type in Java. There are mainly two methods in java called as getClass() and getName(). They are...

3 minutes read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

3 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Java Math copySign() Method

The copySign() method of Math class returns the first floating-point argument with the sign of the second argument. Syntax: public static float copySign(float magnitude, float sign)public static double copySign(double magnitude, double sign) Parameters: The...

1 minute read.