Thursday, November 30, 2023
HomeSoftware EngineeringType Lexicographical Order of Substrings in Java

Type 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

Possibility 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);
    }
}

Possibility 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);
  }
}

Possibility 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){
              end result.add(array1[i]);
              j =array2.size;
            }
          }
      }
    Collections.kind(end result);
    return end result.toArray(new String[result.size()]);
  }
}

Take a look at circumstances to validate our answer

import org.junit.jupiter.api.Take a look at;
import static org.junit.jupiter.api.Assertions.*;

public class WhichAreInTest {
    @Take a look at
    public void test1() {
        String[] a = new String[]{ "arp", "reside", "robust" };
        String[] b = new String[] { "energetic", "alive", "harp", "sharp", "armstrong" };
        String[] r = new String[] { "arp", "reside", "robust" };
        assertArrayEquals(r, WhichAreIn.inArray(a, b));
    }
    @Take a look at
    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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments