Skip to content

Instantly share code, notes, and snippets.

@Danushka96
Last active May 8, 2023 15:02
Show Gist options
  • Save Danushka96/86002300c93db71fb40ee507da362dab to your computer and use it in GitHub Desktop.
Save Danushka96/86002300c93db71fb40ee507da362dab to your computer and use it in GitHub Desktop.
package com.cloudimpl.beep;
/**
* @author danushka
* 2023-05-08
*/
import java.util.*;
import java.util.stream.Collectors;
class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of array A: ");
int n1 = scanner.nextInt();
ArrayList<Integer> arr1 = new ArrayList<>();
System.out.println("Enter the elements of array A:");
for (int i = 0; i < n1; i++) {
arr1.add(i, scanner.nextInt());
}
System.out.print("Enter the size of array B: ");
int n2 = scanner.nextInt();
ArrayList<Integer> arr2 = new ArrayList<>();
System.out.println();
System.out.println("Enter the elements of array B:");
for (int i = 0; i < n2; i++) {
arr2.add(i, scanner.nextInt());
}
System.out.print("[");
for (int i = 0; i < arr1.size(); i++) {
System.out.print(arr1.get(i) + " ");
}
System.out.println("]");
System.out.print("[");
for (int i = 0; i < arr2.size(); i++) {
System.out.print(arr2.get(i) + " ");
}
System.out.println("]");
int result = solution(arr1, arr2);
System.out.println("Result = " + result);
}
public static int solution(List<Integer> a, List<Integer> b) {
Set<String> result = new HashSet<>();
result.add("[" + a.stream().map(String::valueOf).collect(Collectors.joining(", ")) + "]");
result.add("[" + b.stream().map(String::valueOf).collect(Collectors.joining(", ")) + "]");
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < b.size(); j++) {
List<String> nonDecreasingArray = getCombination(a, b, i, j);
result.addAll(nonDecreasingArray);
}
}
return result.size() - 2;
}
private static List<String> getCombination(List<Integer> a, List<Integer> b, int i, int j) {
List<Integer> copyOfA = new ArrayList<>(a);
List<Integer> copyOfB = new ArrayList<>(b);
copyOfA.set(i, b.get(j));
copyOfB.set(j, a.get(i));
if (isNonDecreasingArray(copyOfA) && isNonDecreasingArray(copyOfB)) {
return List.of(copyOfA.toString(), copyOfB.toString());
} else {
return Collections.emptyList();
}
}
private static boolean isNonDecreasingArray(List<Integer> array) {
for (int i = 0; i < array.size() - 1; i++) {
if (array.get(i) > array.get(i + 1)) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment