×

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist between the sum of the numbers included in the initial subset and, thus, the following subset when the supplied set is subdivided. The length of each collection must equal n / 2 if n is an even number. The size of one group must be n / 2, and the length of the other set must be (n + 1) / 2 if somehow the value of n is odd. Let's break it down with the aid of some examples.

Problem:

  • An array of n numerals is supplied to you.
  • You must split up these n numerals into two subgroups so that the difference between the two subsets' sums is as small as possible.
  • Both sets will have precisely n/2 elements if n is even. One set will have (n-1)/2, and the second set will include (n+1)/2 pieces if n is an odd number.
  • If the division is not feasible, print "-1."
  • By using the input array [a, b, c, d] to clarify this query,

Example 1:

S is a set of 10 elements that has the following values: 3, 5, 4, 3, 1, 100, 54, 89, 20, 23.

Undoubtedly, 10 is an even integer. As a result, the two subsets we will extract from the supplied set must each be of average size (10 / 2 = 5). They are these two subsets:

S1 = {4, 1, 100, 20, 23} as well as S2 = {-3, 5, 3, 54, 89}

The subset S1 adds up to 4 + 1 + 100 + 20 + 23 which equals 148.

The subset S2 has the following sum: - 3 + 5 + 3 + 54 + 89 = 148.

As a result, we can see that the summation of subsets S1 and S2 are equal. As a result, the minimum difference between the two groups is 148 - 148 = 0.

Example 2:

The set S has the following values: -34, 23, 98, 45, 12, 4, 4, -99, -1, 189, 0, and so forth.

Undoubtedly, 11 is an odd integer. This means that the two subsets we will extract from the supplied set must have sizes of 5 (10 / 2 = 5) and 6 (10 / 5 + 1 = 6). They are these two subsets:

S1 = {45, -34, 12, 98, -1} as well as S2 = {23, 4, 4, -99, 189, 0}

Subset S1 adds up to 45 -34 + 12 + 98 -1 = 120.

The subset S2 is equal to 23 + 4 + 4 -99 + 189 + 0 = 121 as a whole.

As a result, we can see that the summation of subsets S1 and S2 are equal. Thus, 121 – 120 = 1 represents the difference between the two subsets. We are unable to get a difference of less than one if we create any additional pair of equal-sized subsets. The most negligible difference that can exist for the specific set is 1, thus.

Approach

The following solution searches for every single half-size subgroup conceivable. If the first subset is half the size, the remaining components form a second subset. The current set is created with no elements and is then filled. Including an entity in the current set is one option, and excluding an item from the current batch is the other. We fill all subsets by taking these two alternatives into account.

The next approach attempts each potential half-size subset. The remaining items make up the other subset if just one subgroup of half the size is generated. We start off with an empty set and piece it together one by one. Every element has two potential outcomes: either a part of the present set or a portion of the leftover elements (remaining subgroups). We take into account both scenarios for every constituent. We determine whether this solution is superior to the best one up until the size of the current set reaches n/2. If so, we will revise the ideal solution.

Implementation

Check out how the abovementioned strategy is used to solve the tug-of-war problem.

Tugofwar.java

