2

I need to sort a string of words in an order those words are placed in the pattern array:

String[] pattern = {"Burger", "Fries", "Chicken", "Pizza", "Sandwich", "Onionrings", "Milkshake", "Coke"};

String s = "Chicken Coke Chicken Chicken Onionrings Coke Burger Milkshake Milkshake Burger Coke Milkshake Burger Onionrings Onionrings Coke Chicken Burger Fries Milkshake"; // input string

Expect

"Burger Burger Burger Burger Fries Chicken Chicken Chicken Chicken Onionrings Onionrings Onionrings Milkshake Milkshake Milkshake Milkshake Coke Coke Coke Coke" // output string
4
  • 1
    Do you have any code snippets of your attempt at this problem? Commented Aug 30, 2020 at 7:40
  • Also, what should happen if s does contain a word that is not in the pattern? Commented Aug 30, 2020 at 7:46
  • No, can't think of a way to do it Commented Aug 30, 2020 at 7:46
  • @Turing85 I've handled it in another method. I only need to sort the string in the order given in the pattern Commented Aug 30, 2020 at 7:48

4 Answers 4

5

You may use a List to be able to get index from word, then sort the words using these indexes

  • Get a List os the words to get them indexable
  • split your String into an array to be able to sort the words
  • sort them based on their indices in the List
  • join the words to get one String
// INPUTS
String s = "Chicken Coke Chicken Chicken Onionrings Coke Burger Milkshake Milkshake Burger Coke Milkshake Burger Onionrings Onionrings Coke Chicken Burger Fries Milkshake";
String expect = "Burger Burger Burger Burger Fries Chicken Chicken Chicken Chicken Onionrings Onionrings Onionrings Milkshake Milkshake Milkshake Milkshake Coke Coke Coke Coke";
String[] pattern = {"Burger", "Fries", "Chicken", "Pizza", "Sandwich", "Onionrings",
    "Milkshake", "Coke"};

// Get the patterns a list to get the indexOf method
List<String> listPatterns = Arrays.asList(pattern);

// Split in words
String[] values = s.split(" ");

//Sort base on index in list
Arrays.sort(values, Comparator.comparing(listPatterns::indexOf));

// Rebuild a string by joining
String result = String.join(" ", values);

// true
System.out.println(result.equals(expect));
Sign up to request clarification or add additional context in comments.

2 Comments

I have given boiler plate code snippet, both solution are correct it depends on @Arther what he needs.
@Natesh you can given an answer to something that haven't been asked, you may delete your post, that is not relevant to the question
1

Since the question does not contain any code, I will only post a rough sketch of a solution.

I would approach the problem by splitting the String in a list of words, then use a Comparator to sort those words and re-join them with separating blanks.

A common way to write Comparators is to assign the both objects compared against each other an int-value, subtract one from the other and return that as the comparison result.

In the Comparator, I would use the index of the two words compared against each other in the pattern-array as base for comparison.

Comments

0

Try this.

String[] pattern = {"Burger", "Fries", "Chicken", "Pizza", "Sandwich", "Onionrings", "Milkshake", "Coke"};

// make pattern to index map. {Burger=0, Fries=1, Chicken=2, ...}
Map<String, Integer> patternMap = IntStream.range(0, pattern.length).boxed()
    .collect(Collectors.toMap(i -> pattern[i], Function.identity()));

// sort words using patternMap
String s = "Chicken Coke Chicken Chicken Onionrings Coke Burger Milkshake Milkshake Burger Coke Milkshake Burger Onionrings Onionrings Coke Chicken Burger Fries Milkshake"; // input string
String[] result = Arrays.stream(s.split("\\s+"))
    .sorted(Comparator.comparing(word -> patternMap.get(word)))
    .toArray(String[]::new);

System.out.println(Arrays.toString(result));

output:

[Burger, Burger, Burger, Burger, Fries, Chicken, Chicken, Chicken, Chicken, Onionrings, Onionrings, Onionrings, Milkshake, Milkshake, Milkshake, Milkshake, Coke, Coke, Coke, Coke]

Comments

-1

here is code to sort alphabetically

public class MainProgram {

    public static void main(String[] args) {
        String temp;
        String[] pattern = {"Burger", "Fries", "Chicken", "Pizza", "Sandwich", "Onionrings", "Milkshake", "Coke"};
          //Sorting the strings
        for (int i = 0; i < pattern.length; i++) 
        {
            for (int j = i + 1; j < pattern.length; j++) { 
                if (pattern[i].compareTo(pattern[j])>0) 
                {
                    temp = pattern[i];
                    pattern[i] = pattern[j];
                    pattern[j] = temp;
                }
            }
        }
      //Displaying the strings after sorting them based on alphabetical order
        System.out.print("Strings in Sorted Order:");
        for (int i = 0; i <= pattern.length - 1; i++) 
        {
            System.out.print(pattern[i] + ", ");
        }
        
    }

}

4 Comments

That is not what is asked, at all
This code return your expected output.. anything else you want
This is not my post. And the expected output is "Burger Burger Burger Burger Fries Chicken Chicken Chicken Chicken Onionrings Onionrings Onionrings Milkshake Milkshake Milkshake Milkshake Coke Coke Coke Coke"
No it does not. The code sorts pattern. That is not the task at hand

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.