Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
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 []
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> consequence = 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){
consequence.add(array1[i]);
j =array2.size;
}
}
}
Collections.type(consequence);
return consequence.toArray(new String[result.size()]);
}
}
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[] { "vigorous", "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[] { "vigorous", "alive", "harp", "sharp", "armstrong", "codewars", "cod", "code" };
String[] r = new String[] { "cod", "code", "ewar", "wars" };
assertArrayEquals(r, WhichAreIn.inArray(a, b));
}
}