Thursday, December 7, 2023
HomeSoftware EngineeringKind Phrases by Place Index in Java

Kind Phrases by Place Index in Java


The problem

Your process is to kind a given string. Every phrase within the string will include a single quantity. This quantity is the place the phrase ought to have within the end result.

Observe: Numbers could be from 1 to 9. So 1 would be the first phrase (not 0).

If the enter string is empty, return an empty string. The phrases within the enter String will solely include legitimate consecutive numbers.

Examples

"is2 Thi1s T4est 3a"  -->  "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2"  -->  "Fo1r the2 g3ood 4of th5e pe6ople"
""  -->  ""

The answer in Java code

Choice 1:

public class Order {
  public static String order(String phrases) {
    
    String[] _words = phrases.break up(" ");
    String[] out = new String[_words.length];

    for (int i=0; i<_words.size; i++) {
      for (Character c : _words[i].toCharArray()) {
        if (Character.isDigit(c)) {
          out[Character.getNumericValue(c)-1] = _words[i];
        }
      }
    }
    
    if (out.size<=1) return "";
    
    return java.util.Arrays.stream(out).accumulate(java.util.stream.Collectors.becoming a member of(" "));
  }
}

Choice 2:

import java.util.Arrays;
import java.util.Comparator;

public class Order {
  public static String order(String phrases) {
    return Arrays.stream(phrases.break up(" "))
      .sorted(Comparator.evaluating(s -> Integer.valueOf(s.replaceAll("D", ""))))
      .cut back((a, b) -> a + " " + b).get();
  }
}

Choice 3:

public class Order {
   public static String order(String phrases) {
        String[] arr = phrases.break up(" ");
        StringBuilder end result = new StringBuilder("");
        for (int i = 0; i < 10; i++) {
            for (String s : arr) {
                if (s.incorporates(String.valueOf(i))) {
                    end result.append(s + " ");
                }
            }
        }
        return end result.toString().trim();
    }
}

Take a look at instances to validate our answer

import static org.junit.Assert.*;
import org.junit.Take a look at;
import static org.hamcrest.CoreMatchers.*;

public class OrderTest {
  @Take a look at
  public void test1() {
    assertThat(Order.order("is2 Thi1s T4est 3a"), equalTo("Thi1s is2 3a T4est"));
  }
  
  @Take a look at
  public void test2() {
    assertThat(Order.order("4of Fo1r pe6ople g3ood th5e the2"), equalTo("Fo1r the2 g3ood 4of th5e pe6ople"));
  }
  
  @Take a look at
  public void test3() {
    assertThat("Empty enter ought to return empty string", Order.order(""), equalTo(""));
	}
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments