Tuesday, April 23, 2024
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.Listing;

public class WhichAreIn {
    public static String[] inArray(String[] array1, String[] array2) {
        Listing<String> in = new ArrayList<>();
        for (String a : array1)
            for (String b : array2) if (b.comprises(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.comprises(x)))
      .distinct()
      .sorted()
      .toArray(String[]::new);
  }
}

Choice 3:

import java.util.*;

public class WhichAreIn { 
  public static String[] inArray(String[] array1, String[] array2) {
    Listing<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.kind(consequence);
    return consequence.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", "dwell", "robust" };
        String[] b = new String[] { "vigorous", "alive", "harp", "sharp", "armstrong" };
        String[] r = new String[] { "arp", "dwell", "robust" };
        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));
    }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments