Reputation: 1
This is my first post here so please bear with me. I'm self-teaching myself Java in attempts to prepare for a Computer Science course.I'm planning on taking next year and I was given a problem.
The problem tasks me to assign values to lower case letters with a = 1, b = 2...
to z = 26
. Then I will have write a method which given an array of strings String[] names
will sort them in terms of which array has the biggest value of letters added together. For example, "ed" would have the value 9 because e is 5 and d is 4.
Another example, given annie, bonnie, liz
the method will sort to bonnie, liz, annie
.
I'm kind of confused with how to approach this in terms of code and am looking for some help. Thanks in advance!
Upvotes: 0
Views: 44
Reputation: 63
You can use a code something like this.
public class J2 {
public static void main(String[] args) {
J2 j = new J2();
String s[] = {"annie", "bonnie", "liz"};
j.sortArray(s);
}
void sortArray(String[] arr2) {
int ww[] = new int[arr2.length];
//find the integer value total of words and put in to array
for (int i = 0; i < arr2.length; i++) {
String s = arr2[i];
char[] c = s.toCharArray();
int w = 0;
for (int j = 0; j < s.length(); j++) {
w += (int) c[j] - 96;
}
ww[i] = w;
}
// sort the array acordind to values
for (int i = 0; i < arr2.length; i++) {
for (int j = 0; j < arr2.length - 1; j++) {
if (ww[j] < ww[j + 1]) {
int t = ww[j];
ww[j] = ww[j + 1];
ww[j + 1] = t;
String s = arr2[j];
arr2[j] = arr2[j + 1];
arr2[j + 1] = s;
}
}
}
//print the array
for (int i = 0; i < arr2.length; i++) {
System.out.println(arr2[i]);
}
}
}
Upvotes: 0
Reputation: 2524
i am not going to solve the exact problem for you as you learn more by experimenting yourself... however you may take this inspiration
public class Sorting {
public static Map<Character, Integer> characters = new HashMap<Character, Integer>();
static{
characters.put('a', 1);
characters.put('b',2);
}
static class StringValue implements Comparable<StringValue> {
private Integer value = 0;
private String name = "";
public StringValue(String name){
this.name = name;
for(char aChar : name.toCharArray()){
value += Sorting.characters.get(aChar);
}
}
public int compareTo(StringValue o) {
return value.compareTo(o.value);
}
public String getName() {
return name;
}
public Integer getValue() {
return value;
}
}
public static void main(String [] args){
String [] values = {"bb", "a", "aa" , "abaa"};
List<StringValue> stringVals = new ArrayList<StringValue>();
for(String val : values){
stringVals.add(new StringValue(val));
}
Collections.sort(stringVals);
for(int i = 1; i <= stringVals.size(); i++){
StringValue aVal = stringVals.get(i-1);
System.out.println(aVal.getName() + " has value " + aVal.getValue() + " and rank " + i);
}
}
}
which outputs:
a has value 1 and rank 1
aa has value 2 and rank 2
bb has value 4 and rank 3
abaa has value 5 and rank 4
Upvotes: 1