0

I'm making a program which receives a string as input and returns the "sum" of the values for each letter of each word.

For example, my input of "Take advantage, do your best, don't stress.", would return:

do(19) take(37) dont(43) best(46) advantage(75) your(79) stress(100)

"do" would have a value of 19 because the letter "d" has a value of 4 (it is the fourth letter of the alphabet), and "o" has a value of 15, so the total is 19.

Now to store these values I have two arrays, one string array for each word, and one int array for the point value that they have. However, I only have this so far:

take(37) advantage(75) do(19) your(79) best(46) dont(53) stress(100) 

As you can see, it is not sorted in ascending order as I am trying to do. I display these values like this:

System.out.print(words[j] + "(" + points[j] + ")" + " ");

where words is the String array and points is the int array. How can I sort them?

My current code:

public static void main (String[] args)
{
    String input = "Take advantage, do your best, don't stress.";
    String output = "";


    //Get rid of all punctuation
    for(int i = 0; i < input.length(); i++){
        if(   ( (int)input.charAt(i) >= 65 && (int)input.charAt(i) <= 90) || (int)input.charAt(i) == 32  || ( (int)input.charAt(i) >= 97 && (int)input.charAt(i) <= 122)){

            //Handles Uppercase
            if(input.charAt(i) >= 65 && input.charAt(i) <= 90){
                int temp = (int)input.charAt(i) + 32;
                char c = (char)temp;
                output += c;
            }
            //Handles all other characters
            else{
                output += input.charAt(i);
            }
        }
    }
    //Done punctuation

    String[] words = output.split(" ");
    int[] points = new int[words.length];

    //Points assignment
    for(int j = 0; j < words.length; j++){
        for(int k = 0; k < words[j].length(); k++){
            points[j] += (int)words[j].charAt(k) - 96;
        }
        System.out.print(words[j] + "(" + points[j] + ")" + " ");
    }
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423

4 Answers4

1

How about storing your results in a Map<String,Integer> instead of two lists:

Map myMap = new HashMap<String,Integer>;

From there you can sort the Map by its values: Sort a Map<Key, Value> by values (Java)

Next you can iterate through the sorted map:

for(String s : myMap.keySet()){
    System.out.println(s+"("+myMap.get(s)+")");
}
Community
  • 1
  • 1
MAZDAK
  • 573
  • 1
  • 4
  • 16
1

If that is an option, your code can be made much simpler with Java 8.

First of all, removing punctuation can be done with a simple regular expression: you only want to keep letters, so we can just remove everything that is neither a letter nor a space. This is done by calling replaceAll("[^a-zA-Z\\s]", ""). After that, we can get a hold of all the words by splitting around "\\s+" (i.e. all whitespace characters).

Then, let's create a helper method returning the value of a String. As you have in your question, this would just be:

private static int value(String str) {
    return str.chars().map(c -> c - 'a' + 1).sum();
}

Finally, we need to sort the words array with a comparator comparing the value of each word. The comparator is created with the help of Comparator.comparingInt(keyExtractor) where the key extraction would be a function returning the value of a word. In this case, it could be expressed a lambda expression: word -> value(word).

To have the final output, we need to transform the words array into a String where each word is concatenated with its value in parentheses. This is done by creating a Stream<String> of the words (Arrays.stream(array)), sorting it according the comparator above (sorted(comparator)), mapping each word to the result of concatenating its value to it and finally collecting that into a String delimited by a space (Collectors.joining(delimiter)).

Whole code would be:

public static void main(String[] args) {
    String str = "Take advantage, do your best, don't stress.";
    String[] words = str.toLowerCase().replaceAll("[^a-zA-Z\\s]", "").split("\\s+");
    String output = 
        Arrays.stream(words)
              .sorted(Comparator.comparingInt(w -> value(w)))
              .map(w -> w + "(" + value(w) + ")")
              .collect(Collectors.joining(" "));
    System.out.println(output);
}

private static int value(String str) {
    return str.chars().map(c -> c - 'a' + 1).sum();
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
1

Use any of sorting algorithm and do sorting for both arrays. For example:

public static void bubbleSort(int[] numArray, String[] words) {

    int n = numArray.length;
    int temp = 0;
    String tt;

    for (int i = 0; i < n; i++) {
        for (int j = 1; j < (n - i); j++) {

            if (numArray[j - 1] > numArray[j]) {
                temp = numArray[j - 1];
                tt=words[j-1];
                numArray[j - 1] = numArray[j];
                words[j-1]=words[j];
                numArray[j] = temp;
                words[j]=tt;
            }

Then change last part of your main function to look like this:

    String[] words = output.split(" ");
    int[] points = new int[words.length];

    //Points assignment
    for(int j = 0; j < words.length; j++){
        for(int k = 0; k < words[j].length(); k++){
            points[j] += (int)words[j].charAt(k) - 96;
        }

    }
    bubbleSort(points,words);
    for(int j = 0; j < words.length; j++){
        System.out.print(words[j] + "(" + points[j] + ")" + " ");

    }
Zvonimir Peran
  • 701
  • 5
  • 9
  • 16
1

If you are not allowed to use Java 8 (else use @Tunaki's approach), create a Comparable object that keeps two values, a String (word) and an int (sum). Then, just add each word to a list and sort it using Collections.sort(yourList).

public class Word implements Comparable<Word>{

    private String word;
    private int sum;

    public Word(String word) {
        this.word = word;
        setSum();
    }

    private void setSum() {
        //your sum function, I just copy and paste it from your post
        for(int k = 0; k < word.length(); k++)
            sum += (int)word.charAt(k) - 96;
    }

    public String getWord() {
        return word;
    }

    public int getSum() {
        return sum;
    }

    @Override
    public int compareTo(Word o) {
        return this.sum > o.sum ? 1 : -1;
    }
}
Kostas Kryptos
  • 4,081
  • 2
  • 23
  • 24