Software Engineering

The way to Kind the Present Code in Java

The way to Kind the Present Code in Java
Written by admin


The problem

Santa’s senior reward organizer Elf developed a option to symbolize as much as 26 presents by assigning a singular alphabetical character to every reward. After every reward was assigned a personality, the reward organizer Elf then joined the characters to kind the reward ordering code.

Santa requested his organizer to order the characters in alphabetical order, however the Elf fell asleep from consuming an excessive amount of scorching chocolate and sweet canes! Are you able to assist him out?

Kind the Present Code

Write a operate referred to as sortGiftCode that accepts a string containing as much as 26 distinctive alphabetical characters, and returns a string containing the identical characters in alphabetical order.

Examples (Enter => Output):

"abcdef"                       => "abcdef"
"pqksuvy"                      => "kpqsuvy"
"zyxwvutsrqponmlkjihgfedcba"   => "abcdefghijklmnopqrstuvwxyz"

The answer in Java code

Choice 1:

public class GiftSorter{
  public String sortGiftCode(String code){
    return code.chars()
      .sorted()
      .acquire(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
      .toString();
  }
}

Choice 2:

public class GiftSorter{
  public String sortGiftCode(String code){
    char[] chars = code.toCharArray();
    java.util.Arrays.kind(chars);
    return new String(chars);
  }
}

Choice 3:

import java.util.Arrays;
import java.util.stream.Collectors;

public class GiftSorter {
    public String sortGiftCode(String code) {
        return Arrays.stream(code.break up(""))
            .sorted()
            .acquire(Collectors.becoming a member of(""));
    }
}

Take a look at circumstances to validate our answer

import org.junit.Take a look at;
import static org.junit.Assert.assertEquals;

public class GiftSorterTest {
    @Take a look at
    public void Tests1() throws Exception {
        GiftSorter gs = new GiftSorter();
        assertEquals("kind fedcba", "abcdef", gs.sortGiftCode("fedcba"));
    }
       
    @Take a look at
    public void Tests2() throws Exception {
        GiftSorter gs = new GiftSorter();
        assertEquals("reverse alphabet", "abcdefghijklmnopqrstuvwxyz", gs.sortGiftCode("zyxwvutsrqponmlkjihgfedcba"));
    }
 
}

About the author

admin

Leave a Comment