package org.wesome.dsalgo;
import java.util.Arrays;
class CountPairsWithDifference {
static int[] countPairsWithDifference(int[] arr) {
int indx = 0, endIndx = arr.length - 1, midIndx = 0;
while (midIndx <= endIndx) {
System.out.println("array current element is = " + arr[midIndx]);
if (arr[midIndx] == 0) {
int temp = arr[indx];
arr[indx] = arr[midIndx];
arr[midIndx] = temp;
indx++;
midIndx++;
}
/* if current element is 3, then swap it with endIndx */
else if (arr[midIndx] == 3) {
int temp = arr[midIndx];
arr[midIndx] = arr[endIndx];
arr[endIndx] = temp;
endIndx--;
}
/* in the current loop, only 0 and 3 will be considered, so for 1 and 2, just increment the index */
else if (arr[midIndx] == 1 || arr[midIndx] == 2) {
System.out.println("array current element is = " + arr[midIndx] + " ignore right now");
midIndx++;
}
}
while (indx <= endIndx) {
System.out.println("array current element is = " + arr[indx]);
if (arr[indx] == 2) {
int temp = arr[indx];
arr[indx] = arr[endIndx];
arr[endIndx] = temp;
endIndx--;
} else {
indx++;
}
}
System.out.println("arr = " + Arrays.toString(arr));
return arr;
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.wesome.dsalgo.CountPairsWithDifference.countPairsWithDifference;
class PairsWithDifferenceTest {
@Test
void countPairsWithDifferenceTest1() {
int[] arr = {3, 2, 1, 0, 2, 3, 1, 0};
Assertions.assertArrayEquals(new int[]{0, 0, 1, 1, 2, 2, 3, 3}, countPairsWithDifference(arr));
}
@Test
void countPairsWithDifferenceTest2() {
int[] arr = {3, 3, 3, 3, 2, 2, 2, 1, 1, 0};
Assertions.assertArrayEquals(new int[]{0, 1, 1, 2, 2, 2, 3, 3, 3, 3}, countPairsWithDifference(arr));
}
}
plugins {
id 'java'
id "io.freefair.lombok" version "6.4.1"
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}