Thursday, March 23, 2023
HomeSoftware EngineeringKind Lexicographical Order of Substrings in Java

# Kind Lexicographical Order of Substrings in Java

## The problem#

Given two arrays of strings `a1` and `a2` return a sorted array `r` in lexicographical order of the strings of `a1` that are substrings of strings of `a2`.

Instance 1:

`a1 = ["arp", "live", "strong"]`

`a2 = ["lively", "alive", "harp", "sharp", "armstrong"]`

returns `["arp", "live", "strong"]`

Instance 2:

`a1 = ["tarp", "mice", "bull"]`

`a2 = ["lively", "alive", "harp", "sharp", "armstrong"]`

returns `[]`

## The answer in Java code#

Choice 1:

``````import java.util.ArrayList;
import java.util.Record;

public class WhichAreIn {
public static String[] inArray(String[] array1, String[] array2) {
Record<String> in = new ArrayList<>();
for (String a : array1)
for (String b : array2) if (b.accommodates(a)) in.add(a);
return in.stream().distinct().sorted().toArray(String[]::new);
}
}
``````

Choice 2:

``````import java.util.stream.Stream;

public class WhichAreIn {
public static String[] inArray(String[] array1, String[] array2) {
return Stream.of(array1)
.filter(x -> Stream.of(array2).anyMatch(y -> y.accommodates(x)))
.distinct()
.sorted()
.toArray(String[]::new);
}
}
``````

Choice 3:

``````import java.util.*;

public class WhichAreIn {
public static String[] inArray(String[] array1, String[] array2) {
Record<String> end result = new ArrayList<String>();
for(int i=0; i<array1.size; i++){
for(int j=0; j<array2.size; j++ ){
if(array2[j].indexOf(array1[i]) >= 0){
j =array2.size;
}
}
}
Collections.type(end result);
return end result.toArray(new String[result.size()]);
}
}
``````

## Check circumstances to validate our resolution#

``````import org.junit.jupiter.api.Check;
import static org.junit.jupiter.api.Assertions.*;

public class WhichAreInTest {
@Check
public void test1() {
String[] a = new String[]{ "arp", "stay", "sturdy" };
String[] b = new String[] { "energetic", "alive", "harp", "sharp", "armstrong" };
String[] r = new String[] { "arp", "stay", "sturdy" };
assertArrayEquals(r, WhichAreIn.inArray(a, b));
}
@Check
public void test2() {
String[] a = new String[]{ "cod", "code", "wars", "ewar", "pillow", "mattress", "phht" };
String[] b = new String[] { "energetic", "alive", "harp", "sharp", "armstrong", "codewars", "cod", "code" };
String[] r = new String[] { "cod", "code", "ewar", "wars" };
assertArrayEquals(r, WhichAreIn.inArray(a, b));
}
}
``````
RELATED ARTICLES