DEV Community

Cover image for TCS Ninja Digital Coding Question
Gourav Kadu
Gourav Kadu

Posted on

TCS Ninja Digital Coding Question

In a computer game, two sets of numbers are flashed on the screen for a few seconds Players need to calculate the sum of the numbers in each of the sets. If the resulting such is odd for either of the two sets, then the players need to identity if swapping any numbers between the two sets would make the resulting sum even in both the sets. The task is to write a code to identify the minimum number of swaps required to ensure that the resulting sum of each of the two sets of numbers is even if there is no possibility of achieving this, then the output t needs to be flagged as -1.

Example 1:

Input:

4-> Value of N

(1,4, 20, 2)-> arr1[] Elements a[0] to a[N-1]. where each input element is separated by a new line.

4-> Value of M

(5,9 , 6 , 3)-> arr2[] Elements a[0] to a[M-1]. where each input element is separated by a new line.

Output: 1

Explanation:

in the Array arr1[i] = (1,4,20,2) Sum1 @ 27 (odd) In the Array arr20]=(5,9,6,3) Sum223 (odd)

Swapping arr1[0] = 1 and arr2[2] = 6 will make the Sum1 and Sum2 even in the Array arr10] (6.4,20,2) Sum1 = 32 (even) In the Array arr2[0]=(5,9,1,3) Sum2 = 18 (even)

As only one swapping is required to make the sums even, the output is 1

Example 2:

4-> Value of N

(3,2,2)-> arr1[] , Elements a[0] to a[N-1], where each input element is separated by a new line.

4 → Value of M

(2,9,6,3)-> arr2[], Elements a[0] to a[M-1], where each input element is separated by a new line.

Output:

0

Explanation:

In the Array Sum1 = 8 (even) In the Array arr2g = (2.9.6.3) Sum2=20 (even) As both Sum1 and Sum2 are even, the output is 0

(indicating no swap is required).

Solution : -

import java.util.*;

public class Template {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
int sum2 = 0;
int arr[]= new int[n];

for(int i = 0; i < n ; i++){
arr[i] = sc.nextInt();
sum += arr[i];
}

int m = sc.nextInt();
int arr2[] = new int[m];

for(int i = 0; i < m ; i++){
arr2[i] = sc.nextInt();
sum2 += arr2[i];
}

if((sum%2 == 0 && sum2%2 == 1)||(sum%2 == 1 && sum2%2 == 0)){
System.out.println("-1");
}


if(sum%2 == 0 && sum2%2 == 0){
System.out.println("0");
}

if(sum%2 == 1 && sum2%2 == 1){
    if(arr[0]%2==0){
     for(int i = 0 ; i < m; i++) {
if(arr2[i]%2!=0) {
int temp = arr[0];
arr[0] = arr2[i];
arr2[i] =temp;
}
}

System.out.println("1");

}

else if(arr[0]%2!=0) {

for(int i = 0 ; i < m; i++) {

if(arr2[i]%2==0) {

int temp = arr[0];

arr[0] = arr2[i];

arr2[i] =temp;

}
}
System.out.println("1");

}
}
sc.close();
}
}

Enter fullscreen mode Exit fullscreen mode
Output_Image_1
Output test case 1
Output_Image_2
Output test case 2
Output_Image_2
Output test case 3

Top comments (0)