// Importing the required packages 
import java.io.*;
public class Tugofwar  
{  
public int min;  
  
// a utility function that repeatedly calls itself to try 
// every potential resolution 
void toutil(int arr[], int s, boolean ele[],  
int selected, boolean ans[],  
int add, int presum, int pos)  
{  
// determining if the position is approaching the bounds  
if (pos == s)  
{  
return;  
}  
  
// ensuring that the remaining element counts are at least
// as many as the components needed to build the solution  
if ((s / 2 - selected) > (s - pos))  
{  
return;  
}  
  
// Think about the scenarios where the present component 
// isn't used in the solution. 
toutil(arr, s, ele,   
selected, ans,   
add, presum, pos + 1);  
  
// adding the current element to our current solution 
// in the following steps.
selected = selected + 1;  
presum = presum + arr[pos];  
ele[pos] = true;  
  
//verifying if we have successfully made the solution or not 
if (selected == s / 2)  
{  
// determining whether the developed solution is superior 
// to the best one thus far 
if (Math.abs(add / 2 - presum) < min)  
{  
min = Math.abs(add / 2 - presum);  
for (int j = 0; j < s; j++)  
{  
ans[j] = ele[j];  
}  
}  
}  
else  
{  
// the current component of the solution is included in the subsequent 
// recursive call.  
toutil(arr, s, ele,  
selected,  
ans, add, presum,  
pos + 1);  
}  
  
// In order to return to the 
// user of this method, the current 
// element is removed. 
ele[pos] = false;  
}    
void tow(int arr[])  
{  
int s = arr.length;  
  
// the boolean integer that contains whether an element 
// is included in the current set or not. The quantity
// that is automatically subtracted from the other set 
boolean[] ele = new boolean[s];  
  
// The inclusion/exclusion array for  
// final solution  
boolean[] ans = new boolean[s];  
  
min = Integer.MAX_VALUE;  
  
int add = 0;  
for (int j = 0; j < s; j++)  
{  
add = add + arr[j];  
ele[j] = ans[j] = false;  
}  
  
// Finding the answer using the recursion
// calling the function toutil recursively.  
toutil(arr, s, ele, 0,  
ans, add, 0, 0);  
  
// Printing the solution 
System.out.print("Elements that make the first subset are : ");  
for (int j = 0; j < s; j++)  
{  
if (ans[j] == true)  
{  
System.out.print(arr[j] + " ");  
}  
}  
  
System.out.print("\n");  
System.out.print("Elements that make the Second subset are : ");  
for (int j = 0; j < s; j++)  
{  
if (ans[j] == false)  
{  
System.out.print(arr[j] + " ");  
}  
}  
}  
  
// Main method starts here
public static void main (String[] args)  
{  
// Making the input array  
int arr[] = new int[]{-34, 23, 98, 45, 12, 4, 4, -99, -1, 189, 0};  
  
// finding the length of the array
int s = arr.length;   
  
// Object creation for the class Tugofwar             
Tugofwar obj = new Tugofwar();  
  
System.out.println("Taken array is as follows : ");  
for(int i = 0; i < s; i++)  
{  
System.out.print(arr[i] + " ");  
}  
  
System.out.println();  
  
// Calling the method tow() using the object    
obj.tow(arr);  
  
// Changing the array taken as input  
arr = new int[]{-3, 5, 4, 3, 1, 100, 54, 89, 20, 23};  
  
// finding the length of the updated array   
s = arr.length;  
  
System.out.println("\n");  
  
System.out.println("Updated array is as follows : ");  
for(int i = 0; i < s; i++)  
{  
System.out.print(arr[i] + " ");  
}  
  
System.out.println();  
  
// Calling the method tow() using the object    
obj.tow(arr);  
}  
}  

Output:

Taken array is as follows :
-34 23 98 45 12 4 4 -99 -1 189 0
Elements that make the First subset are : -34 98 45 12 -1
Elements that make the Second subset are : 23 4 4 -99 189 0


Updated array is as follows :
-3 5 4 3 1 100 54 89 20 23
Elements that make the First subset are : 4 1 100 20 23
Elements that make the Second subset are : -3 5 3 54 89
 

Time Complexity:

The above program has a time complexity of 2n, and wherein n represents the length of the array that is a number of elements.


Related Topics

How to Send SMS in Java with Example

Sending SMS messages in Java is a fairly common task, and there are a number of libraries and APIs available to help you do it. One popular option is to...

2 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

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 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.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

Alien language problem in Java

Given the alphabetic sequence of an alien language, given a sorted dictionary (array of words) for the languages. Example: Words = { "aac", "abc", "aaa" } Output c, a, b Algorithm: (1) Compare two words that...

3 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Java Default Keyword

The Default keyword in java programming language is used as access modifier.If any of the variable or the constructor or the methods or the classes are not assigned with the...

3 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Morris Traversal for Preorder in Java

Without the use of recursion or stacks, we traverse a tree using the Morris algorithm. The linked binary tree is the foundation of the Morris traversal. Preorder Morris Traversal Algorithm The preorder...

3 minutes read.

Java Networking

Networking Networking is a way of communicating the devices. It is made up of various technologies like computers, switches, routers that are interconnected and share data among themselves. The two common network protocols: 1. TCP/IP TCP stands for...

10 minutes read.

Automatic Resource Management

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources. There are two ways of management of resources: The computer program itself...

2 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

Java FileOutputStream

What is FileOutputStream?When we need raw stream data written into a file, we need to look for another option: FileOutputStream. It is used when the file's data is byte-oriented. It comes under...

4 minutes read.