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> 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()]);
  }
}

Check instances 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[] { "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));
    }
}
See also  Why It Issues to Software program Evolution and Why All people Places It Off

Leave a Reply