×

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

Types of Logical Operators in Java

In this tutorial, we are going to study logical operators. A logical operator is an operator that accomplishes a logical operation that is to connect two or more operations. These...

5 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 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 Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

How to find the length of an Array in Java

Arrays: An array is a sort of container object that stores constant quantities of values of a single type in one memory area. A finite number of items must all be...

3 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.

Read JSON file in Java

 To know about reading a JSON file in Java first we must know about the JSON file. JSON: JSON is “JavaScript Object Notation”. The JSON is the simple format for storing and...

3 minutes read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

What are Array strings in Java?

In normal programming, An array is a group and a collection of identical forms of data that are stored in a sequential memory region and may be accessed using their...

4 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.